I have a function that gets a number and should return the minimum digit.
This is what I was trying to do, but maybe I didn't fully understand how recursion works.
def min_dig(num):
minimum = 9
if num < 10:
return num
min_dig(num / 10)
if num % 10 < minimum:
minimum = num % 10
return minimum
print(min_dig(98918))
Output is 8 but supposed to be 1.
I think what the recursion trying to do is like this:
def min_dig(num):
if num < 10:
return num
return min(num % 10, min_dig(num // 10))
print(min_dig(98918))
If the number is smaller than 10, then its minimum digit is itself. If the number is larger than 10, we just compare its last digit and the minimum digit of the number composed of all its digits except the last digit, and return the smaller one.
I have modified your function in a way that works and I think is simpler to understand.
def min_dig(number):
if number < 10:
return number
else:
return min(number % 10, min_dig(number // 10))
This also uses recursion, I just do it as the return. Here you basically compare (number % 10) and (min_dig(number // 10) and just return the lowest. This way you can compare all the digits in your number between them. Hope this helps.
Lets start by thinking about this in the logic for now;
You get given a number,
You split the number into an array of numbers,
You loop through that array and store the first digit in a variable,
For all of the next iterations of the array, you compare that index in the array with what's stored in the variable, and if it's smaller, you overwrite the variable with the new number, if not, continue,
Return the number in the variable
Here's some Pseudocode that should help you out a little, you can convert it into python yourself
number = 98918
numberArray = number.split
smallest = numberArray[0]
for (digit in numberArray){
if (digit < smallest){
smallest = digit
}
}
print(smallest)
You have made minimum as your local variable so every time it will assign the value as 9. Try to make it global variable.
minimum = 9
def min_dig(num):
global minimum
if num < 10:
return num
min_dig(num // 10)
if num % 10 < minimum:
minimum = num % 10
return minimum
print(min_dig(98918))
Related
I have a function here which converts a number to its constituents.
def breakdown(number):
res = []
multiplier = 1
while number != 0:
digit = (number % 10)*multiplier
number = number//10
multiplier = multiplier*10
res.append(digit)
res.reverse()
return res
Example breakdown(8541) gives [8000, 500, 40, 1].
This program works fine for any positive number, but goes into an infinite loop when provided with a negative integer. Any ideas on how to make it work with any number?
Sample:
Input: breakdown(-4562) should give output: [-4000,-500,-60,-2]
The way the // operator works is that it will round DOWN the quotient. That means that the infinite loop is caused during negative numbers because it will never be 0, it will always be -1.
A potential solution to your problem is to have an if statement that checks whether or not the number is negative, and multiply the digit by -1, while performing the operations as if it were a positive number:
def breakdown(number):
if number > 0:
sign = 1
else:
number *= -1
sign = -1
res = []
multiplier = 1
while number != 0:
digit = (number % 10)*multiplier
number = number//10
multiplier = multiplier*10
res.append(digit * sign)
res.reverse()
return res
Converting my comment to an answer (pardon the silly function name, I'll let you rename them):
def breakdown_possibly_negative_number(number):
return [-x for x in breakdown(-number)] if number < 0 else breakdown(number)
where breakdown is your function. This converts the negative number to positive and takes the negation of the constituent parts while passing positive numbers through unaltered.
I'm trying to study for midterms and am struggling with this problem. The question is this:
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
I've gotten everything except how to return the smaller value in case of a tie.
This is my code and the function closest_power(3,12)keeps going between the exponents 3, and 2 (the correct code will return 2). Any help is much appreciated
def closest_power(base, num):
exponential = base+num/2
increment = 1
while abs(num-base**exponential) >= 0.01:
print ("Exp: {}, Our number = {}, correct number: {}".format(exponential,base**exponential, num))
if num > (num-base**exponential-2) and num < (num-base**exponential):
return expontential-1
if base**exponential > num:
exponential -= 1
else:
exponential += 1
return exponential
print(closest_power(3,12))
Your test for whether num is between two exponents is incorrect, it should be
num > base**(exponential-1) and num < base**exponential
which can also be written as
base**(exponential-1) < num < base**exponential
Also you have a typo,
return expontential-1
should be
return exponential-1
and you should set the starting value as
exponential = (base + num) // 2
to ensure it is an integer, but it would be even more efficient to set it to:
exponential = num // base
In total:
def closest_power(base, num):
exponential = num // base
increment = 1
while abs(num-base**exponential) >= 0.01:
print ("Exp: {}, Our number = {}, correct number: {}".format(exponential,base**exponential, num))
if base**(exponential-1) < num < base**exponential:
return exponential-1
if base**exponential > num:
exponential -= 1
else:
exponential += 1
return exponential
print(closest_power(3,12))
Output:
Exp: 4, Our number = 81, correct number: 12
Exp: 3, Our number = 27, correct number: 12
2
You can rather simplify your problem using log.
Your question is 3**x = 12. Find x?
Apply log
x*log3 = log12
x = log12/log3
Using this approach:
def exp(x,y):
return(int(log(y)/log(x)))
I have this python problem:
Write a program that asks the user for a limit, and then prints out
the sequence of square numbers that are less than or equal to the
limit provided.
Max: 10
1
4
9
Here the last number is 9 because the next square number (16) would be
greater than the limit (10).
Here is another example where the maximum is a square number:
Max: 100 1
4
9
16
25
36
49
64
81
100
But I don't exactly know how to do this. So far I have
maximum = int(input("Max: "))
for i in range(1, maximum):
But don't really know how to process the numbers and squaring them.
Thanks
Edit: I have
maximum = int(input("Max: "))
for i in range(1, maximum):
if i*i <= maximum:
print(i*i)
'''
Ask the user input a limit and
convert input string into integer value
'''
limit = int(input("Please input the limit: "))
'''
Extract the squre root of `limit`.
In this way we discard every number (i) in range [0, limit]
whose square number ( i * i ) is not in range [0, limit].
This step improves the efficiency of your program.
'''
limit = int(limit ** .5)
'''
`range(a, b)` defines a range of [a, b)
In order to exclude zero,
we assign `a = 1`;
in order to include `limit`,
we assign `b = limit + 1`;
thus we use `range(1, limit + 1)`.
'''
for i in range(1, limit + 1):
print(i * i)
I think a while loop may be better suited for this problem.
maximum = int(input("Max: "))
i = 1
while(i*i <= maximum):
print(i*i)
i+=1
First, the simplest change to your existing code is to get rid of that nested loop. Just have the for loop and an if:
for i in range(1, maximum+1):
if i*i > maximum:
break
print(i*i)
Or just have the while loop and increment manually:
i = 1
while i*i <= maximum:
print(i*i)
i += 1
One thing: Notice I used range(1, maximum+1)? Ranges are half-open: range(1, maximum) gives us all the numbers up to but not including maximum, and we need to include maximum itself to have all the numbers up to maximum squared, in case it's 1. (That's the same reason to use <= instead of < in the while version.
But let’s have a bit more fun. If you had all of the natural numbers:
numbers = itertools.count(1)
… you could turn that into all of the squares:
squares = (i*i for i in numbers)
Don’t worry about the fact that there are an infinite number of them; we’re computing them lazily, and we’re going to stop once we pass maximum:
smallsquares = itertools.takewhile(lambda n: n<=maximum, squares)
… and now we have a nice finite sequence that we can just print out:
print(*smallsquares)
Or, if you’d prefer if all on one line (in which case you probably also prefer a from itertools import count, takewhile):
print(*takewhile(lambda n: n<=maximum, (i*i for i in count(1)))
But really, that lambda expression is kind of ugly; maybe (with from functools import partial and from operator import ge) it’s more readable like this:
print(*takewhile(partial(ge, maximum), (i*i for i in count(1)))
You got a few good, detailed answers.
But let's also have some fun, here is a one-line solution:
print(*(x**2 for x in range(1, 1 + int(int(input('Limit: '))**(1/2)))))
I have decided to post the answer that works. Thanks all for the help.
maximum = int(input("Max: "))
for i in range(1, maximum + 1):
if i*i <= maximum:
print(i*i)
THE BELOW PROGRAM IS TO FIND SQUARE VALUE OF GIVE NUMBERS
Enter the value you want to find.(Give a range)
the value you give runs and goes to r command.
i have used for loop in this case.
output will be displayed
give the input
maximum = input("Enter Max: ")
r = range(1, maximum)
Square = maximum * maximum
Execute THE loop
for i in r:
if i * i <= Square:
print (i * i),
I have been challenged with designing a code which validates a GTIN-8 code. I have looked on how to find the equal or higher multiple of a 10 and I have had no success so far, hope you guys can help me!
Here is a small piece of code, I need to find the equal or higher multiple of 10.
NewNumber = (NewGtin_1 + Gtin_2 + NewGtin_3 + Gtin_4 + NewGtin_5 + Gtin_6 + NewGtin_7)
print (NewNumber)
If you mean find the smallest multiple of 10 that is greater than or equal to your number, try
def round_up_by_10s(num):
return -((-num) // 10) * 10
That works for positive and negative numbers, integer or float, in Python 2.x or Python 3.x. It also avoids an if statement and can be written as a one-liner. For a float number it returns a float: surround the return value with an int(...) if you want the returned value to always be an integer.
If you mean find the smallest number that is a multiple of your number and of 10, try
def lcm10(num):
return (10 // gcd(num, 10)) * num
Generally speaking You can find multiples with the modulo operation:
if number % 10 == 0:
do something
I'm guessing you what the smallest multiple of 10 that is higher or equal than NewNumber. If that's the case, do:
last_digit = NewNumber % 10
bigger = NewNumber - last_digit
if last_digit != 0:
bigger += 10
Also, you shouldn't use capital letters to start variable names, those are usually used for classes only.
Trying using this:
# method 1 for integers
n = NewNumber / 10 * 10
if n < NewNumber: n += 10
# method 2 for floats, decimals
import math
n = math.ceil(NewNumber / 10) * 10
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1.
But when number is not a happy number it loops endlessly in a cycle which does not include 1.
i have coded happy number problem in python but the problem is when a number is not happy , then how could i stop the iterating cycle. since it will not end with 1 and will keep on repeating itself.
def happynumber(number):
while(number!=1):
numberstr = str(number) #converting a number to string
index=0
sum=0
while(index!=len(numberstr)):
sum = sum + int(numberstr[index])*int(numberstr[index])
index = index+1
print sum
number = sum
return number
You can detect unhappy numbers with a constant amount of memory. According to Wikipedia, for any positive integer starting point, the sequence will terminate at one, or loop forever at 4, 16, 37, 58, 89, 145, 42, 20, 4. Since no other loops exist, it is easy to test for unhappiness.
def isHappy(x):
while True:
if x == 1:
return True
if x == 4:
return False
x = nextNumberInSequence(x)
You would have to keep a record of all the numbers you have produced so far in the sequence, and if one of them comes up a second time you know you have a loop which will never reach 1. A set is probably a good choice for a place to store the numbers.
As long as the current number has more than 3 digits, it's value decreases in the next iteration. When the number has 3 digits, the maximum value it can take in the next iteration is 3*81 <= 250. So use an array of size 250 and record all the numbers in the sequence that are less than 250. You can then easily detect if you have a duplicate.
This method will return true , if given number is happy number or else it will return false. We are using set here to avoid infinite loop situation.
Input: 19
Output: true
Explanation:
1*1 + 9*9 = 82
8*8 + 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 + 0*0 = 1
public static boolean isHappy(int n) {
Set<Integer> seen = new HashSet<Integer>();
while(n != 1) {
int current = n;
int sum = 0;
while(current != 0) {
sum += (current % 10) * (current % 10);
current /= 10;
}
if(seen.contains(sum)) {
return false;
}
seen.add(sum);
n = sum;
}
return true;
}