I am stuck with 2 ways of how to use for and while loops in listing values to empty lists.
Example 1.
Creating a function that takes in user's input and lists positive decimal values in a list UNTIL user inserts negative value. Then listing ends and the last value should be this negative value. How the output should look like:
Add a number to the list:
1.5
Add a number to the list:
5.2
Add a number to the list:
6
Add a number to the list:
-2
The list: [1.5, 5.2, 6.0, -2.0]
My tryout that didn't work out
list = []
positive = float(input("Add number to put it in list:"))
while positive > 0:
list.append(positive)
else:
print(list)
Example 2
Another problem about using for loop and range() together: How to list first 20 even numbers starting from number 2. At the end of function print out the list with 20 values.
My tryout that didn't work out
emptylist = []
for days in range(40):
if days % 2 == 0:
print(emptylist)
Thanks already in advance to help me solve these applications! :)
You need to ask for the user input inside the loop
numbers = []
num = 1
while num > 0:
num = float(input("Add number to put it in list:"))
numbers.append(num)
else:
print(numbers)
As a side note, don't use list as a variable, it's a built-in name.
You must replace your while with an if else
positive=1
list = []
while(positive):
positive = float(input("Add number to put it in list:"))
if positive > 0:
list.append(positive)
else:
print(list)
Answer for part-I:
output_list = []
isPositive=True
while(isPositive):
num = float(input())
if (num > 0):
output_list.append(num)
else:
isPositive=False
output_list.append(num)
break
print (output_list)
Answer for part-II:
>>> n=20
>>> for num in range(2,n*2+1,2):
... print(num)
...
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
Related
A sequence of numbers is called cute if all the numbers in the sequence are made of only two digits, 8 and 9.
Example of a cute sequence is: 8, 9, 88, 89, 98, 99…. and so on.
A number is called beautiful if it is divisible by any number which is part of the cute sequence.
For example: 8 (divisible by 8), 9(divisible by 9), 889 (divisible by 889), 10668 (divisible by 889) are beautiful numbers. Given a number, n, write a code to print “beautiful” (without quotes) if it is divisible by any number that contains only 8 or 9 or both and print -1 otherwise.
This is the python code which i tried:
I used a for loop from 8 to n/2 and i used regex to check if the number contains only 8 and 9. This code is working fine for smaller numbers, for larger numbers it is giving Time limit exceeded! Is there any efficient solution for this question ?
import re
n=int(input())
l="^[8-9]+$"
x=0
if re.match(l,str(n)):
print("beautiful")
else:
for i in range(8,int(n/2+1),1):
if re.match(l,str(i)) and n%i==0:
print("beautiful")
x=1
break
if x==0:
print(-1)
There is a function that generates all cute number with specified maximum length:
from collections import deque
elements = ["8", "9"]
def all_cute_numbers(max_len):
prefixes = deque(elements)
while prefixes:
p = prefixes.popleft()
yield p
if len(p) < max_len:
for el in elements:
prefixes.append(p + el)
numbers = all_cute_numbers(3)
print(list(numbers))
You can loop over it and check that some of number divide your input n
n = int(input("enter the number "))
s = str(n)
print(len(s))
k = [] a = [8,9]
flag = 0
#generate cute sequence numbers by appending 8 and 9 to the already generated numbers
while True:
x = (a[0]*10) + 8
a.append(x)
y = (a[0]*10) + 9
a.append(y)
#check whether the generated number divides the given number
if ((n%x==0) or (n%y==0)):
flag = 1
print("beatiful")
break
if (len(str(y))>len(s)):
break
k.append(a[0])
a.pop(0)
print(k)
if (flag==0):
print("-1")
I'm trying to create a multiplication table. The user enters their list of numbers and the program spits out the multiplication for each number. for example,
3 x 1 = 3
3 x 2= 6
3 x 3 = 9
......
.....
3 x 12=42
this is what I have tried so far:
enter code here
N = int(input("How many numbers would you like to multiply?:"))
num = []
q=1
p = 1
count=0
for i in range(0,N):
add = int(input(f"number {i}:"))
num.append(add)
print(num)
for j in num:
while q <= 12:
print (j * q, end=" ")
q+=1
#The result is
How many numbers would you like to multiply?:3
number 0:2
number 1:6
number 2:5
[2, 6, 5]
2 4 6 8 10 12 14 16 18 20 22 24
enter code here
How do I get the program to spit out all the multiplication for every number in the list?
Store your tables in a dictionary and call in any way you want. See below code:
def inputmethod():
N = int(input("How many numbers would you like to multiply?:"))
num = []
for i in range(0,N):
add = int(input(f"number {i}:"))
num.append(add)
return num
def multiplication(m,num):
L = list(range(1,m+1))
dict_tables = {}
for n in num:
dict_tables[n] = [e*n for e in L]
return dict_tables
def print_tables(dict_tables):
for key,value in dict_tables.items():
print(f"Table of {key} is : {value}")
num = inputmethod()
generate_tables = multiplication(12,num)
print_tables(generate_tables)
Here's how (and why) I would have written that:
# More verbose variable names are nice documentation!
num_count = int(input("How many numbers would you like to multiply?:"))
numbers = []
# Start at 1 instead of 0, because humans are used to counting from 1.
for i in range(1, num_count + 1):
number = int(input(f"number {i}:"))
numbers.append(number)
print(numbers)
# Loop across the list of numbers you built in the previous step.
for number in numbers:
# `for i in range(...)` is the canonical Python way to loop over numbers.
for i in range(1, 13):
print(number * i, end=" ")
print()
Alternatively:
...
for i in range(12):
print(number * (i + 1), end=" ")
...
gets the same result, but I find it a lot simpler to iterate over the actual list of numbers I want to use, especially in more complex formulas where you're referring to that variable more than once. For instance, if you were calculating squares and writing number * (i + 1) * (i + 1), and you were my coworker, I would wag my finger at you.
im doing this exercise basically to add the first 2 integers in a list in python, but my script shows it runs the for loop twice before it iterates to the next integer in a list.
my code is below, i added a print statement so i can see how it iterates the FOR loop inside a WHILE loop.
def add2(nums):
count = 0
ans = 0
while count <= 2:
count += 1
print(f'count: {count}')
for x in nums:
ans += x
print(f'ans: {ans}')
HOwever if i run my code, i get this result. Why is it adding the value of ans twice before it goes to the next iteration?
add2([2,3,5])
count: 1
ans: 2
ans: 5
ans: 10
count: 2
ans: 12
ans: 15
ans: 20
count: 3
ans: 22
ans: 25
ans: 30
You don't need to overcomplicate this. Just use slicing to return the first to elements of the list.
simpler code
listNums = [1,2,3,4]
print(float(listNums[0])+float(listNums[1]))
output
3.0
This is based on your explanation of the problem.
Now using your logic of solving this proble, I would consider removing the while loop altogether but keeping the for loop. Though keeping the plain for loop will not give us our desired output because it will find the sum of every number in the list. Instead we can cut the list of at two elements. The below code shows how to do that.
your logic code
def add2(nums):
count = 0
ans = 0
for x in nums[:2]:
ans += x
print(f'ans: {ans}')
add2([1,2,3,4])
output
ans: 3
It could be as simple as this:
ans=0
for i in range(len(nums)):
ans+=nums[i]
if i > 2:
break
The problem below uses the function get_numbers() to read a number of integers from the user. Three unfinished functions are defined, which should print only certain types of numbers that the user entered. Complete the unfinished functions, adding loops and branches where necessary. Match the output with the below sample:
Numbers are: 5 99 -44 0 12
I already figured out how to complete first function.
Having a hard time complete odd and negative number comparison.
For some reason
def print_odd_numbers(numbers):
if numbers % 2 == 1:
print('Odd numbers:', numbers)
Is not working?
size = 6
def get_numbers(num):
numbers = []
user_input = input('Enter %s integers:\n' % num)
i = 0
for token in user_input.split():
number = int(token) # Convert string input into integer
numbers.append(number) # Add to numbers list
print(i, number)
i += 1
return numbers
def print_all_numbers(numbers):
# Print numbers
print('Numbers:')
def print_odd_numbers(numbers):
# Print all odd numbers
print('Odd numbers:')
def print_negative_numbers(numbers):
# Print all negative numbers
print('Negative numbers:')
nums = get_numbers(size)
print_all_numbers(nums)
print_odd_numbers(nums)
print_negative_numbers(nums)
Enter 5 integers:
0 5
1 99
2 -44
3 0
4 12
Numbers: 5 99 -44 0 12
Odd numbers: 5 99
Negative numbers: -44
The code isn't working because numbers is a list of numbers. Try this code:
def print_odd_numbers(numbers):
print('Odd numbers: ')
for n in numbers:
if n % 2 == 1:
print(n, end=' '))
You could also use a list comprehension:
def print_odd_numbers(numbers):
odd = [n for n in numbers if n % 2 == 1]
print('Odd numbers:', ' '.join(map(str, odd)))
modulus needs to be == 0 to seen as an even and if number%2 != 0 then itll be read as an odd number
This is my code. I am trying to find the prime numbers before or equal to the integer inputted. However, it seems that the loop stops when it sees an integer in the range that fits the requirements. Unfortunately, this is not I wanted it to do. I would like to make it run through all the tests in the range before making the judgement. Is this possible? If so, how do I do this? Thank you.
def getNumber(main):
n = int(input())
return n
def isPrime(n):
list=[2]
if n > 1:
for i in range(2, n+1):
for a in range (2, n):
if i*a != i and i%a != 0 and i%2 != 0:
list.append(i)
break
return "\n".join(map(str, list))`
def main():
n = getNumber(main)
print(isPrime(n))
main()
You've got your logic a bit wrong. Here's what your code is doing:
Examine numbers in increasing order from 2 to the inputted n.
For each number i, check if any number a between 2 and n divides i
If a divides i, add i to the list, and then move to the next i
This isn't going to get you a prime number. In fact, I'm having trouble figuring out what it will give you, but a prime number probably isn't it. Look at this function instead, which will return all the prime numbers less than or equal to the given number - you can compare it to your code to figure out where you went wrong:
def getPrimesLessThanOrEqualTo(n):
if n <= 1: # Anything 1 or less has no primes less than it.
return "" # So, return nothing.
list = [2] # 2 is the lowest prime number <= n
for i in range(3, n+1): # We start at 3 because there's no need to re-check 2
for a in list: # Instead of iterating through everything less than
# i, we can just see if i is divisible by any of
# the primes we've already found
if i % a == 0: # If one of the primes we've found divides i evenly...
break # then go ahead and try the next i
list.append(i) # Now, if we got through that last bit without
# hitting the break statement, we add i to our list
return "\n".join(list) # Finally, return our list of primes <= i
If you wanted to be more efficient, you could even use range(3, n+1, 2) to count by twos - thus avoiding looking at even numbers at all.
You can use a if/else block if your break is never executed by any item in the iterable the else statement will triggered. https://docs.python.org/3/tutorial/controlflow.html 4.4 demonstrates this accomplishing this almost exact task.
n = int(input('Enter number: '))
if n <= 1:
print('No primes')
else:
primes = []
for i in range(2, n +1):
for k in range(2, i):
if not i % k:
break
else:
primes.append(i)
print(*primes)
# Enter number: 50
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47