Recursion Extracting Digits Using a Base - python

Homework help needed here.
Im really struggling to get my head around recursion and the way it works.
The problem is, write a recursive function dec2base(n,b) that returns the list of base b digits in the positive integer n
exmaple:
dec2base(120, 10) => [1,2,0] (1*10*2 + 2/10**1 + 0*10**0)
I understand there should be a stop case but i cant think of what it might be.
So at the moment, all my code looks like is:
def dec2base(n, b):
if
And that's it. Any guidance would be amazing. Thankyou!
EDIT: tired a code for somehting like this:
def dec2base(n, b):
if n < 10:
return [n]
else:
return getdigits(n/b) + [n%b]
but that doesnt get me anwyehre...

To understand recursion, one has to first understand recursion.
You stated the stop case by yourself, it's of course when it's reached base**0
Edit: #your Edit: you almost got it, do not give up. how many arguments does dec2base take? think!

The key element to this task is understanding (or devising)
Horner's method.
We can write numbers in your way:
1234 = 1*103 + 2*102 + 3*101 + 4*100
But after thinking a bit we come up with this representation:
1234 = 123*10 + 4 = (12*10 + 3)*10 + 4 = ((1*10 + 2)*10 + 3)*10 + 4
I hope you can see recursion more clearly. In each step, check if number can be divided mod 10. If so, remainder is next digit and quotient can be worked on recursively.

