Using set theory to find the shape area in Python - python

So I'm given the following diagram:
And I'm being asked to find the area of each polygon given n. The area is basically the sum of all blue squares since each square has an area of 1. So when n = 1, the area is one. When n = 2, the area is 5. Because of the relationship between each polygon, I know that I could knock this down using set theory.
n Area(n)
1 1
2 A(n-1) + (4 * (n-1)) = 5
3 A(n-1) + (4 * (n-1)) = 13
4 A(n-1) + (4 * (n-1)) = 25
5 A(n-1) + (4 * (n-1)) = 41
However, I didn't have as much luck trying to represent this in code:
def shapeArea(n):
prev_output = 0
output = 0
if n == 1:
output = 1
elif n > 1:
for i in range(n):
prev_output = n-1 + (4 * (n-1))
output = prev_output + (4 * (n-1))
return output
For example: For n = 2, I'm getting an output of 9 instead of 5.

You were close :-)
Here are the small fix-ups:
def shapeArea(n):
output = 1
for i in range(1, n):
output += 4 * i
return output
Running this:
for n in range(1, 6):
print(n, shapeArea(n))
Gives this output:
1 1
2 5
3 13
4 25
5 41

of course with Gauss's theorem the code would look like this:
def ShapeArea(n):
return 2*(n**2) - (2*n)+1

In a recursive solution, it is much simple from your logic.
def shape_area(n):
if n == 1:
return 1
return shape_area(n-1) + 4*(n-1)

You can use Gauss' trick to make a closed-form formula:
2*Area(n) =
1 + 4 + 8 + 12 + ... + 4(n-1)
+
1 + 4(n-1) + 4(n-2) + 4(n-3) + ... + 4
--------------------------------------------------
2 + 4n + 4n + 4n + ... + 4n
= (n-1)4n + 2
= 4n^2 - 4n + 2
So Area(n) = 2n2 - 2n + 1

def shape_area(n):
return sum([1] + [4*i for i in range(1, n)])

Related

