How can i make this condition work inside this while loop? - python

Have been trying to write some code that is supposed to read a string on a list and see if the string in question is present in a certain range, but the IF is just ignoring the WHILE loop entirely...
This is the full thing, i have no idea what is making this not work...
Thanks in advance
ls = list()
qt = int(input('How many numbers you want to analize: '))
for c in range(1,qt+1):
ls.append(input(f'Write the number you want to analize: '))
start = int(input('First digit: '))
end = int(input('Last digit: '))
i = 0
for c in range(start, end, 1):
n = str(c)
while i < len(ls):
if ls[i] in n:
print(n, end=' → ')
i += 1
print('Done')

The while loop is not beeing ignored. You have two main issues:
you do not reset i everytime the outside for loop enters a new iteration and because of that the part of the list which had already been checked for the first number is not beeing checked again for the next number. Move the i = 0 into the for loop and it will work as expected.
You are not including the last number when counting the range. If you want all numbers between two numbers to be checked you need to count up to end + 1.
my_list = []
quantity = int(input('How many numbers you want to analize: '))
for _ in range(1,quantity + 1):
my_list.append(input(f'Write the number you want to analize: '))
start = int(input('Start: '))
end = int(input('End: '))
for number in range(start, end + 1, 1):
i = 0
converted_number = str(number)
while i < len(my_list):
if my_list[i] in converted_number:
print(converted_number, end=' → ')
i += 1
print('Done')
Another issue you have in your code is that it is unreadable. You should always try to make your code is as easy to understand as possible. Never use single character variable names (apart from counting variables like i or maybe mathematical expressions like m*x + b but not! a*b*c if you are dealing with cuboids as the three sides are different, always use length, width and height in that case).
I changed the single character variable names in your code to descriptive names to make it easier to understand.

Related

Error with my random number generation code

My code it generates a random number it checks if it is in the list if it is it generates another random number and then it checks if it is equal or not and shows the result and repeats the process. But when I start the code it generated the normal number but it repeats the numbers and it shouldn't repeat the number. What do I do?
from random import randint
import os
n = 0
numsort = 14564487
attempt = 0
numbers = []
while n < 100:
num = randint(10000000, 99999999)
if num in numbers:
num = randint(10000000, 99999999)
numbers.append(num)
attempt += 1
if num == numsort:
print(f'{num}' + '\033[32m' + ' Right number' + '\033[0m')
print(f'After {attempt} attempts it was')
break
if num != numsort:
print(f'{num}' + '\033[31m' + ' Wrong number' + '\033[0m')
print(f'Attempt # {attempt}')
os.system('clear')
The issue here is a simple one. The primary problem is with this code snippet:
num = randint(10000000, 99999999)
if num in numbers:
num = randint(10000000, 99999999)
numbers.append(num)
Translating this to English, we have:
Generate a random seven-digit integer
If the integer is in our list of numbers then regenerate it and add it to the list
The problem you have here is that you have no guarantee that the regenerated number won't also be in the list. The chance of this happening will grow as the list grows. And, since your loop variable is never updated, this list will grow infinitely.
To fix this problem, you have two possible solutions. For small lists, you can continue on with your strategy of regenerating numbers and replace the if with a while:
num = randint(1000000, 9999999)
while num in numbers:
num = randint(1000000, 999999999)
numbers.append(num)
Note that this will only work while the desired size of your list is much smaller than the range of possible values being generated. As you fill up the list, the chance of collisions between the range of possible values and actual values will increase, causing the while loop to run longer.
Alternatively, you can use sample to choose your values, which would replace the entire loop:
numbers = random.sample(range(1000000, 10000000), n)
Note here that the use of range means that this is actually just as space efficient as the previous solution and will guarantee unique values.

Fibonacci sequence with numbers in 1 line and without using list or array [duplicate]

