I have a list like Y Y Y N Y. I need to figure out the longest streak. The code
print(max(map(len,input().replace(' ','').split('N'))))
works but I need to do this without max and split.
The following code works for Y Y Y N and for N N N (results zero) but fails for Y Y N Y Y Y.
I need to somehow introduce a counter that is not set to 0 after the streak is broken and remember the largest streak
Y = 'Y'
temp = 0
streak = False
entry = input()
mylist = list(entry)
for i in range(0, len(mylist)):
if mylist[i] == Y:
streak = True
temp = temp + 1
else:
streak = False
#print (temp)
#temp = 0
print(temp)
I codded the general case of unknown input (not only N and Y), and without using built-in functions max or split by building an histogram and find out the maximum in it (take into calculation the case of several times the same letter as input), e.g:
input: insert string: yyttyyyy
entry = input("insert string: ")
mylist = list(entry)
hist = {} # string as key and int as value
lastItem = None
iterations_num = 0
for item in mylist:
if item == lastItem:
if item + str(iterations_num) in hist.keys():
hist[item + str(iterations_num)] = hist[item + str(iterations_num)]+1
else:
lastItem = item
iterations_num = iterations_num+1
hist[item + str(iterations_num)] = 1
max = 0
for amount in hist.values():
if amount>max:
max = amount
print(hist)
print(max)
output:
{'y1': 2, 't2': 2, 'y3': 4}
4
All you're missing is to reset the counter (temp) and check if it's greater than the current maximum (which you are missing) in the else part. The boolean streak variable is really unnecessary:
longest = 0
streak = 0
entry = input()
mylist = entry.split()
for elem in mylist:
if elem == 'Y':
streak += 1
else:
longest = max(longest, streak)
streak = 0
print(max(longest, streak))
Related
I am trying to arrange slashes in print statement to Graph like this
Below is skeleton of my code
y = input("Enter numbers (seperated by space): ")
y_arr = []
y_list = y.split()
for n in range(len(y_list)):
y_arr.append(int(y_list[n]))
space_no = 0
for x in range(len(y_arr)):
value = y_arr[x]
for z in range(value):
if (x%2 == 0):
print (" "*space_no,"\\")
space_no += 1
else:
print (" "*space_no,"/")
space_no += 1
Input statement take numbers and put it into list, then the slashes are generated based on the value of list item. For exa: if value is 2 then 2 slashes will be printed. Even index values go up, odd index values go down. Print statement is printing every character in new line but I want to arrange them like shown in graph.
How to achieve this?
code edited to Python 3
That sounds like homework, but here it is.
y_list = '0 3 1 2 3 6 2 3 6 2 3'.split()
y_arr = []
for n in range(len(y_list)):
y_arr.append(int(y_list[n]))
def cumulative(lists):
cu_list = []
length = len(lists)
cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]
return cu_list[1:]
space_up = 0
space_dn = 0
last_idx = -1
lines = ['']*max(cumulative([-x if i%2 == 0 else x for i,x in enumerate(y_arr)]))
for x in range(len(y_arr)):
value = y_arr[x]
for z in range(value):
if (x%2 == 0):
lines[last_idx] += (" "*space_dn+"\\")
space_dn = len(lines[last_idx])-len(lines[last_idx-1])
last_idx -= 1
space_up = 0
else:
last_idx += 1
lines[last_idx] += (" "*space_up+"/")
try:
space_up = len(lines[last_idx])-len(lines[last_idx+1])
except IndexError:
pass
space_dn = 0
print('\n'.join(lines[::-1]))
I'm having trouble trying to
compute x * y using only addition, printing the intermediate result for each loop iteration, and
printing the final number. This is my
teacher's example of what the output should look like
I could really use some help figuring it out,, I don't really understand how to yet.
Edit: I am a first time coder so I'm not very skilled, I do know the basics though (Also very new to this website) Here's what my code looks like so far:
x = int(input("Input positive x: "))
y = int(input("Input positive y: "))
z = 0
w = 0
if x < 0:
exit("Please input a positive number for x")
if y < 0:
exit("Please input a positive number for y")
def multiplier(number, iterations):
for i in range(1, iterations):
number = number + 3
print(number) # 12
multiplier(number=3, iterations=4)
My answer. Little shorter than the others.
Ok, try thinking of multiplication as adding a number with itself by x times. Hence, 3*4 = 3+3+3+3 = 12, which is adding 3 by itself 4 times
Replicating this with a for loop:
#inputs
x = 3
y = 4
#output
iteration = 1
result = 0
for num in range(4):
result += x
print(f'Sum after iteration {iteration}: {result}')
iteration += 1 #iteration counter
The resulting output will be:
Sum after iteration 1: 3 Sum after iteration 2: 6 Sum after iteration
3: 9 Sum after iteration 4: 12
The code is simple and straightforward,Check which number is bigger and iterate according to that number.
x = 3
y = 4
out = 0
if x > y:
for v in range(0,x):
out += y
print("after iteration",v+1, ":", out)
if y > x:
for v in range(0,y):
out += x
print("after iteration",v+1, ":", out)
print(x,"*", y, "=", out)
Use print to print inside the loop to show each number after adding and the number of iteration occurs.
Here is a start. This assume both arguments are integers 0 or more:
def m(n1, n1a):
n1b = 0
while n1a > 0:
n1b += n1
n1a -= 1
return n1b
n = m(9, 8)
print(n == 72)
I tried it a lot and I want to get occurrence of 4 without using count function
n = int(input()) #number of input
for i in range(n): #range
l = [] #list
x = int(input()) #input
while (x > 0): #innserting input into list
y = x % 10
x = x / 10
l.append(y)
z = 0
for i in l:
if (i == 4): # calculating no of occurrence
z = z + 1
print(z)
Here's a much simpler way of solving it.
number = int(input("Enter Number: "))
fours = [] #create list to store all the fours
for x in str(number): #loop through the number as a string
if x == '4': #check if the character if 4
fours.append(x) #add it to the list of fours
print("Number of fours: " + str(len(fours))) #prints the length of the array
Take integer input from a user and then delete the elements from an array having those many consecutive ocurences from the array.
Eg the input array is "aabcca" and the input from the user is 2.
Then the answer should be "ba".
I tried it when the elements are not repeated. My code works perfectly for examples like "aaabbccc".
for j in range(t, (n+1)):
if (t == n):
if (count == k):
array = [x for x in array if x != temp]
print array
exit()
if (t == n and count == k):
array = [x for x in array if x != temp]
print array
exit()
if temp == data[j]:
count += 1
t += 1
if temp != data[j]:
if count == k:
array = [x for x in array if x != temp]
temp = data[t]
count = 1
t += 1
you can use sliding window or two pointers to solve it.
the key point is use [start, end] range to record a consecutive seq, and only add the seq whose length less than n:
def delete_consecutive(s, n):
start, end, count = 0, 0, 0
res, cur = '', ''
for end, c in enumerate(s):
if c == cur:
count += 1
else:
# only add consecutive seq less than n
if count < n:
res += s[start:end]
count = 1
start = end
cur = c
# deal with tail part
if count < n:
res += s[start:end+1]
return res
test and output:
print(delete_consecutive('aabcca', 2)) # output: ba
print(delete_consecutive('aaabbccc', 3)) # output: bb
Hope that helps you, and comment if you have further questions. : )
Here is one way to do that:
def remove_consecutive(s, n):
# Number of repeated consecutive characters
count = 0
# Previous character
prev = None
# Pieces of string of result
out = []
for i, c in enumerate(s):
# If new character
if c != prev:
# Add piece of string without repetition blocks
out.append(s[i - (count % n):i])
# Reset count
count = 0
# Increase count
count += 1
prev = c
# Add last piece
out.append(s[len(s) - (count % n):])
return ''.join(out)
print(remove_consecutive('aabcca', 2))
# ba
print(remove_consecutive('aaabbccc', 2))
# ac
print(remove_consecutive('aaabbccc', 3))
# bb
I'm currently having an issue with my code. The program works properly but for some reason when I enter all positive numbers I receive an error for the last function. The last function is removing all the negative numbers from the list.
i=0
numList = []
x = int(input("Please enter number from -9999 to end:"))
while x > -9999:
i = i + 1
numList.insert(i,x)
x = int(input("Please enter number from -9999 to end:"))
if x == -9999:
print("The list of numbers entered:",(numList))
newList = numList[:]
secList = numList[:]
def posNumAvg(newList):
for e in newList[:]:
if e < 0:
newList.remove(e)
def negNumAvg(secList):
for y in secList[:]:
if y > 0:
secList.remove(y)
posNumAvg(newList)
negNumAvg(secList)
mydict = {'AvgPositive':(sum(newList)//len(newList)),'AvgNonPos': (sum(secList)//len(secList)),'AvgAllNum':(sum(numList)//len(numList))}
print("The dictionary with averages is:",mydict)
You are trying to compute the average of an empty list, which is not defined (specifically, the list's length is zero so you end up dividing by zero).
You need to decide what you want to do in that case and handle it specifically.
As an aside, you can rewrite
for e in newList[:]:
if e < 0:
newList.remove(e)
as
newList = [e for e in newList if e >= 0]
NOte: Never modify the list when you iterating over it. Let me make some changes to your code
numList = []
while True:
x = int(input("Please enter number from -9999 to end:")
if x == -9999:
print("The list of numbers entered:",(numList))
break
# you don't need i here, used append to insert element at last of list
# insert is used to insert a element at specific position
numList.append(x)
def posNumAvg(gotList):
list_negative = [] # will contain negative number
for e in gotList:
if e < 0:
list_negative.append(e)
return list_negative
def negNumAvg(gotList):
list_positive = [] # will contain positive number
for y in gotList:
if y >= 0:
list_positive.append(y)
return list_positive
list_positive = posNumAvg(numList)
list_negative = negNumAvg(numList)
mydict = {'AvgPositive':(sum(list_positive)//len(list_positive)),'AvgNonPos': (sum(list_negative)//len(list_negative)),'AvgAllNum':(sum(numList)//len(numList))}
print("The dictionary with averages is:",mydict)
you can get positive and negative number from one function: see this code
def neg_poss(gotList):
list_positive = [] # will contain positive number
list_negative = [] # will contain negative number
for y in gotList:
if y >= 0:
list_positive.append(y)
else:list_negative.append(y)
return list_positive,list_negative
list_positive,list_negative = neg_post(numList)