sum of Fibbonaci Sequences? - python

Trying to add the sum of Fibonacci, using definite loops. It's meant to calculate the summation of Fibonacci number with each number too. Below is the sample for the Fibonacci sequence and its summation, how do i add the sum of the fibonacci eg 1,1,2,3,5,8
Fibonacci Summation
0 0
1 1
1 2
2 4
3 7
5 12
8 20
n = int(input("enter"))
def fibonacciSeries():
a=0
b=1
for i in range (n-2):
x = a+b
a=b
b=x
int(x)
x[i]= x+x[i-1]
#should add the previous sequences
print(x)
fibonacciSeries()

You don't need to keep track of the whole sequence. Plus your Fibonacci implementation doesn't start with 1, 1 but rather 1, 2 so I fixed that.
def fibonacciSeries(n):
a=0
b=1
x=1
series_sum = 0
for i in range (n-2):
series_sum += x
print(f'{x} {series_sum}')
x = a+b
a=b
b=x
n = 10
fibonacciSeries(n)
Output:
1 1
1 2
2 4
3 7
5 12
8 20
13 33
21 54

def fibonacciSeries(n):
sum = 0
a = 0
b = 1
x = 1
sum = 0
for i in range(0,n - 2):
sum += x
print(x,sum)
x = a + b
a = b
b = x
n = int(input("enter : ")) # n = 8
fibonacciSeries(n)
Output:
enter : 8
1 1
1 2
2 4
3 7
5 12
8 20

Related

Find Python Multiplication from user input

Junior Python Coder here! Trying to print multiplication table with user input but stuck.
min_num=1
max_num=11
starting_range = int(input ("Enter the minimum number: "))
ending_range = int(input ("Enter the maximum number: "))
print ("The Multiplication Table of: ", starting_range)
for count in range(1, 11):
print (starting_range, 'x', count, '=', ending_range * count)
if max_num - min_num > 10 :
print('invalid range ')
else:
for num in range (min_num,max_num):
print ("The Multiplication Table of: ", ending_range)
for count in range(min_num, max_num):
print (starting_range, 'x', count, '=', ending_range * count)
I'm not sure I really understand what you're trying to do as your code isn't formatted, but for a multiplication table, a nested loop is a solution.
The basic idea is: For every number in the given range, loop over the whole range and multiply it by each element. This will print the whole multiplication table.
start = 1 # You can change these to be inputted by the user.
end = 10
for i in range(start, end + 1): # We add 1 to the end because range() is exclusive on endpoint.
for j in range(start, end + 1):
print(f"{i} x {j} = {i * j}")
If you only need the table as something like:
15 x 1
15 x 2
15 x 3
...
You can do this with one loop:
num = 10
for i in range(1, num + 1):
print(f"{num} x {i} = {num * i}")
I recommend you search up on F-strings in Python if you do not understand the print(f"..") parts. They're very convenient. Good luck!
Minimal change to original code:
min_num = 1
max_num = 11
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
# Removed the error checking, wasn't sure precisely what it was meant to do.
for num in range(starting_range,ending_range):
print ("The Multiplication Table of: ", num)
for count in range(min_num, max_num):
print (num, 'x', count, '=', num * count)
Try it at https://www.mycompiler.io/view/7JVNtxkT53k
This prints:
The Multiplication Table of: 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
The Multiplication Table of: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
The Multiplication Table of: 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Alternative code defining a function:
def print_multiplication_table(n, max_value=11):
if n > max_value or n <= 0:
raise ValueError
print(f"The Multiplication Table of: {n}")
for m in range(1, max_value):
print(f"{n} x {m} = {n*m}")
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
for i in range(starting_range, ending_range):
print_multiplication_table(i)
Try it at https://www.mycompiler.io/view/1uttFLmFEiD

how can I decrease execution time needed for python code?

#https://www.codechef.com/problems/GRIDGM
from sys import setrecursionlimit
setrecursionlimit(10**6)
def sol(l,lst):
sum=0
for i in range(l[0],l[2]+1):
for j in range(l[1],l[3]+1):
#print(lst[i-1][j-1],end="")
sum += lst[i-1][j-1]
#print('---')
#print("sol below")
return sum
for _ in range(int(input())):
n,m=map(int, input("enter values of n and m").split())
lst=[]
for _ in range(n):
lst.append(list(map(int,input("enter a row").split())))
#print(lst)
#q=int(input())
#dj=[] #it saves x y and a b
for _ in range(int(input("enter no of queries"))):
#v=list(map(int,input().split()))
#print(v)
#print('sol below')
print(sol(list(map(int,input("enter cordinates").split())),lst))
sample input
1
4 4
9 13 5 2
1 11 7 6
3 7 4 1
6 0 7 10
2
2 1 4 2
2 2 4 4
output
28
53
above code took 5.1 sec to execute.
in this question, I have to find sum of elements within given coordinates a,b and x,y
more information about this problem can be found in the link below.
https://www.codechef.com/problems/GRIDGM

How to implement input into multiplication table?

