I am wondering if there is a way that I can compare the first letter of the string to the second; then the third to the forth ... etc.
At the moment I have this:
a=0
b=0
string = "GG EZ"
if string[a:b] == string[a+1:b+1]:
print("hello")
It works but is there a more efficient way of doing it?
You can use zip to pair up the elements
s = "GGEZ"
for a, b in zip(*[iter(s)]*2):
if a==b:
print('Hello')
More on this usage of zip here
string = "GG EZ abbdff"
for i in range(0, len(string), 2):
if string[i] == string[i+1]:
print("characters match")
Create a range of every second character in the string. Iterate over the range and compare character at the index i with the following.
Edit: If your string length is an odd number you run into an out of range exception. I let you figure that one out by yourself :)
Related
I have the first two strings in a string list strs that is guaranteed to have length of at least 2. I want to compare their letters against each other, and perform a task when their letters are identical. Here is the code I am using:
iter_len = len(strs[1])
if (len(strs[0]) >= len(strs[1])):
iter_len = len(strs[0])
for i in range (0, iter_len, 1):
if (strs[0][i] == strs[1][i]):
[do a thing]
However, when I run this, I get a IndexError: string index out of range for the if (strs[0][i] == strs[1][i]): line. I don't quite understand why this is happening, as the first if statement should ensure that iter_len is the minimum length between strs[0] and strs[1], and should prevent the index from going over. Any advice is much appreciated.
If you need to iterate through two sequences in lockstep, it's generally best practice to use zip:
for a,b in zip(strs[0], strs[1]):
if a == b:
#[do a thing]
This will deal with the issue of one sequence being longer than the other.
If you need the index, you can use enumerate with your zip:
for i, (a, b) in enumerate(zip(strs[0], strs[1])):
if a == b:
#[do a thing with i]
Suppose I have an string: s = "hello2020"
How can I create a program that returns the number of duplicates in the string? In this instance, the program would return 3 as the letter "l" appears more than once, and the numbers "2" and "0" also appear more than once.
Thanks in advance.
EDIT: So far, I have tried: return len([x for x in set(s) if s.count(x) > 1]), but it fails two of the testcases. Therefore, I am looking for an alternative solution.
from collections import Counter
def do_find_duplicates(x):
dup_chars = 0
for key,val in Counter(x).items():
if val > 1: dup_chars += 1
print(dup_chars)
do_find_duplicates('hello2020')
One Liner Solution, convert string to set then subtract length of string by converted set string
def duplicate_count(string):
return len(string) - len(set(string))
print(duplicate_count("hello2020"))
#3
i have to write a code for a class where i have to define a function, and the parameters come from an input(). the input is always going to be a string with numbers and letters following each other, in this form :""5 2 S 2 333 A" ". depending on the letter following the 2 numbers, i have to do use a certain function on the two previous numbers. for this i go through the string input and add each element to a list so it is easier to work with them. my issue is, that the first and last element of the last always start/end with a reverse backslash, making it impossible to int() the numbers, and i dont why and how to get rid of them. here is my code, if you know an easier way i would appreciate it but i mostly want to know where the backslashes come from...
def addition(a,b):
return a + b
def soustraction(a,b):
return a - b
def multiplication(a,b):
return a * b
if __name__ == '__main__':
c = input() #here comes the string input
ma_liste = [] #the list where i want to add the elements of my string
for i in range(0, len(c)): #checking each element of the string
if i == 0:
for j in range(len(c)):
if " " in c[i:j+2]:
ma_liste.append(c[i:j+1])
break
else:
for j in range(i,len(c)): #check if there is a space to know where the number ends
if c[i:j+1] == c[i-1:j+2].strip():
ma_liste.append(c[i:j+1])
break
for e in range(len(ma_liste)): #going through the elements of my list
if ma_liste[e].isdigit():
int(ma_liste[e])
if ma_liste[e].isalpha():
if ma_liste[e] == "S":
soustraction(int(ma_liste[e-2]),int(ma_liste[e-1]))
if ma_liste[e] == "A":
addition(int(ma_liste[e-2]),int(ma_liste[e-1]))
if ma_liste[e] == "M":
multiplication(int(ma_liste[e-2]),int(ma_liste[e-1]))
Welcome to SO. Seems like the issue here is that the end of the line '\n' gets appended when you read the data as it is directly. May be convert the whole ndarray to using numpy.asarray dtype=int. This will solve your problem. Hope it helps. :)
import numpy as np
a = ['1','2','3\n']
print(a)
b = np.asarray(a,dtype=np.int)
print(b)
input: ['1', '2', '3\n']
output: [1 2 3]
I am trying to create a loop where I can generate string using loop. What I am trying to achieve is that I want to create a small collection of strings starting from 1 character to up to 5 characters.
So, starting from sting 1, I want to go to 55555 but this is number so it seems easy if I just add them, but when it comes to alpha numeric, it gets tricky.
Here is explanation,
I have collection of alpha-numeric chars as string s = "123ABC" and what I want to do is that I want to create all possible 1 character string out of it, so I will have 1,2,3,A,B,C and after that I want to add one more digit in length of string so I can get 11, 12, 13 and so on until I get all possible combination out of it up to CA, CB, CC and I want to get it up to CCCCCC. I am confused in loop because I can get it to generate a temp sting but looping inside to rotate characters is tricky,
this is what I have done so far,
i = 0
strr = "123ABC"
while i < len(strr):
t = strr[0] * (i+1)
for q in range(0, len(t)):
# Here I need help to rotate more
pass
i += 1
Can anyone explain me or point me to resource where I can find solution for it?
You may want to use itertools.permutations function:
import itertools
chars = '123ABC'
for i in xrange(1, len(chars)+1):
print list(itertools.permutations(chars, i))
EDIT:
To get a list of strings, try this:
import itertools
chars = '123ABC'
strings = []
for i in xrange(1, len(chars)+1):
strings.extend(''.join(x) for x in itertools.permutations(chars, i))
This is a nested loop. Different depths of recursion produce all possible combinations.
strr = "123ABC"
def prod(items, level):
if level == 0:
yield []
else:
for first in items:
for rest in prod(items, level-1):
yield [first] + rest
for ln in range(1, len(strr)+1):
print("length:", ln)
for s in prod(strr, ln):
print(''.join(s))
It is also called cartesian product and there is a corresponding function in itertools.
Recently, I def a function which can compare two words in each wordlist. However, I also found some problems here.
def printcorrectletters():
x=0
for letters in correctanswer:
for letters2 in userinput:
if letters == letters2:
x = x+1
break
return x
In this function, if the correctanswer='HUNTING', and I input 'GHUNTIN', it will show 6 letters are correct. However, I want it compare words' letters 1 by 1. So, it should march 0. For example, 'H' will match first letter of userinput.. and so on.
I also think another function which can solve it by using 'zip'. However, our TA ask me to finish it without things like 'zip'.
If the strings are different lengths, you want to compare each letter of the shorter string:
shortest_length = min(len(correctanswer), len(userinput))
min just gives you the minimum of two or more values. You could code it yourself as:
def min(a, b):
return a if a < b else b
You can index a character in a string, using [index]:
>>> 'Guanfong'[3]
n
So you can loop over all the letter indices:
correct = 0
for index in range(shortest_length):
if correctanswer[index] == userinput[index]:
correct += 1
If you did use zip and sum:
correct = sum(1 for (correct_char, user_char) in zip(correctanswer, userinput)
if correct_char == user_char)
Python provides great facilities for simplifying ideas and for communicating with the computer and programmers (including yourself, tomorrow).
Without zip you can use enumerate() to loop over elements of correctanswer , and get index and element at the same time. Example -
def printcorrectletters():
x=0
for i, letter in enumerate(correctanswer):
if i < len(userinput) and letter == userinput[i]:
x = x+1
return x
Or if even enumerate() is not allowed, simply use range() loop till len(correctanswer) and get elements from each index.