Reason for result of output of Python code - python-3.x

why the while loop is executing more times than expected in printing a pascal triangle?
every time the while loop is executed x is incremented by 1 whereas n remains the same
I just started learning python
please help
memo = {0:1}
def fac(n):
if n not in memo:
memo[n] = n*fac(n-1)
return memo[n]
else:
return memo[n]
def pascal(x, space):
while(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
pascal(x, space)
n = eval(input())
space = n
x = 0
pascal(x, space)

You are using two methods to iterate through the numbers in the pascal function, a while loop, and a recursive call. You just need one of them.
Keeping the while loop:
def pascal(x, space):
while(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
Keeping the recursive call, turning the while into an if:
def pascal(x, space):
if(x <= n):
for j in range(space):
print(" ", end = "")
for i in range(0, x+1):
print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
print("\n", end = "")
x += 1
space -= 1
pascal(x, space)
Given 3 as input, both versions print the following:
1
1 1
1 2 1
1 3 3 1

Related

I wrote a code segment which supposed to work like an bubble sorting algorithm but it doesn't like "1" string

I've been studying in Hackerrank. Question wants me to sort an given array. I know there is some library functions for those but since i don't know any yet, i've tried to write it manually.
Sample input:
15 43 3 2 150
Sample output:
150 2 3 43 15
I've wanted to write a code starts reading the string from the right and stops when it finds a blank. Than adds the string before the blank to the final result. Then keeps going untill it reaches to the [0].
Here's my code:
sortedResult = ""
tempNumbers = ""
tempCount = 0
numbers = input()
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in range(-1, 11):
tempCount += 1
continue
else:
for counter2 in range(counter, counter + tempCount + 1):
tempNumbers += numbers[counter2]
sortedResult += tempNumbers
tempNumbers = ""
tempCount = 0
else:
for counter3 in range(counter, counter + tempCount + 1):
sortedResult += numbers[counter3]
print(sortedResult)
You appear to be sorting a string, not a list of numbers. To fix this, change the input line to numbers = [int(x) for x in input().split(" ")]. In addition, you should change tempNumbers and sortedResult to lists and use .append() instead of +=.
Final code:
sortedResult = []
tempNumbers = []
tempCount = 0
numbers = [int(c) for c in input().split(" ")]
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in range(-1, 11):
tempCount += 1
continue
else:
for counter2 in range(counter, counter + tempCount + 1):
tempNumbers.append(numbers[counter2])
sortedResult += tempNumbers
tempNumbers = []
tempCount = 0
else:
for counter3 in range(counter, counter + tempCount + 1):
sortedResult.append(numbers[counter3])
print(sortedResult)
Here's my final code. It is working and it works as the way i intented it to.
sortedResult = ""
tempNumbers = ""
tempCount = 0
numbers = input()
firstTenNumbers= "0123456789"
for counter in range(len(numbers) - 1, -1, -1):
if counter != 0:
if numbers[counter] in firstTenNumbers:
tempCount += 1
continue
else:
sortedResult += numbers[slice(counter + 1, tempCount + counter + 1)] + " "
tempCount = 0
else:
sortedResult += numbers[slice(tempCount + 1)]
tempCount = 0
print(sortedResult)

I have to write a code for pattern recognition and replacing the pattern?

I have this problem statement where I have a column of patterns that were if the first four bytes have date it should replace those four bytes to ccyy and the rest to N and zeros to Z's
eg. 20190045689 -> CCYYZZNNNNN
if space we need to consider the space as well.
66-7830956 -> NN-NNNZNNN
def patternGeneration(string):
x = re.findall("[\s0-9a-zA-Z]", string)
n = len(x)
j = 0
r = re.compile("\A[^(19|20)]")
y = list(filter(r.match, x))
b = len(y)
for i in range(0, b):
if y[i] == "0":
y[i] = 0
elif y[i] == " ":
y[i] = " "
else:
y[i] = "n"
print(convert(y))
for i in range(0, n):
if x[i] == "0":
x[i] = 0
j = j + 1
elif x[i] == " ":
x[i] = " "
j = j + 1
else:
x[i] = "n"
print(convert(x))
str1 = input("enter the string\t")
patternGeneration(str1)
#convert to new format
def convert(string):
# check for year
head = string[:4]
tail = string[4:]
if head.isnumeric():
if 1900 <= int(head) <= 2099:
head = "CCYY"
new_string = head + tail
return "".join(["Z" if x == "0" else "N" if x.isnumeric() else x for x in str(new_string)])
sample = "20196705540"
print(convert(sample))
#"CCYYNNZNNNZ"
sample = "66-7830956"
print(convert(sample))
#"NN-NNNZNNN"

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

python3 pattern program diagonal

HOW IT SHOULD LOOK ALIKE
I want pattern to be like this, but I couldn't come up with the loops ((
rows = int(input("number of rows: "))
space = rows - 1
n = 5
for i in range(0, rows):
for j in range(0, space):
print("", end=" " * n)
for j in range(0, i + 1):
print("*", end=" " * n)
space = space - 1
print()
space = 1
for i in range(rows - 1, 0, +1):
for j in range(space, 0):
print(" ", end=" ")
for k in range(0, i - 1):
print("*", end=" " * n)
space = space + 1
print()
rows = int(input("number of rows: "))
width = int(input("width of your window: "))
space = 9 # space between stars
for i in range(rows):
string = " " * (i % space)
for j in range(width):
if j % space == 0:
string += "*"
else:
string += " "
print(string)

Given a positive integer, determine if it's the nth Fibonacci number for some n

I try to find out the index of a certain Fibonacci number. However my program returned to me this result "Your program took too long to execute. Check your code for infinite loops, or extra input requests" after typing in 1134903171.
num = 1
num_prev = 1
n = int(input())
i = 1
if n < 2:
print(1, 2)
else:
while i <= n + 2:
num_prev, num = num, num + num_prev
i += 1
if n == num:
print(i + 1)
break
elif i == n + 3:
print(-1)
#break`
Thank you guys. The problem of last code is that: if the number isn't a Fibonacci number and meanwhile it is too large, it will took to many loops for the calculation. As I used a web compiler to calculate, they do not allow such "infinity" loop to operate. Then I used a math methode to limite the loop.
import math
N=int(input())
root1=math.sqrt(5*N*N+4)
root2=math.sqrt(5*N*N-4)
i=1
num, num_prev = 1, 1
if root1%1==0 or root2%1==0:
while i <= N+2:
num_prev,num = num,(num+num_prev)
i+=1
if N==num:
print(i+1)
break
else:
print(-1)
But the best answer could be:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)

Resources