This question already has answers here:
How do I print a fibonacci sequence to the nth number in Python?
(8 answers)
Closed 2 years ago.
I'm very new to python and programming in general. This is the first year we have programming classes, so I'd say I started about a month ago.
We got our first assignment last week and I've managed to make most of the tasks, apart from the following one:
Generate n numbers from the Fibonacci sequence, where n is entered by the user.
Write these numbers to the screen.
Print the numbers on 1 single line.
Tip: print (value, end = '')
Do not use list or array.
This is the last question and this one is significantly more difficult than the others. I tried some things but non came close to doing what is asked. I genuinely have no clue how I'd even have to start.
In pseudocode:
First you need to check, print and save the results of fibonacci(0) and fibonacci(1)
Then make a loop to calculate the next fibonacci value using the last two calculated and print it.
Update the variables for the last two calculated.
Iterate steps 2 and 3 for each N>2
Thinking in python3:
# Print Fibonacci(0)
if n>=0:
print (1, end =', ')
f2 = 1
# Print Fibonacci(1)
if n>0:
print (1, end =', ')
f1=1
# Print Fibonacci(n) ; n>1
if n>1:
for i in range (2, n+1):
result = f1+f2
print(result, end=', ')
# updating last two variables
f2 = f1
f1 = result
Although not mentioned, you may want to 'memorize' previous Fibonacci numbers so you can generate the sequence faster.
def fibonacci(n, _cache={}):
if n in _cache: # Check to see if the number has been done
return _cache[n] # Return the pre-done number
elif n > 1:
return _cache.setdefault(n, fibonacci(n-1) + fibonacci(n-2)) # Call this function recursively to generate the previous Fibonacci numbers
return n
n = int(input("n = "))
for i in range(n):
print(fibonacci(i), end=', ')
You need to think about loops, how to iterate a set number of times, and use the print statement given to you in the "tip".
In pseudo code:
next_in_sequence = 1
loop_count = 1
while loop_counter <= number_entered:
next_in_sequence = caclulate_next_fibonacci(next_in_sequence)
print (next_in_sequence, end = '')
loop_counter = loop_counter + 1
Have a go at writing this in python, you'll have to write the caclulate_next_fibonacci function to work out the next number in the sequence. If you have any problems edit your question to show your code and ask for more help
To calculate the next Fibonacci number simply add together the two previous values. You can do this in a for loop using variables declared outside the loop to hold the previous two values.
Use this statement within your loop
print (value, end = '')
This will print the sequence all on one line with each value separated by a space.
n = int(input())
fib0 = 0
fib1 = 1
for x in range(0, n):
nextFib = fib0 + fib1
fib0 = fib1
fib1 = nextFib
print(fib0 , end = ' ')

one while loop to count up and down

How do you write a program to count up and down from a users integer input, using only one while loop and no for or if statements?
I have been successful in counting up but can't seem to figure out how to count down. It needs to look like a sideways triangle also, with spaces before the number (equal to the number being printed).
this is my code so far;
n = int(input("Enter an integer: "))
i = " "
lines = 0
while lines <= n-1:
print(i * lines + str(lines))
lines += 1
You can solve this by making good use of negative numbers and the absolute value: abs() which will allow you to "switch directions" as the initial number passes zero:
n = int(input("Enter an integer: "))
s = " "
i = n * -1
while i <= n:
num = n - abs(i)
print(s * num + str(num))
i += 1
This will produce:
Enter an integer: 3
0
1
2
3
2
1
0
Move the print line to after the while loop. Form a list of lists (or an array) in the while loop using the content from your current print statement. Then create a second statement in your single while loop to count down, which creates a second list of lists. Now you can sequentially print your two lists of lists.

countdown from 200 to 0 in multiples of x. X is a value input by the user (python)

I wanted to make a program that counts down from 200 to 0 in multiples of "x". "x" is a number that the user inputs. For example, if the user inputs "5", I want the program to print a list that begins with 200,195,190,185,180... and ends with 0. This is the code I have written so far:
rows = int(input('What number? '))
i = 1
for i in range(200,-1,rows):
print (200- i * rows)
i = i + 1
Right now it's telling me that "for i in range" can only have one argument, but when I make the argument 0, it doesn't run. When I make the argument 200, the program subtracts "x" from two hundred 200 times. How can I get the program to stop the list at 0?
What you need to do is negate rows like this:
rows = int(input('What number? '))
for i in range(200, -1, -rows):
print(i)
You don't have to increment i manually in Python.
range(a, b, step) is a range from a inclusive to b exclusive with preset step. Please see.
For your purpose, the following would be suitable:
print(i) for i in reversed(range(1, 200+1, x))
You can use this code
rows = int(input('What number? '))
i = 1
for i in range(1, int(200/rows)+1):
print (200- i*rows)

