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
Related
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))
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),
Just want to apologize in advance for the general coding and logic gore you might encounter while reading this. I recently discovered Project Euler and thought it was fun. I've made it a point to not only find the answer, but make a generic function that could find the answer for any similar case given the appropriate input. For instance, problem number 4, involving palindromes, which can be seen here: https://projecteuler.net/problem=4
Essentially what I did was found a way to multiply every possible combination of numbers given a number of digits, n, then found products that were palindromes. However, anything above 3 digits just takes way too long to process. I believe this is because I used the list() function to take advantage of indexing to determine whether the product was a palindrome. Is there another way to do something of this nature? I feel like this is shoving a square through a circular hole.
Here's the function in question.
def palindrome(n):
number = 0
for i in range(0,n):
number = number + 9 * pow(10, i)
a = pow(10, n - 1) - 1
b = pow(10, n - 1)
while a * b < number * number:
a = a + 1
b = a
while b <= number:
c = a * b
b = b + 1
digits = list(str(int(c)))
lastdigits = digits[::-1]
numdigits = len(digits)
middle = int((numdigits - (numdigits % 2)) / 2) - 1
if numdigits > 1 and digits[:middle + 1] == lastdigits[:middle + 1] and digits[0] == digits[-1] == '9' and numdigits == 2 * n:
print(c)
"Find the largest palindrome made from the product of two 3-digit numbers."
3-digit numbers would be anything from 100 - 999. One thing about the largest product is guaranteed: The two operands must be as large as possible.
Thus, it would make sense to step through a loop starting from the largest number (999) to the smallest (100). We can append palindromes to a list and then later return the largest one.
When you calculate a product, convert it to a string using str(...). Now, checking for palindromes is easy thanks to python's string splicing. A string is a palindrome if string == string[::-1], where string[::-1] does nothing but return a reversed copy of the original.
Implementing these strategies, we have:
def getBiggestPalindrome():
max_palindrome = -1
for i in range(999, 99, -1):
for j in range(999, i - 1, -1):
prod = i * j
str_prod = str(prod)
if str_prod == str_prod[::-1] and prod > max_palindrome:
print(prod)
max_palindrome = prod
return max_palindrome
getBiggestPalindrome()
And, this returns
>>> getBiggestPalindrome()
906609
Note that you can use the range function to generate values from start, to end, with step. The iteration stops just before end, meaning the last value would be 100.
I am attempting to find the closest power of two that is greater than or equal to a target value. A for loop must be used to achieve this. However, I am unsure of what to put as the range value so that upon reaching the required value the exponent will stop increasing by i and instead exit the for loop. Thanks for your help.
target = int(input("Enter target number: "))
def power_of_two(target):
x = 2
change = 0
power = 0
for i in range():
number = x ** change
change = i
if number >= target:
power = number
return power
p = power_of_two(target)
print("The closest power of 2 >= {0:d} is {1:d}." .format(target, p))
since you have to use for:
def power_of_two(target):
if target > 1:
for i in range(1, int(target)):
if (2 ** i >= target):
return 2 ** i
else:
return 1
that is assuming you want the value to be greater than or equal to 2^0
I have corrected your code, so that it works. I think you learn best from your mistakes :)
target = int(input("Enter target number: "))
def power_of_two(target):
x = 2
change = 0
power = 0
for i in range(target+1):
# target is okay for this, function terminates anyway
# add one to avoid error if target=0
number = x ** change
change = i
if number >= target: # you had indentation errors here and following
power = number
return power
p = power_of_two(target)
print("The closest power of 2 >= {0:d} is {1:d}." .format(target, p))
You could find a perfect value for the end of the range using logarithm with base 2, but then you wouldn't need the for loop anyway ;)
As a suggestion: maybe take a look at the binary representation of powers of 2. You could use a for loop with bitshifting for this.
EDIT: I had indentation errors myself, because of the weird formatting system here... maybe you haven't had these before :D
a = []
for i in range(3):
a.append(input())
j = 0
for i in a:
if i % 10 != 7:
j = min(a)
print j
I need an algorithm which finds the smallest positive number in list, which decimal representation does not end with the number 7. It is guaranteed that the list has at least one positive element, which decimal representation does not end with the number 7. I tried this, but condition doesn't work. For example: it says that 7 is smallest in [9,8,7].
You are always testing for the minimum number in a, albeit as many times as there are unfiltered numbers in a. Don't add numbers that end in 7 to a in the first place; you probably want to filter on positive numbers too:
a = []
for i in range(3):
value = input()
if i % 10 != 7 and i >= 0:
a.append(value)
print min(a)
Alternatively, filter out values in a generator expression:
a = []
for i in range(3):
a.append(input())
print min(i for i in a if i % 10 != 7 and i >= 0)
EDIT:
Ok I misreaded your code, you were using remainder which i think is better. Although it could work using just plain divisions like this.
if ((i / 10) - int(i / 10)) * 10 != 7:
And also, if you aren't using Python 3, you might need to use this for the above to work:
from __future__ import division
Or casting to floats with float(), but that makes it too messy.