Start a new line after 4th element in list - python

I've written a code to print a Fibonacci sequence up to a certain value input by the user. I need the output to start a new line after every 4th element.
Here is my code:
number = int(input("Enter a positive number: \n"))
f1, f2 = 0, 1
count = 1
fibonacci = [f1]
while count < number:
fn = f1 + f2
f1 = f2
f2 = fn
fibonacci.append(f1)
count += 1
print(fibonacci)

While not changing priginal fibonacci list, you can print your values like this.
Instead of
print(fibonacci)
you could use this:
for i in range(0, len(fibonacci), 4):
print(fibonacci[i:i+4])

number = int(input("Enter a positive number: "))
def fabronic(n):
if n<=1:
return n
else:
return fabronic(n-1)+fabronic(n-2)
count,n=0,0
while n<number:
print(fabronic(n),end=' ')
count+=1
if count==4:
print()
count=0
n=n+1
input=Enter a positive number: 15
output=
0 1 1 2
3 5 8 13
21 34 55 89
144 233 377
By using list
n=0
mylist=[]
while n<number:
mylist.append(fabronic(n))
n=n+1
for item in range(0,len(mylist),4):
print(mylist[item:item+4],sep=' ',end='\n')
output=
Enter a positive number: 15
[0, 1, 1, 2]
[3, 5, 8, 13]
[21, 34, 55, 89]
[144, 233, 377]

You already have a counter so I guess what you want is that every time it reaches a multiple of 4, use print('\n')

Related

Divide a number into smaller specific numbers

I want to create a program that takes in an input from a user and returns the value in bills
i.e. if the input is 110, I would want to program to output:
1 x 100
1 x 10
and if the input is 87 I want to program to output
4 x 20
1 x 5
2 x 1
etc. Anyone know how to do this?
You can use integer division to get the how often each bill fits.
bills = [20, 5, 1]
input = 87
for bill in bills:
integer_div = input // bill
if integer_div > 0:
print(f'{integer_div} x {bill}')
input -= integer_div * bill
Result
4 x 20
1 x 5
2 x 1
def change(amount, bills):
money = {}
for bill in bills:
bill_count = amount/bill
money[bill] = bill_count
amount -= bill * bill_count
return money
result = change(87, [20, 5, 1])
for coin, amount in result.items():
if amount != 0:
print("%d X %d" % (amount, coin))
will make the required result.

A for loop to print dictionary items once without repeating the print function

I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and i'm not good at enlish.But i have a problem with this code.
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print('They are',n,end=' ')
The result of the code when ran comes out looking like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37
but i want it like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37
If you're completely determined not to use the print function more than once inside the loop, you could set a flag to determine whether to print the first two words. Like so:
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
first = 'They are '
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print(first + str(n), end=' ')
if len(first) > 0:
first = ''
The following solution may help you
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
num = [] # Create empty list
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
num.append(n)
# Write the print statement outside of the loop and use .join() function and for loop
#to print each element of the list look like the output you have posted
#
print('They are'," ".join(str(x) for x in num))
Output:
Displays prime numbers from 1 to N.
Please enter a value of n: 40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

Python. How do i count the number of divisors in nested for loop?

I have a code that generates triangular numbers, calculates the divisors for each triangular number and prints out 3 columns where the first column is the input numbers, the second column is the triangular numbers and the third column is the divisors of each triangular number. How can I count the number of divisors of each triangular number(count the numbers in the third column)?
for num in range(10):
triangle_number = num*(num+1)//2
print(num, end = ' ')
print(triangle_number, end = ' ')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
print()
Output looks like this:
0 0
1 1 1,
2 3 1,3,
3 6 1,2,3,6,
4 10 1,2,5,10,
5 15 1,3,5,15,
6 21 1,3,7,21,
7 28 1,2,4,7,14,28,
8 36 1,2,3,4,6,9,12,18,36,
9 45 1,3,5,9,15,45,
You can add a variable inside for loop and increment it when you get the divisor and print a the end.
for num in range(10):
count = 0
triangle_number = num*(num+1)//2
print(num, end = '\t')
print(triangle_number, end = '\t')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
count += 1
print("\t", count)
##Output:
##0 0 0
##1 1 1, 1
##2 3 1,3, 2
##3 6 1,2,3,6, 4
##4 10 1,2,5,10, 4
##5 15 1,3,5,15, 4
##6 21 1,3,7,21, 4
##7 28 1,2,4,7,14,28, 6
##8 36 1,2,3,4,6,9,12,18,36, 9
##9 45 1,3,5,9,15,45, 6
##Output order : input number, count of divisors divisors, triangular number
or you can create a list of divisors and measure length before printing.
for num in range(10):
divisors = []
triangle_number = num*(num+1)//2
print(num, end = '\t')
print(triangle_number, end = '\t')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
divisors.append(divisor)
print(len(divisors), "\t", ",".join(str(div )for div in divisors))
##Output:
##0 0 0
##1 1 1 1
##2 3 2 1,3
##3 6 4 1,2,3,6
##4 10 4 1,2,5,10
##5 15 4 1,3,5,15
##6 21 4 1,3,7,21
##7 28 6 1,2,4,7,14,28
##8 36 9 1,2,3,4,6,9,12,18,36
##9 45 6 1,3,5,9,15,45
##Output order : input number, triangular number, count of divisors divisors
You might replace your inner for loop using list comprehension and then just get length of that list using len function, that is replace:
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
with:
divisors = [divisor for divisor in range(1, triangle_number+1) if triangle_number%divisor == 0]
print(*divisors, sep=',', end=' ')
print(len(divisors), end='')
list comprehension is succint way of creating list which might be created via appending inside for loop, * (star operator) does unpacking, if you would have list x = [1, 2, 3] then print(*x) is equivalent of print(1, 2, 3) and so on.