def dec2base(n,b):
if n < b:
return [n]
else:
return dec2base(n//b, b) + [n%b]

Related

I'm not able to memoize this question in leetcode ? What am i doing wrong?

Question link: https://leetcode.com/problems/unique-paths/
Code with memoization but takes the same amount of time :https://leetcode.com/submissions/detail/672801459/
Code without memoization: https://leetcode.com/submissions/detail/672800593/
Code with memoization but takes the same amount of time :https://leetcode.com/submissions/detail/672801459/
I've written code for memoization but something doesn't work please tell me what am i doing wrong.
Memoization is not the problem
I just think that even if the implementation works the way you intend it, it is still too slow, you could have up to one billion path to explore wich could each take more than 100 steps.
Try it with combinatorics
Another approach is to look at the problem from a combinatorics side:
notice how each path could be represented by a list of down or right moves
so the total number of paths is just the number of ways to arrange the down and up moves
From the original question, we can see that there are m-1 moves down and n-1moves up.
In combinatorics, we say that the result is the combination of m-1 in (m-1) + (n-1)
Here is some code that would do that:
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
def factorial(a):
out = 1
for i in range(1, a+1):
out *= i
return out
def combination(a, b):
out = 1
for i in range(b-a+1, b+1):
out *= i
return out // factorial(a)
return combination(m-1, (m-1)+(n-1))

How to I find the last three digits of a number that is the result of 2^(a^b)

In Python, I am trying to figure out how to find the last three digits of a number that is the result of 2^(a^b) with a and b as the imput values. It handles input values up to 6, 6 without slowing down, but once it gets to 7, 7 it becomes very slow, and 8, 8 just doesnt work. I was wondering if there was some kind of mathematical shortcut or something to get the last three digits faster. Also, I am kind of new to stack overflow, so I don't know if I am asking this in the right place. Also, I am using replit if that changes anything. (This is for school and I would really appreciate help)
def last_three(a, b):
num = 2 ** (a ** b)
string = str(num)
length = len(string)
print (length)
new_string = ''
new_string += string[length - 3]
new_string += string[length - 2]
new_string += string[length - 1]
return int(new_string)
I realized that the equation is not the slow part, it was the fact that I was converting it to a string, finding the length, and indexing the last 3 digits.
One of the comments told me to do 2**(a**b) % 1000 to get the solution, and it worked.
Thank you all for the feedback.

Finding the Maximum Pyramidal Number by recursion in Python

I'm given the task to define a function to find the largest pyramidal number. For context, this is what pyramidal numbers are:
1 = 1^2
5 = 1^2 + 2^2
14 = 1^2 + 2^2 + 3^2
And so on.
The first part of the question requires me to find iteratively the largest pyramidal number within the range of argument n. To which, I successfully did:
def largest_square_pyramidal_num(n):
total = 0
i = 0
while total <= n:
total += i**2
i += 1
if total > n:
return total - (i-1)**2
else:
return total
So far, I can catch on.
The next part of the question then requires me to define the same function, but this time recursively. That's where I was instantly stunned. For the usual recursive functions that I have worked on before, I had always operated ON the argument, but had never come across a function where the argument was the condition instead. I struggled for quite a while and ended up with a function I knew clearly would not work. But I simply could not wrap my head around how to "recurse" such function. Here's my obviously-wrong code:
def largest_square_pyramidal_num_rec(n):
m = 0
pyr_number = 0
pyr_number += m**2
def pyr_num(m):
if pyr_number >= n:
return pyr_number
else:
return pyr_num(m+1)
return pyr_number
I know this is erroneous, and I can say why, but I don't know how to correct it. Does anyone have any advice?
Edit: At the kind request of a fellow programmer, here is my logic and what I know is wrong:
Here's my logic: The process that repeats itself is the addition of square numbers to give the pyr num. Hence this is the recursive process. But this isn't what the argument is about, hence I need to redefine the recursive argument. In this case, m, and build up to a pyr num of pyr_number, to which I will compare with the condition of n. I'm used to recursion in decrements, but it doesn't make sense to me (I mean, where to start?) so I attempted to recall the function upwards.
BUT this clearly isn't right. First of all, I'm sceptical of defining the element m and pyr_num outside of the pyr_num subfunction. Next, m isn't pre-defined. Which is wrong. Lastly and most importantly, the calling of pyr_num will always call back pyr_num = 0. But I cannot figure out another way to write this logic out
Here's a recursive function to calculate the pyramid number, based on how many terms you give it.
def pyramid(terms: int) -> int:
if terms <=1:
return 1
return terms * terms + pyramid(terms - 1)
pyramid(3) # 14
If you can understand what the function does and how it works, you should be able to figure out another function that gives you the greatest pyramid less than n.
def base(n):
return rec(n, 0, 0)
def rec(n, i, tot):
if tot > n:
return tot - (i-1)**2
else:
return rec(n, i+1, tot+i**2)
print(base(NUMBER))
this output the same thing of your not-recursive function.

Python. I'm curious if my solution to solve this programming issue is odd? Also, what might be a proper solution from someone who has more experience

I was doing a google python exercise and I came up with a solution that worked. I find this exercise very interesting. I'm just wondering if my solution is odd or not, and is there a much more normal way someone with experience might have solved this same issue? I'm just trying to improve my coding. I'm all self taught, so just looking for feedback. Thanks!
# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
# a-front + b-front + a-back + b-back
def front_back(a, b):
# +++your code here+++
lengthABack = len(a)/2
lengthAFront = len(a)/2 + len(a)%2
lengthBBack = len(b)/2
lengthBFront = len(b)/2 + len(b)%2
return a[:lengthAFront]+b[:lengthBFront]+a[-lengthABack:]+b[-lengthBBack:]
A slightly shorter and maybe more Pythonic solution:
def front_back(a, b):
a_split = (len(a) + 1) // 2
b_split = (len(b) + 1) // 2
return a[:a_split] + b[:b_split] + a[a_split:] + b[b_split:]
We use (len(a) + 1) // 2 here because it mathematically gives the same result as len(a)/2 + len(a)%2 but involves only one evaluation of len(a).

Could someone show me a good factorial code?

I just started to study Python. I must use Python3.7.
Could someone show me a working factorial code?
i tried some i found here but i always get this error:
=================== RESTART: C:\programozás\pytutorial.py ===================
Code:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
Your code is working, even though you could simply use the math library:
import math
print(math.factorial(5))
The problem does not come from your script, so maybe you should try to reinstall your python, and avoid paths with special characters as Adam Toth pointed out.
Update: to get the input and return a factorial as asked in comments
import math
print(math.factorial(int(input(">>"))))
The problem is most likely caused because you have a special character in the path to the .py file. So should use a folder like C:\programming, or anything without a special character, like 'á'.
It's very important to do like this, even if it does not solve your current problem, it can prevent many more in the future.
Ps.: Jó kiszúrni magyar programozót is :)
I see a related (older) thread here about this error
For the logic:
We have to consider:
Negative numbers
Zero
Positive numbers
So one way to write it will be:
def factorial(n):
if n < 0:
result = "Factorial doesn't exist for negative numbers"
elif n == 0:
result = 1
else:
result = 1
for i in range(1, n + 1):
result *= i
return result
You can try the concept of recursion as well.
To get the factorial of a number "num":
print(factorial(num))
Make sure you indent the code properly, indentation is important in python.
Hope it helps!
Python Code of Factorial Using Recursive Function:
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
factorial(5)
Note: The First Condition will only meet when the input is 0 or 1 and in else block n will be recursively multiplying n * n - 1.

Categories