so i have some code that works perfectly without a function. But i want to change this inside a function, but it does not work properly.
For example, i have the end="". This doesn't work in a function, without using print.
I also have more than one print statements. When i turn these to return, they don't work. So could someone please help me change this code to work in a function?
Thanks!
My code
def underscore_hash_staircase(number):
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
print(end=" ".replace(" ", "_"))
k = k - 1
for j in range(0, i + 1):
print("#", end="")
print("")
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
print('', end=' '.replace(" ", "_"))
j -= 1
k = 1
while k <= i:
print('#', end='')
k += 1
print()
i -= 1
print(underscore_hash_staircase(8))
so the code above doesn't work properly in a function, without the print statements. Please let me know how to get this working in a function without the print statements. Using returns. It should be exact output as what is being returned in this not function-working code.
Thanks again!
Since a function can only return one value, instead of printing, you want to add to a variable to return instead of printing. Try:
def underscore_hash_staircase(number):
returnValue = "" # start as empty string
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
returnValue += "_"
k = k - 1
for j in range(0, i + 1):
returnValue += "#"
returnValue += "\n" # adding a new line
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
returnValue += "_"
j -= 1
k = 1
while k <= i:
returnValue += "#"
k += 1
returnValue += "\n"
i -= 1
print(underscore_hash_staircase(8))
Edit: missed a print when replacing
The function should append to a string instead of printing, and then return the string. Append \n to add a newline.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
result += "_"
k = k - 1
for j in range(0, i + 1):
result += "#"
result += "\n"
else:
number = -number
i = number
while i >= 1:
j = number
while j > i:
result += "_"
j -= 1
k = 1
while k <= i:
result += "#"
k += 1
result += "\n"
i -= 1
return result
print(underscore_hash_staircase(8))
You also don't need all those inner loops. You can repeat a string by multiplying it.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(1, number + 1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
else:
number = -number
for i in range(number, 0, -1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
return result
print(underscore_hash_staircase(8))
print(underscore_hash_staircase(-8))
Related
When I debug my code, the value of the variables shows that they are equal to my limit condition but my while loop still works
I'm trying to stop my while loop by this limitation:
while (i + j) != len(fruits):
Even though (i+j) is equal to len(fruits), the loop still works, it doesn't break.
It should be broken when it meets my limitation.
My code is below:
from typing import List
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
pointed = [0 for i in range(max(fruits) + 1)]
maX, count = 0, 0
count_type = 0
i, j = 0, 0
while (i + j) != len(fruits):
while count_type < 3:
if pointed[fruits[i + j]] == 0:
count_type += 1
if count_type < 3:
count += 1
pointed[fruits[i + j]] += 1
j += 1
elif count_type < 3 and pointed[fruits[i + j]] != 0:
pointed[fruits[i + j]] += 1
count += 1
j += 1
if count > maX: maX = count
if pointed[fruits[i]] == 1: count_type -= 2
pointed[fruits[i]] -= 1
count -= 1
i += 1
j-= 1
return maX
fruits = input()
fruits = [int(i) for i in fruits.split()]
obj = Solution()
print(obj.totalFruit(fruits))
when I debug:
enter image description here
I have an assignment for my Python course that I'm struggling with.
We are supposed to make a function that prints out binary as follows:
If the input is:
chessboard(3)
It should print out:
101
010
101
And so forth..
Its a "simple" program but I'm really new to coding.
I can produce a while loop that writes out the correct length and amount of lines but I'm struggling to produce variation between the lines.
This is what I have come up with so far:
def chessboard(n):
height = n
length = n
while height > 0:
while length > 0:
print("1", end="")
length -= 1
if length > 0:
print("0", end="")
length -= 1
height -= 1
if length == 0:
break
else:
print()
length = n
With the input:
chessboard(3)
It prints out:
101
101
101
Could someone help me figure out how I could start every other line with zero instead of one?
As I understand it, it is simple :
print("stackoverflow")
def chessboard(n):
finalSentence1 = ""
finalSentence2 = ""
for i in range(n): #we add 0 and 1 as much as we have n
if i%2 == 0: #
finalSentence1 += "1"
finalSentence2 += "0"
else:
finalSentence1 += "0"
finalSentence2 += "1"
for i in range(n): #we print as much as we have n
if i%2 == 0:
print(finalSentence1)
else:
print(finalSentence2)
chessboard(3)
returns :
stackoverflow
101
010
101
I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
def chessboard(x):
i = 0
while i < x:
if i % 2 == 0:
row = "10"*x
else:
row = "01"*x
print(row[0:x])
i += 1
The question is to solve the following question in Sedgewick Wayne's Python book:
Given an array of integers, compose a program that finds the length and location of the longest contiguous sequence of equal values where the values of the elements just before and just after this sequence are smaller.
I tried on this problem, and encountered some problems.
Here are my codes:
import sys
import stdio
# Ask the user input for the list of integers
numList = list(sys.argv[1])
maxcount = 0
value = None
location = None
i = 1
while i < len(numList) - 1:
resList = []
count = 0
# If i > i-1, then we start taking i into the resList
if numList[i] > numList[i - 1]:
# start counting
resList += [numList[i]]
# Iterating through the rest of the numbers
j = i + 1
while j < len(numList):
# If the j element equals the i, then append it to resList
if numList[i] == numList[j]:
resList += [numList[j]]
j += 1
elif numList[i] < numList[j]:
# if j element is greater than i, break out the loop
i = j
break
else:
# if j element is smaller than i, count equals length of resList
count = len(resList)
if count > maxcount:
maxcount = count
value = resList[1]
location = i
i = j
else:
# if not greater than the previous one, increment by 1
i += 1
stdio.writeln("The longest continuous plateau is at location: " + str(location))
stdio.writeln("Length is: " + str(maxcount))
stdio.writeln("Number is: " + str(value))
The result shows:
python exercise1_4_21.py 553223334445554
The longest continuous plateau is at location: 11
Length is: 3
Number is: 5
python exercise1_4_21.py 1234567
The longest continuous plateau is at location: None
Length is: 0
Number is: None
But somehow, if the list given is in the format of having a group of continuous integers that is greater than the previous one, but then this group ends the list with no integer following it, my program simply doesn't end....
exercise1_4_21.py 11112222111444
Traceback (most recent call last):
File "exercise1_4_21.py", line 32, in <module>
if numList[i] == numList[j]:
KeyboardInterrupt
exercise1_4_21.py 111222211112223333
Traceback (most recent call last):
File "exercise1_4_21.py", line 25, in <module>
if numList[i] > numList[i - 1]:
KeyboardInterrupt
Not quite sure where the logical error is...thank you very much for your help and kindness!
Seems you overcomplicated the solution (while correctly selected key cases).
It requires only single run through the list.
def maxplat(l):
if (len(l)==0):
return 0, 0
start, leng = 0, 1
maxlen, maxstart = 0, 1
for i in range(1, len(l) + 1):
if (i == len(l)) or (l[i] < l[i-1]):
if (leng > maxlen):
maxlen, maxstart = leng, start
elif (l[i] == l[i-1]):
leng += 1
else:
start, leng = i, 1
return maxlen, maxstart
#test cases
print(maxplat([])) #empty case
print(maxplat([3])) #single element
print(maxplat([3,2,4,4,2,5,5,5,3])) #simple case
print(maxplat([3,2,4,4,2,5,5,5,6])) #up after long run
print(maxplat([3,2,4,4,2,5,5,5])) #run at the end
print(maxplat([3,3,3,3,2,4,4,2])) #run at the start
>>>
(0, 0)
(1, 0)
(3, 5)
(2, 2)
(3, 5)
(4, 0)
You need to add an extra check in your code to exit.
if j == len(numList):
maxcount = len(resList)
value = resList[1]
location = i
break
In your code it'll look like this:
import sys
import stdio
# Ask the user input for the list of integers
numList = list(sys.argv[1])
maxcount = 0
value = None
location = None
i = 1
while i < len(numList) - 1:
resList = []
count = 0
# If i > i-1, then we start taking i into the resList
if numList[i] > numList[i - 1]:
# start counting
resList += [numList[i]]
# Iterating through the rest of the numbers
j = i + 1
while j < len(numList):
# If the j element equals the i, then append it to resList
if numList[i] == numList[j]:
resList += [numList[j]]
j += 1
elif numList[i] < numList[j]:
# if j element is greater than i, break out the loop
i = j
break
else:
# if j element is smaller than i, count equals length of resList
count = len(resList)
if count > maxcount:
maxcount = count
value = resList[1]
location = i
i = j
#EXTRA CHECK HERE
if j == len(numList):
maxcount = len(resList)
value = resList[1]
location = i
break
else:
# if not greater than the previous one, increment by 1
i += 1
stdio.writeln("The longest continuous plateau is at location: " + str(location))
stdio.writeln("Length is: " + str(maxcount))
stdio.writeln("Number is: " + str(value))
I have written a code using recursion, but later realized that the depth is too high and does not work for higher level input values. It works completely fine without any issue.
def checkCount(first_window, index=0,reference_list=None):
reference_list = []
count = 0
while index<=len(first_window)-2:
if first_window[index] < first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(int((count*(count+1))/2))
count = 0
while index <= len(first_window)-2:
if first_window[index] > first_window[index+1]:
index += 1
count += 1
else: break
if count != 0:
reference_list.append(-int((count*(count+1))/2))
if index > len(first_window)-2: return reference_list
elif first_window[index] == first_window[index+1] and index<len(first_window)-2: index += 1
reference_list = reference_list + checkCount(first_window, index, reference_list)
return reference_list
import random
import time
start = time.clock()
input_array = list(map(int,"188930 194123 201345 154243 154243".split(" ")))
input_array = random.sample(range(1,100),10)
def main():
N = len(input_array)
K = 8
if K == 1: return None
print("Input array: ",input_array)
print("First Window",input_array[:K])
print("Real Output", checkCount(input_array[:K]))
if __name__ == "__main__":main()
Now no matter how I try without recursion, it ends with an infinite loop. I have tried different ways but no progress.
One way I have tried is taking out the recursion statement and returning the referencelist + index:
def checkCount(..):
....
....
return referencelist,index
while index <= K-2:
print("While",index)
reference_list, index = checkCount(new_input, index=0, reference_list=[])
referencelist += reference_list
The application is similar to the here. But we have to deal with tons of data where recursion cannot help. Assume that the input array is greater than 100,000. I am really struck here, I do not understand what logic am I missing. Any help will be grateful.
The first_window variable is only read, and the index variable is only incremented. There is no need for recursion, a simple loop can work.
def check_count(first_window):
reference_list = []
index = 0
while index < len(first_window) - 2:
count = 0
while index <= len(first_window) - 2:
if first_window[index] < first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(int((count * (count + 1)) / 2))
count = 0
while index <= len(first_window) - 2:
if first_window[index] > first_window[index + 1]:
index += 1
count += 1
else:
break
if count != 0:
reference_list.append(-int((count * (count + 1)) / 2))
if index < len(first_window) - 2 and first_window[index] == first_window[index + 1]:
index += 1
return reference_list
Of course, this algorithm can be optimised, for instance, we can avoid repetitions like: len(first_window) - 2.
I have a problem with loops and declaring variables. currently I am making a program about Collatz Conjecture, the program should check what is the biggest steps to reach one from certain amount of Collatz Sequence. here's my code :
start_num = int(input("insert a starting Number > "))
how_many = int(input("how many times you want to check? >"))
def even_or_odd(number):
if number % 2 == 0:
return 'isEven'
else:
return 'notEven'
def collatz(n):
z = n
counter = 0
while True:
if n != 1:
if even_or_odd(n) == 'isEven':
n = n/2
counter += 1
continue
if even_or_odd(n) == 'notEven':
n = (n*3)+1
counter += 1
continue
else:
print('number ' + str(z) + ' reached 1 with : ' + str(counter) + ' steps')
return counter
break
def check_biggest_steps(steps_before, steps_after):
if steps_before > steps_after:
return steps_before
if steps_after > steps_before:
return steps_after
if steps_after == steps_before:
return steps_after
def compute_collatz(n_times, collatz_number):
for _ in range(n_times):
before = collatz(collatz_number)
collatz_number += 1
after = collatz(collatz_number)
collatz_number += 1
biggest_steps = check_biggest_steps(before, after)
print('Biggest Steps is :' + str(biggest_steps))
compute_collatz(how_many, start_num)
this biggest_steps variable always return the last 2 steps. I know what causing this problem is that biggest_step variable located inside the loop but I can't get it working anywhere don't know what to do. Thanks
Don't read my code until you have tried it yourself.
Try to make a list that appends every change to a list, then to get the number of moves at the end, just get the length of the list.
.
def collatz(x):
while x != 1:
if x % 2 > 0:
x =((3 * x) + 1)
list_.append(x)
else:
x = (x / 2)
list_.append(x)
return list_
print('Please enter a number: ', end='')
while True:
try:
x = int(input())
list_ = [x]
break
except ValueError:
print('Invaid selection, try again: ', end='')
l = collatz(x)
print('\nList:', l, sep=' ')
print('Number of steps required:', len(l) - 1)
you didn't save your biggest_steps and compared always the last 2 only.
I would suggest following change.
def compute_collatz(n_times, collatz_number):
biggest_steps = 0
for _ in range(n_times):
steps = collatz(collatz_number)
if steps > biggest_steps:
biggest_steps = steps
collatz_number += 1
print('Biggest Steps is :' + str(biggest_steps))