In this code , I want the user to enter an integer number like n and enter n names. And I need to find the number of non-repeating letters in each name entered by the user and get the maximum between those numbers and print the maximum result, which is the number of non-repeating letters of the name that has the most non-repeating letters.
I have a problem in the part where I have to get the maximum number of each non-repeating letter in each name and I don't know how to do this:
n = int(input())
for i in range(n):
s = input()
t = ''
for ch in s:
if ch not in t:
t += ch
Have two set which keep track of letter which occur one time or multiple time
# your code goes here
n = int(input())
maxc_ = 0
word = ''
for i in range(n):
s = input()
count =0
seen_once = set()
seen_more = set()
for ch in s:
if ch not in seen_more:
if ch not in seen_once:
seen_once.add(ch)
count +=1
else:
seen_once.remove(ch)
seen_more.add(ch)
count-=1
if maxc_<count:
maxc_ = count
word = s
print(maxc_, word)
You can try this:
n = int(input())
q=[]
for i in range(n):
s = input()
b=0
for ch in s:
t=0
for j in range(0, len(s)):
if ch == s[j]:
t=t+1
if t==1:
b=b+1
q.append(b)
print("The maximum number of unrepeated letters is:", max(q))
Hope it works :)
def solve():
# solution goes here
n = int(input())
#to store the maximum non-repeating letter count
maximum = 0
for i in range(n):
s = input()
#to store the letter count appears only once in a name
count = 0
#to store the letter count of each name(size is 26 because we have 26 letters in English Alphabets)
nameLetterCount = [0]*26
for ch in s:
if(ord(ch) < 97):
#convating all in lower case letter(as name can have mixed case letters Upper/Lower)
ch = chr(ord(ch) + 32)
#storing the alphbet count
nameLetterCount[ord(ch) - ord('a')] += 1
for i in range(26):
if(nameLetterCount[i] == 1):
#update the currrent name letter count
count += 1
maximum = max(maximum, count)
print(maximum)
Related
I want to count number of same letter at beginning between two words (letter by letter) until there's one different and return who has the most same letter.
This is my code :
def same(word, liste):
letter = 0
dico = dict()
for i in liste:
while word[letter] == i[letter]:
letter += 1;
dico[i] = letter;
letter = 0;
same = max(dico, key=dico.get)
return same
But i get always this error of string index out of range, I've tried with much way but nothing
while word[letter] == i[letter]:
IndexError: string index out of range
In input :
same('hello',['hi,'hell','helo'])
Output:
'hell'
Thanks
I would just use a list comprehension along with basic substring logic:
def same(word, liste):
return max([x for x in liste if x in word], key=len)
print(same('hello',['hi','hell','helo'])) # hell
you can't go out of range in your while
verify the length of your word before word[letter] == i[letter]
while letter < len(word) and letter < len(i) and word[letter] == i[letter]:
gives you :
def same(word, liste):
letter = 0
dico = dict()
for i in liste:
while letter < len(word) and letter < len(i) and word[letter] == i[letter]:
letter += 1;
dico[i] = letter;
letter = 0;
same = max(dico, key=dico.get)
return same
print(same('blablabla',['blaze','bli']))
----------
>>> blaze
A combination of zip, sum and max should give you the result -
def same(word, liste):
pairs = [zip(word, x) for x in liste]
match_len = [sum([x == y for x, y in pair]) for pair in pairs]
return lst[match_len.index(max(match_len))]
Yet an other solution:
def same(word, liste):
def get_score(word, other):
for i, (l1, l2) in enumerate(zip(word, other)):
if l1 != l2:
break
return i
scores = {other:get_score(word, other) for other in liste}
return max(scores, key=scores.get)
In this case, I define the function get_score to count the number of common letters in a pair of words. I am sure to not run in IndexError because of the zip that makes an iterator over the 2 words.
Then I just did the same as you to get the word associated with the greatest score.
My code all work fine apart from the list at the very bottom "newList = [i + j for i, j in zip(numberString, products)]". I expected it to add all the elements within the two list without fault, sort of like this: [a9, b7, c5, d3, e1].
Instead i got this: "['[a', '[b', '9c', ',d', ' e']". Both lists are strings, so i'm not sure why they aren't concatenating properly.
# create an empty list for your products.
products = []
# Asking for the number of elements to be inputted.
n = int(input("Enter number of products you're buying : "))
# Some UI for the customer.
print("What are these products?")
# iterating until the range that has been chosen.
for i in range(0, n):
ele = input()
products.append(ele) # adding the element
def sort_numbers(number_list):
# sorts a list of valid numbers in descending numerical order
swaps = True
loopcount = len(number_list) - 1
while loopcount > 0 and swaps:
swaps = False
for i in range(loopcount):
if number_list[i] < number_list[i + 1]:
number_list[i], number_list[i + 1] = number_list[i + 1], number_list[i]
swaps = True
loopcount = loopcount - 1
def input_numbers(number_list):
# inputs shopping items and costs and stores them in two lists
user_input = input('Input a number of type Q to quit ')
while user_input.upper() != 'Q':
valid_number = False
while valid_number == False:
# use an exception handler to cover non-numeric input
try:
number_list.append(int(user_input))
valid_number = True
except ValueError:
print('Please enter a valid number')
user_input = input('Input a number or type Q to quit ')
user_input = input('input a number or type Q to quit ')
def totalise_numbers(number_list):
# sums us the list of numbers
total = 0
for i in range(len(number_list)):
total = total + number_list[i]
print('The total of the numbers is ', total)
print('The total of the numbers minus the smallest number is ', total - number_list[0])
# initialise the list
numbers = []
# call the function to create the list of numbers
input_numbers(numbers)
# sort the list in ascending order
sort_numbers(numbers)
# Totalise the numbers
totalise_numbers(numbers)
numberString = str([numbers])
# print the list of numbers
newList = [i + j for i, j in zip(numberString, products)]
print(newList)
print(numbers)
Replace the few bottom lines with this code.
numberString = numbers
# print the list of numbers
newList = [str(i) + j for i, j in zip(numberString, products)]
print(newList)
print(numbers)
1) The purpose of the code: I have coded an algorithm, which is supposed to give me the exact number, which is the most frequent and consecutive at the same time number.
2) What I have tried: I have tried to write the whole code, and actually managed to get that exact number. I have also added the frequency of that number, which is the output.
3) What I need: I am looking for the algorithm, which will identify the first starting index of those consecutive numbers. For example, if the input is 123777321, as an index number 3 is needed, the reason being 777 is the most frequent consecutive number in this input, it should find its "index", and also print it out.
The Code I have written:
def maxRepeating(str):
length = len(str)
count = 0
result = str[0]
for i in range(length):
current_count = 1
for x in range(i + 1, length):
if (str[i] != str[x]):
break
current_count += 1
if current_count > count:
count = current_count
result = str[i]
print("Longest same number sequence is of number {} by being repeated {} times in a row, with the first index starting at {}".format(result, count, i))
inputString = str(input("Please enter the string: "))
maxRepeating(inputString)
Example of an input: Please enter a string: 123777321
Example of an output: Longest same number sequence is of number 7 by being repeated 3 times in a row, with the first index starting at 3
Just add a variable to track the starting index of the best sequence.
def maxRepeating(str):
length = len(str)
count = 0
result = str[0]
start_ind = None
for i in range(length):
current_count = 1
for x in range(i + 1, length):
if (str[i] != str[x]):
break
current_count += 1
if current_count > count:
count = current_count
result = str[i]
start_ind = i
print("Longest same number sequence is of number {} by being repeated {} times in a row, with the first index starting at {}".format(result, count, start_ind))
inputString = str(input("Please enter the string: "))
maxRepeating(inputString)
From your comments, I assume you are trying to get the index at which the most frequently occurring element starts right?
Declare another variable like max_index and update it each time you update count and use that to print the index.
.....
max_index = 0
for i in range(length):
current_count = 1
for x in range(i + 1, length):
if (str[i] != str[x]):
break
current_count += 1
if current_count > count:
count = current_count
result = str[i]
max_index = i
print("Longest same number sequence is of number {} by being repeated {} times in a row, with the first index starting at {}".format(result, count, max_index))
......
My teacher challenged me of finding a way to count the occurences of the word "bob" in any random string variable without str.count(). So I did,
a = "dfjgnsdfgnbobobeob bob"
compteurDeBob = 0
for i in range (len(a) - 1):
if a[i] == "b":
if a[i+1] == "o":
if a[i+2] == "b":
compteurDeBob += 1
print(compteurDeBob)
but I wanted to find a way to do that with a word of any length as shown below, but I have no clue on how to do that...
a = input("random string: ")
word = input("Wanted word: ")
compteurDeBob = 0
for i in range (len(a)-1):
#... i don't know...
print(compteurDeBob)
a = input("random string: ")
word = input("Wanted word: ")
count = 0
for i in range(len(a)-len(word)):
if a[i:i+len(word)] == word:
count += 1
print(count)
If you want your search to be case-insensitive, then you can use lower() function:
a = input("random string: ").lower()
word = input("Wanted word: ").lower()
count = 0
for i in range(len(a)):
if a[i:i+len(word)] == word:
count += 1
print(count)
For the user input
Hi Bob. This is bob
the first approach will output 1 and the second approach will output 2
To count all overlapping occurrences (like in your example) you could just slice the string in a loop:
a = input("random string: ")
word = input("Wanted word: ")
cnt = 0
for i in range(len(a)-len(word)+1):
if a[i:i+len(word)] == word:
cnt += 1
print(cnt)
You can use string slicing. One way to adapt your code:
a = 'dfjgnsdfgnbobobeob bob'
counter = 0
value = 'bob'
chars = len(value)
for i in range(len(a) - chars + 1):
if a[i: i + chars] == value:
counter += 1
A more succinct way of writing this is possible via sum and a generator expression:
counter = sum(a[i: i + chars] == value for i in range(len(a) - chars + 1))
This works because bool is a subclass of int in Python, i.e. True / False values are considered 1 and 0 respectively.
Note str.count won't work here, as it only counts non-overlapping matches. You could utilise str.find if built-ins are allowed.
The fastest way to calculate overlapping matches is the Knuth-Morris-Pratt algorithm [wiki] which runs in O(m+n) with m the string to match, and n the size of the string.
The algorithm first builds a lookup table that acts more or less as the description of a finite state machine (FSM). First we construct such table with:
def build_kmp_table(word):
t = [-1] * (len(word)+1)
cnd = 0
for pos in range(1, len(word)):
if word[pos] == word[cnd]:
t[pos] = t[cnd]
else:
t[pos] = cnd
cnd = t[cnd]
while cnd >= 0 and word[pos] != word[cnd]:
cnd = t[cnd]
cnd += 1
t[len(word)] = cnd
return t
Then we can count with:
def count_kmp(string, word):
n = 0
wn = len(word)
t = build_kmp_table(word)
k = 0
j = 0
while j < len(string):
if string[j] == word[k]:
k += 1
j += 1
if k >= len(word):
n += 1
k = t[k]
else:
k = t[k]
if k < 0:
k += 1
j += 1
return n
The above counts overlapping instances in linear time in the string to be searched, which was an improvements of the "slicing" approach that was earlier used, that works in O(m×n).
Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then program should print
Number of times bob occurs is: 2
I wrote this program below.
s = 'azcbobobegghakl'
count = 0
if(s.find("b")):
p = s.index('b')
while p+2 <= len(s):
if(s[p+1] == 'o' and s[p+2] == 'b'):
count = count+1
p = s[p+2]
else:
p = s[p+1]
print (count)
But it shows errors on while loop. But if I don't use while loop, it runs without any error.
s = 'azcbobobegghakl'
count = 0
if(s.find("b")):
p = s.index('b')
while p+2 <= len(s):
if(s[p+1] == 'o' and s[p+2] == 'b'):
count = count+1
p = p+2
else:
p = p+1
print (count)
You have an error on incrementing p.
I would suggest using regexp for this though.
Try this:-
s = 'azcbobobegghakl'
count = 0
result = ''
ind = 0
for i in range(3,len(s),3):
result += s[ind:i]
if "bob" in result:
count+=1
ind = i
result = s[i-1]
print(count)