Heyy, i got a bit of help earlier but am stuck once again :(
I am completely new to coding so i apologize for questions on such simple matters.
I am writing a program that puts out a multiplication table for the numbers that the user chooses(Using while instead of for to better understand how while loops work)
This is what i have so far:
print(end='')
max_x = int(input("Number of columns:"))
x = 1
while x <= max_x:
print(end='')
x += 1
max_y = int(input("Number of rows:"))
y = 1
while y <= max_y:
print('')
print(end='')
z = 1
while z <= max_x:
print(y*z, end='\t')
z += 1
y += 1
And this is the output that i get:
Number of columns:5
Number of rows:4
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
My issue is that i can´t for the life of me figure out how to get the table to also include the 1, as in:
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16
Appreciate any help as i´ve been trying and googling a bunch and frankly feel quite dumb struggling with such a simple thing
The extra digits are for the axis labels so they need to be drawn separately.
Try this code:
print(end='')
max_x = int(input("Number of columns:"))
x = 1
while x <= max_x:
print(end='')
x += 1
max_y = int(input("Number of rows:"))
y = 1
print(' \t' + '\t'.join([str(i+1) for i in range(max_x)]), end="") # labels X axis
while y <= max_y:
print('')
print(end='')
z = 1
print(y,end='\t') # label Y axis
while z <= max_x:
print(y*z, end='\t')
z += 1
y += 1
Output:
Number of columns:4
Number of rows:4
1 2 3 4
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12
4 4 8 12 16

How to make a while loop for a multiplication table?

I am trying to create a multiplication chart with a while loop for an assignment but I am having a hard time getting the expected output.
I have tried everything I can think of. I am new to the coding world.
#While loop
print('While Loop')
print()
x = 1
y = 1
z = 1
while x <= 12:
print(x ,end='\t')
x += 1
while y <= 12:
print('\n')
print(y,'\t')
y += 1
while z <= 12:
print(x*z ,end='\t')
z += 1
z = 0
x = 1
I expect the output to be
but I get
.
Short answer: you use x*z when you calculate the product, but you use y as a "row counter" and z as a "column counter" so it should be y*z. Furthermore you should increment the y after the inner while loop.
Since you use y as the "row counter" and z as the "column counter", you should print y * z as the answer of that specific multiplication. Furthermore you increment y too soon: you should increment it after the while loop, and reset z to 1, like:
print('While Loop')
print('x', end='\t') # print a cross
x = 1
while x <= 12:
print(x ,end='\t')
x += 1
y = 1
while y <= 12:
print('')
print(y,end='\t')
z = 1 # reset to 1
while z <= 12:
print(y*z ,end='\t') # use y * z
z += 1
y += 1 # incerement after while loop
print()
Using for loops
There are also some minor formatting issues. For example you should first print('X', end='\t') since otherwise the columns do not match correctly.
That being said, you make things way harder than these should be. You can make use of a for loop instead, like:
print('x', end='\t')
print('\t'.join(str(i) for i in range(1, 13)))
for r in range(1, 13):
print(r, end='\t')
print('\t'.join(str(r*c) for c in range(1, 13)))
or in a function:
def mulgrid(n):
print('x', end='\t')
print('\t'.join(str(i) for i in range(1, n+1)))
for r in range(1, n+1):
print(r, end='\t')
print('\t'.join(str(r*c) for c in range(1, n+1)))
For example:
>>> mulgrid(1)
x 1
1 1
>>> mulgrid(2)
x 1 2
1 1 2
2 2 4
>>> mulgrid(5)
x 1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
>>> mulgrid(7)
x 1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49

Grouping list of integers in a range into chunks

Given a set or a list (assume its ordered)
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
I want to find out how many numbers appear in a range.
say my range is 10. Then given the list above, I have two sets of 10.
I want the function to return [10,10]
if my range was 15. Then I should get [15,5]
The range will change. Here is what I came up with
myRange = 10
start = 1
current = start
next = current + myRange
count = 0
setTotal = []
for i in myset:
if i >= current and i < next :
count = count + 1
print str(i)+" in "+str(len(setTotal)+1)
else:
current = current + myRange
next = myRange + current
if next >= myset[-1]:
next = myset[-1]
setTotal.append(count)
count = 0
print setTotal
Output
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 8]
notice 11 and 20 where skipped. I also played around with the condition and got wired results.
EDIT: Range defines a range that every value in the range should be counted into one chuck.
think of a range as from current value to currentvalue+range as one chunk.
EDIT:
Wanted output:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
[10, 10]
With the right key function, thegroupbymethod in the itertoolsmodule makes doing this fairly simple:
from itertools import groupby
def ranger(values, range_size):
def keyfunc(n):
key = n/(range_size+1) + 1
print '{} in {}'.format(n, key)
return key
return [len(list(g)) for k, g in groupby(values, key=keyfunc)]
myset = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print ranger(myset, 10)
print ranger(myset, 15)
You want to use simple division and the remainder; the divmod() function gives you both:
def chunks(lst, size):
count, remainder = divmod(len(lst), size)
return [size] * count + ([remainder] if remainder else [])
To create your desired output, then use the output of chunks():
lst = range(1, 21)
size = 10
start = 0
for count, chunk in enumerate(chunks(lst, size), 1):
for i in lst[start:start + chunk]:
print '{} in {}'.format(i, count)
start += chunk
count is the number of the current chunk (starting at 1; python uses 0-based indexing normally).
This prints:
1 in 1
2 in 1
3 in 1
4 in 1
5 in 1
6 in 1
7 in 1
8 in 1
9 in 1
10 in 1
11 in 2
12 in 2
13 in 2
14 in 2
15 in 2
16 in 2
17 in 2
18 in 2
19 in 2
20 in 2
If you don't care about what numbers are in a given chunk, you can calculate the size easily:
def chunk_sizes(lst, size):
complete = len(lst) // size # Number of `size`-sized chunks
partial = len(lst) % size # Last chunk
if partial: # Sometimes the last chunk is empty
return [size] * complete + [partial]
else:
return [size] * complete

Categories

Resources