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))
......
Related
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)
I have a long string of characters and not only am I trying to find if a substring of those characters exists within the larger string, I'm also trying to find the longest run of successive instances.
For example... in the code snippet below I've found that I can use "count" to see how many times the substring b appears in a. That result is 5. However, what I'm trying to identify is the longest successive run, which would be 3 (where 'abc' appears back to back to back in the middle). I'm having difficulty running through the logic of this one. Any advice would be appreciated.
a = "abcxyzabcabcabcxyzabcxyz"
b = "abc"
total = a.count(b)
print(total)
This should be fairly simple with a while loop:
def func(a, b):
n = 1
while b*n in a:
n += 1
return n - 1
One possible and naive solution is to use the python index function to identify the closest index of the substring. From there you can simply continue searching ahead for the substring until you find a point where it doesnt appear anymore, then call index again to skip ahead.
Example:
a = "abcxyzabcabcabcxyzabcxyz"
b = "abc"
curr_index = a.index(b)
longest_count = 0
current_count = 0
while curr_index < len(a):
if a[curr_index : curr_index + len(b)] == b:
curr_index += len(b)
current_count += 1
else:
if longest_count < current_count:
longest_count = current_count
try:
curr_index = a.index(b, curr_index)
except ValueError:
# Substring no longer found in string slice
break
current_count = 0
if longest_count < current_count:
longest_count = current_count
print(longest_count)
This just returns the longest repeating count, but it doesn't return the location where it starts. Adding that functionality, however, is trivial.
Keep calling a.index on b with the appropriate indices. If the index is the start of your subset, you're in the same run. Otherwise, start a new run:
def longest_run(string, pattern):
longest = 0
current = 0
start = 0
while True:
try:
ind = string.index(pattern, start)
if ind == start:
current += 1
else:
if current > longest:
longest = current
current = 1
start += len(pattern)
except ValueError:
return longest
You can use re.findall with a pattern that matches one or more times of b (use re.escape to prevent b from being interpreted as regex), then map the returning strings to len and pass them to max to obtain the length of the longest match, and then divide that length by the length of b to get the number of times b is repeated:
import re
max(map(len, re.findall('(?:%s)+' % re.escape(b), a))) // len(b)
string = input("Enter the string: ")
sub_string = input("Enter sub string: ")
count = 0
idx = 0
while string.count(sub_string, idx) != 0:
count += string.count(sub_string, idx)
idx = string.index(sub_string, idx)
idx += 1
if string.count(sub_string, idx) == 0:
print(count)
break
when i give this code input as follows:
ininini
ini
It prints output 4. I tried running debugger and found out that it is incrementing count with +2 in the first step instead of +1 and I couldn't figure out that. Any suggestions would be very much helpful.
Use:
count += 1
instead of
count += string.count(sub_string, idx)
string.count(sub_string, idx) is 2 initially, and that's why you end up adding 2 in first iteration (instead of intended 1), thereby getting a 1 more than expected.
What you need is to increment count by 1 in every iteration and if you make this change, you get 3 as output.
I would use a for loop instead:
string = input("Enter the string: ")
sub_string = input("Enter sub string: ")
count = 0
for index in range(len(string) - len(sub_string) + 1):
if string[index: index + len(sub_string)] == sub_string:
count += 1
print(count)
If you are tyring to reach to get the length of the string, just use
len(string)
I am writing this program to find the 13 adjacent digits in this number that, when added together, have the largest sum. When I run it, however, the b value does not start at 12; it starts at some obscenely high number and I cannot figure out why. Any idea why my a and b values are not incrementing correctly?
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
a = 0
b = 12
greatest = 0
while b != len(str(num)):
num = str(num)
newNum = num[a:b]
total = 0
for num in newNum:
num = int(num)
total += num
if total > greatest:
greatest = total
a+=1
b+=1
print(b)
print(greatest)
The main issue is that you are reusing num in the inner loop, which renders the "original" num wrong after the first run.
Additionally, if you want a 13 digits run-in, you'd better start with b = 13
And furthermore, there is no need for str(num) since it is already a string, and no need to change b along the program. You can also replace the inner loop with a sum upon map.
Here is what it should look like after these changes:
num = "731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
index = 0
run_in = 13
greatest = 0
while index + run_in < len(num):
num_slice = num[index: index + run_in]
slice_sum = sum(map(int, num_slice))
if slice_sum > greatest:
greatest = slice_sum
index += 1
print(greatest)
If you are into super functions, you can create the same effect with a list comprehension and a max closure, iterating all possible indexes (until the length of the number minus the run in):
greatest = max(sum(map(int, num[index: index + run_in])) for index in range(len(num) - run_in))
def largest(num, k):
num = str(num)
if len(num) < k: raise ValueError("Need a number with at least {} digits".format(k))
currsum = sum(int(i) for i in num[:k])
answer = currsum, 0
i = k+1
while i < len(num):
currsum -= int(num[i-k])
currsum += int(num[i])
if currsum > answer[0]: answer = currsum, i
i += 1
return answer
total, ind = largest(myNum, 13)
print("The maximum sum of digits is {}, starting at index {}".format(total, ind))
So I am working diligently on some examples for my homework and came across yet another error.
The original:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count
Ok. Looks simple.
I then used this code in a function name count and generalized it so that it accepts the string and the letter as argument.
def count1(str, letter):
count = 0
word = str
for specific_letter in word:
if specific_letter == letter:
count = count + 1
print count
This is where I'm still not sure what I'm doing wrong.
I have to rewrite this function so that instead of traversing the string, it uses the three-parameter version of find from the previous section. Which this is:
def find(word, letter, startat):
index = startat
while index <= len(word):
if word[index] == letter:
return index
index = index + 1
return -1
This is how far I got... but the program doesn't work the way I want it to.
def find(str, letter, startat):
index = startat
word = str
count = 0
while index <= len(word):
if word[index] == letter:
for specific_letter in word:
if specific_letter == letter:
count = count + 1
print count
index = index + 1
Can someone point me in the right direction. I want to understand what I'm doing instead of just given the answer. Thanks.
The point of the exercise is to use the previously defined function find as a building block to implement a new function count. So, where you're going wrong is by trying to redefine find, when you should be trying to change the implementation of count.
However, there is a wrinkle in that find as you have given has a slight error, you would need to change the <= to a < in order for it to work properly. With a <=, you could enter the body of the loop with index == len(word), which would cause IndexError: string index out of range.
So fix the find function first:
def find(word, letter, startat):
index = startat
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
And then re-implement count, this time using find in the body:
def count(word, letter):
result = 0
startat = 0
while startat < len(word):
next_letter_position = find(word, letter, startat)
if next_letter_position != -1:
result += 1
startat = next_letter_position + 1
else:
break
return result
if __name__ == '__main__':
print count('banana', 'a')
The idea is to use find to find you the next index of the given letter.
In your code you don't use the find function.
If you want to try something interesting and pythonic: Change the original find to yield index and remove the final return -1. Oh, and fix the <= bug:
def find(word, letter, startat):
index = startat
while index < len(word):
if word[index] == letter:
yield index
index = index + 1
print list(find('hello', 'l', 0))
Now find returns all of the results. You can use it like I did in the example or with a for position in find(...): You can also simply write count in terms of the length of the result.
(Sorry, no hints on the final function in your question because I can't tell what you're trying to do. Looks like maybe you left in too much of the original function and jumbled their purposes together?)
Here's what I came up with: This should work.
def find(word, letter, startat)
index = startat
count = 0
while index < len(word):
if word[index] == letter:
count = count + 1 ##This counts when letter matches the char in word
index = index + 1
print count
>>> find('banana', 'a', 0)
3
>>> find('banana', 'n', 0)
2
>>> find('mississippi', 's', 0)
4
>>>
Try using :
def find_count(srch_wrd, srch_char, startlookingat):
counter = 0
index = startlookingat
while index < len(srch_wrd):
if srch_wrd[index] == srch_char:
counter += 1
index += 1
return counter`
def count_letter2(f, l):
count = 0
t = 0
while t < len(f):
np = f.find(l, t)
if np != -1:
count += 1
t = np + 1
"I was wrong by doing t =t +1"
else:
break
return count
print(count_letter2("banana", "a"))
print(count_letter2("abbbb", "a"))