Write a function named get_numbers() that returns a list of integers

When I try to run module the output shows "None". What can I change for my function.
Like this:
Enter a set of numbers separated by spaces for analysis: 10 2 38 23 38 23 21 23
None
import math
def get_numbers():
numbers_string = input("Enter a set of numbers separated by spaces for analysis: ")
numbers = numbers_string.split()
for index in range(len(numbers)):
numbers[index] = int(numbers[index])
numbers.sort()
print(get_numbers())
output:
Enter a set of numbers separated by spaces for analysis: 10 2 38 23
38 23 21 23
[10, 2, 38, 23, 38, 23, 21, 23]
Nothing is being returned in your function. Just add return numbers at the end of function and it will work.
Example:
def get_numbers():
numbers_string = input("Enter a set of numbers separated by spaces for analysis: ")
numbers = list(map(int, numbers_string.split()))
numbers.sort()
return numbers
print(get_numbers())
Output:
>>> python3 test.py
Enter a set of numbers separated by spaces for analysis: 3 6 8 5 4
[3, 4, 5, 6, 8]

Python: Wrong output and ValueError: Prime Factors Creator

I've created a program that successfully detects whether a number is prime, or not, it also will return a list of the factors of the number if it isn't, but that part is not successful.
Here is my code:
def prime_num():
num = int(input("Give me a number...: "))
prime = True
if num == 1:
prime = False
elif num == 2:
prime = True
for x in range(2, num):
if num % x == 0:
prime = False
break
if prime == False:
print("That's not a prime number!")
factors(num)
elif prime == True:
print("That's a prime number!")
def factors(num):
factors = []
for x in range(1, num+1):
if num % x == 0:
factors.append(x)
print("The factors for " + str(num) + " are: ", factors)
for x in factors:
for y in range(1, x):
if x % y == 0:
factors.remove(x)
print("The prime factors for " + str(num) + " are: ", factors)
When I use this function with a "num" value of 25 I get this output...
prime_num()
Give me a number...: 25
That's not a prime number!
The factors for 25 are: [1, 5, 25]
The prime factors for 25 are: [1, 25]
Which isn't the correct output for prime factors, I just want it to return: [5]
(I'm not concerned about the multiplicity of the factors at this time)
However, when I try the number 50, as my "num". I get this output with a valueError:
prime_num()
Give me a number...: 50
That's not a prime number!
The factors for 50 are: [1, 2, 5, 10, 25, 50]
Traceback (most recent call last):
File "<ipython-input-19-12c785465e2a>", line 1, in <module>
prime_num()
File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 25, in prime_num
factors(num)
File "C:/Users/x/Desktop/Python/Python Practice/primes.py", line 40, in factors
factors.remove(x)
ValueError: list.remove(x): x not in list
I realize this means somehow my x isn't in factors, but I'm not sure how considering I'm specifically iterating through factors.
This should make it clear what your problem is:
factors = [1,5,25]
for x in factors:
for y in range(1,x):
print x,y
5 1
5 2
5 3
5 4
25 1
25 2
25 3
25 4
25 5
25 6
25 7
25 8
25 9
25 10
25 11
25 12
25 13
25 14
25 15
25 16
25 17
25 18
25 19
25 20
25 21
25 22
25 23
25 24
You're iterating over your factors in such a way that you ignore 1 and ignore the x % x combination. range(1,1) is the empty list, and then you simply stop short because you've increased the start point by 1 (from zero) but not the end point, leaving what you iterate over too short.
The reason you get a ValueError is because any non-square number (ie, not 4, 9, 16, 25, etc.) will be removed twice. For 6, for example, it will remove for the 2,3 combo and when it gets to the 3,2 combo it's already been removed, thus the error. One way to fix this is to make the code only go halfway minus one to your total, so that inverted numbers aren't removed twice. For example, stop at 2 for 6, 4 for 10, etc.

Categories