Addition carries in Python

number1 = int(input('Number #1: '))
number2 = int(input('Number #2: '))
l = len(str(number1))
l1 = len(str(number2))
print()
def addition():
print(' ',max(number1,number2))
print('+')
print(' ',min(number1,number2))
print('-'*(max(l,l1)+2))
print(' ')
print(' ',number1+number2)
def carries():
while (int(str(number1)[::-1])+int(str(number2)[::-1]))>=10:
carries = 0
carries = carries + 1
return carries
addition()
print()
print('Carries : ',carries())
I am trying to make a program that does the addition of two user input numbers and calculates the answer while also stating how many carries there are. Carries being if 9+8=17, then there would be 1 carry and so forth. I am having issues with having my program go beyond 1 carry. So this program so far is only applicable for user input numbers that when added are below 99. If you could explain to me how I would go about altering this program to make it applicable to any numbers, that would be great. I was thinking about using the len(number1) and len(number2) and then inputting the string of the user input backwards so it would look like str(number1[::-1])) but I do not think it works like that.
Fun one-liner solution
def numberOfCarryOperations(a, b):
f=lambda n:sum(map(int,str(n)));return(f(a)+f(b)-f(a+b))/9
# f is the digitSum function :)
Explanation
Asserting a,b >=0, you can proof mathematically: every time you have a carry, the digitSum decreases by 9.
9, because we are in number system 10, so we "lose 10" on one digit if we have carry, and we gain +1 as the carry.
Readable solution
def digitSum(n):
return sum(map(int,str(n)))
def numberOfCarryOperations(a, b)
# assert(a >= 0); assert(b >= 0);
return (digitSum(a) + digitSum(b) - digitSum(a+b)) / 9
I rewrote your carry function so it works, but the implementation is totally different. You first make the numbers strings so you can iterate through them. Then you make them equal length by appending 0's, and loop through each digit to check whether their sum (plus the carry) is over 9. If it is, increment the counter. Hope this helps:
number1 = int(input('Number #1: '))
number2 = int(input('Number #2: '))
l = len(str(number1))
l1 = len(str(number2))
print()
def addition():
print(' ',max(number1,number2))
print('+')
print(' ',min(number1,number2))
print('-'*(max(l,l1)+2))
print(' ')
print(' ',number1+number2)
def carries():
num1 = str(number1)
num2 = str(number2)
carry = 0
carries = 0
c1 = l
c2 = l
if (l < l1):
while (c1 < l1):
num1 = '0' + num1
c1+=1
if (l1 < l):
while (c2 < l):
num2 = '0' + num2
c2+=1
i = c1
while (i > 0):
if (int(num1[i-1])+int(num2[i-1])+carry > 9):
carry = 1;
carries+=1
else:
carry = 0
i-=1
return carries
addition()
print()
print('Carries : ',carries())
Edited with quick fix
Your while loop is fatally flawed.
You set carries to 0 every time, and then add 1, so there's no way to return anything but 0.
The return is inside the loop, so you will always return after the first iteration.
If the ones digits don't provide a carry, then you never get into the loop, and return None.
You don't provide for multiple carries, such as the three carries in 999 + 1.
If you remove the return from the while loop, you have an infinite loop: the terms of the condition never change. You don't iterate through anything.
You gave a function and a variable the same name. This is not good practice.
Here's a start for you, based loosely on your original routine.
Set the count of carries to 0.
Convert the two numbers to strings and find the common (shorter) length.
So long as you have digits in both numbers, grab the digits (moving from the right end) and see whether their numeric sum requires a carry. If so, increment the count.
def carries():
carry_count = 0
str1 = str(number1)
str2 = str(number2)
for digit_pos in range(1, min(len(str1), len(str2)) + 1):
if int(str1[-digit_pos]) + int(str2[-digit_pos]) >= 10:
carry_count += 1
return carry_count
Sample output:
Number #1: 77077
Number #2: 4444
77077
+
4444
-------
81521
Carries : 3
This still has deficiencies for you to fix. Most notably, it doesn't handle multiple carries. However, it should get you moving toward a solution.

Categories