Python - How can I line up the equals sign of all my equations?

Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.
Here is the code I already wrote :
def div(n):
return [x for x in range(1,n+1) if n%x==0]
def pgcd(x,y):
a = x
b = y
while b > 0:
reste = a % b
print(a, "=", a//b, "*", b, "+", a%b)
a,b = b,reste
return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
And it ouputs this :
pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
I want it to output that :
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
I've read many articles online but I have no idea how to put that into my code.
Thanks in advance.
You can use the rjust string method.
The thing is you need to figure out what is the widest string on the left hand side you will print. Luckily here, it would be the first value.
So I would go with this.
def pgcd(x,y):
a = x
b = y
len_a = len(f"{a}")
while b > 0:
reste = a % b
print(f"{a}".rjust(len_a), "=", a//b, "*", b, "+", a%b)
a,b = b,reste
return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
Should print this.
>>> pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
'PGCD(178;52) = 2'
See .format for strings. An example of right justifying would look something like print('{:>6}'.format(42))
You can also use rjust
Use str.format() to achieve this:
'{0: >{width}}'.format(178, 3)
'{0: >{width}}'.format(52, 3)
Will output
178
52
Ok I asked it on a Discord server and they found out so if anyone is having the same problem as me here is the solution (did not put all code for space) :
def pgcd(x,y):
a = x
b = y
maxi = len(str(a))
while b > 0:
reste = a % b
print(" "*(maxi-len(str(a))),a, "=", a//b, "*", b, "+", a%b)
Basically compare to original code we added a maxi variable that has the maximum lenght of my integers, and then if the int is smaller like 8 compare to 178 we add to spaces because the difference of their length is 2.
This explanation is probably not 100% correct but it helps getting an idea.

How can i calculate and print the sum of first N elements of below sequence using recursive function

How can i calculate and print the sum of first N elements of below sequence using recursive function
Example:
Sample Input N: 4
Sample Output: 7 + 12 + 17 + 22 = 58
I did some part of the code but it gives wrong result and I don't know where I'm making mistakes. That's why I need help!
def recur_sum(n):
if n <= 1:
return n
else:
for i in range(7,n+1):
return i + recur_sum(i-1)
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
As far as I understand your question, you want the sum of a sequence which each element of this sequence is increased by a step (such as 5), and it has an initial value (like 7), and you want the sum of first N (like 4) elements of this sequence.
At each recursion level, we add the current value to step , but when n == 1 we only return the current value (which is the Nth item of the sequence).
Do this:
def recur_sum(cur_val, step, n):
if n == 1:
return cur_val
return cur_val + recur_sum(cur_val+step,step,n-1)
num = int(input("Enter a number: "))
init_val = 7
step = 5
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(init_val, step, num))
Output:
The sum is 58
this returns a list of all sequential numbers starting at 7 each increment of 5. sum the return array.... change 5 and 2 to change increments for desired jumps/steps, and change the initial return value..
def recur_sum(n):
if n == 1:
return [7]
else:
return [5*n+2] + recur_sum(n-1)
num = int(input("Enter a number: "))
res = recur_sum(num)
print(sum(res))
A recursive function which returns all the elements up to n (where n is the input of your function) has already been proposed above.
In my understanding, you want a function with some recursive logic that return the sum of all the elements up to the n-th.
Your sequence is 7, 12, 17, 22, 27 and so forth. If we disect it:
it element sum sum is element is
1 7 7 1 * 7 + 0 * 5 1 * 7 + 0 * 5
2 12 19 2 * 7 + 1 * 5 1 * 7 + 1 * 5
3 17 36 3 * 7 + 3 * 5 1 * 7 + 2 * 5
4 22 58 4 * 7 + 6 * 5 1 * 7 + 3 * 5
5 27 85 5 * 7 + 10 * 5 1 * 7 + 4 * 5
If you want at any cost to implement a recursive solution, if is evident that at each step you need to increase the rolling sum by it * 7 + (it - 1) * 5 (where 7 is your start point, while 5 is your step).
You can implement a recursive solution as follows:
def recursive(n, step = 5, start = 7, counter = 1):
if n > 0:
this_element = start + (counter - 1) * step
if counter == n:
return this_element
else:
return this_element + recursive(n, step = step, start = start, counter = counter + 1)
else:
return 0
for i in range(1, 10):
print(recursive(i))
OUTPUT
7
19
36
58
85
117
154
196
243
From the table above you can see though that maybe a recursive solution is overkilling here given that the sum of elements up to n-th step has solution:
def my_sum(n, step = 5, start = 7):
return n * start + int(step * (n - 1) * n / 2)
for i in range(1, 10):
print(my_sum(i))
OUTPUT
7
19
36
58
85
117
154
196
243

How do I solve this: "Step forward and backward problem"?

The Problem Statement:
Sanjay is addicted to alcohol. Every night he drinks 4 bottles of vodka. He is going to his home. At first, he takes a step forward (which is 5m) but beacuse he is drunk, after his each step in forward direction, his body gets imbalanced and he takes a step backward (which is 3m).
Each step takes 1 min to complete. The distance from the bar to home is n metres. Calculate the time taken by him to reach his home.
Input Format:
single line containing one integer n.
Constraints:
0 <= n < 10^18
Output Format
single integer describing the time taken by him to reach home.
from math import *
n = int(input())
x = 0
m = 0
n = n % 1000000007
n = n % 1000000007
while x < n:
x += 5
m += 1
if x >= n:
break
x -= 3
m += 1
print(m)
But the time limit is exceeding in the last test case i.e. for n = 10^18 like numbers
Sample Input 0
11
Sample Output 0
7
The time taken is simply n/2 * 2
He advances 2 meters each "cycle" 5 forward 3 back
So we see how many "cycles" go into n (n / 2m) this will result
In the number of "cycles" taken to reach his house
Then we simply multiply by the amount of time taken per cycle (2 minutes)
to get the total time taken (t = n/2 * 2).
Try reducing the problem. Let time_taken(dist) be the function that tells us how long it takes to get home. Then the following hold:
time_taken(1) == 1
time_taken(2) == 1
time_taken(3) == 1
time_taken(4) == 1
time_taken(5) == 1
time_taken(6) == 1 * 2 + time_taken(4) (since 5-3 = 2)
== 1 * 2 + 1
time_taken(7) == 1 * 2 + time_taken(5)
== 1 * 2 + 1
time_taken(11) == 1 * 2 + time_taken(9)
== 2 * 2 + time_taken(7)
== 3 * 2 + time_taken(5)
== 3 * 2 + 1
time_taken(26) == 1 * 2 + time_taken(24)
== 2 * 2 + time_taken(22)
== ...
== 11 * 2 + time_taken(4)
== 11 * 2 + 1
if n > 5:
time_taken(n) == 1 * 2 + time_taken(n - 2)
== 2 * 2 + time_taken(n - 4)
== ...
== (formula here) * 2 + time_taken(4 or 5)

All + - / x combos for 4 numbers

4 one digit numbers and try to get all the possible combos
4511
like 4 + 5 + 1 x 1
Code to get first, 2nd 3rd and 4th numbers
numbers = input("Input 4 numbers separated with , : ")
numlist = numbers.split(",")
print (numlist)
No1 = int(numlist.pop(0))
No2 = int(numlist[0])
No3 = int(numlist[1])
No4 = int(numlist[2])
An exhaustive search:
from random import randrange
from itertools import permutations
def solve(digits):
for xs in permutations(digits):
for ops in permutations('+-*/', 3):
equation = reduce(lambda r, (x, op): '{0} {1} {2}'.format(r, op, float(x)), zip(xs[1:], ops), xs[0])
try:
if eval(equation) == 10:
yield equation.replace('.0','')
except ZeroDivisionError:
pass
digits = [randrange(0,10,1) for x in range(4)]
solutions = list(solve(digits))
if solutions:
print '\n'.join(solutions)
else:
print 'No solution for {0}'.format(digits)
Example output:
2 * 5 / 1 + 0
2 * 5 / 1 - 0
2 * 5 + 0 / 1
2 * 5 - 0 / 1
2 / 1 * 5 + 0
2 / 1 * 5 - 0
5 * 2 / 1 + 0
5 * 2 / 1 - 0
5 * 2 + 0 / 1
5 * 2 - 0 / 1
5 / 1 * 2 + 0
5 / 1 * 2 - 0
0 + 2 * 5 / 1
0 + 2 / 1 * 5
0 + 5 * 2 / 1
0 + 5 / 1 * 2
0 / 1 + 2 * 5
0 / 1 + 5 * 2
or
No solution for [7, 1, 0, 2]
Note: I like the recursive expression generator referred to in the comment above, but I just don't think recursively straight off.
Use a recursive approach:
numbers = input("Input 4 numbers separated with , : ")
numlist = list(numbers)
def f(lst,carry,result):
x = lst.pop(0)
if lst == []:
return carry+x == result or \
carry-x == result or \
carry*x == result or \
carry/x == result
elif carry==None:
carry = x
return f(lst,carry,result)
else:
return f(lst,carry+x,result) or\
f(lst,carry-x,result) or\
f(lst,carry*x,result) or\
f(lst,carry/x,result)
print(f(numlist, None, 10))
Your I/O is wrong (first two lines), and I don't know if this is something that you have already tried.

Is this working properly - Sum of Fibonacci in Python 3

I have a task to make a program that will sum the first 100 Fibonacci numbers. I checked my output in Python, and my output in QBasic 64 and they aren't same. I checked with different inputs also.
Input: 10
Output: 89
-----------
Input: 100
Output: 573147844013817084101
Is it correct ?
Here is my code:
n = int(input())
print()
p = 0
d = 1
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
for i in range(n - 2):
p = d
d = z
z = p + d
print(str(p) + ' + ' + str(d) + ' = ' + str(z))
print('Sum:', z)
EDIT: Code edited again, check it now. I just found on Wikipedia.. It depends from what number you start the loop. So if I use (0, 1, 1, 2, 3, 5, 8, 13, 21, and 34) as first 10 Fibonacci numbers, the sum is going to be 88, not 89.
The sums of the first ten and 100 fibonacchi number would be 88 and 573147844013817084100, respectively:
>>> cache = {}
>>> def fib(n):
if n == 0: return 0
if n == 1: return 1
if not n in cache:
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
>>> sum([fib(i) for i in range(10)])
88
>>> sum([fib(i) for i in range(100)])
573147844013817084100
In your loop you are already starting the iteration at the 3rd position, since you set. So set your range to (n -2).
0: 1
1 : 1
2 : 1
3 : 2
4 : 3
5 : 5
To get the sum of the Fibonacci numbers, using zero as the first in the series, you need to do this:
def run_it(n):
N2 = 0
N1 = 0
N = 0
z = N
for i in range(n):
print(N,z)
N2 = N1
N1 = N
if N is 0: N = 1
else: N = N1 + N2
z = z + N
run_it(int(input('Number: ')))
To calculate the sum using one as the start of the series, change the initial value of N from zero to one.

Categories