I'm trying to find all three digit armstrong numbers in python.
My script for this is
import re
a=[x for x in range(100, 1000)]
m = [int(e) for e in re.search((a),",")]
print(m)
z=((m[0]^len(m))+(m[1]^len(m))+(m[2]^len(m)))==m
print(z)
When i try to run this code it returns
Traceback (most recent call last):
File "ppc1-1 (2).py", line 3, in <module>
m = [int(e) for e in re.search((a),",")]
File "/usr/lib/python3.6/re.py", line 182, in search
return _compile(pattern, flags).search(string)
File "/usr/lib/python3.6/re.py", line 289, in _compile
p, loc = _cache[type(pattern), pattern, flags]
TypeError: unhashable type: 'list'
My objective is to find all three digit armstrong numbers.
You can find the armstong number in the following way.
The review of your code:
1)'^' does not mean exponent in python '**' operator is the exponent.
2) How do you expect to iterate over all the three digit numbers without using a loop?
a=[x for x in range(100, 1000)]
for i in a:
m=list(map(int, str(i)))
length=len(m)
z=((m[0]**length)+(m[1]**length)+(m[2]**length))
if z==i:
print("The armstong number is",i)
This is my answer to your issue:
a = [x for x in range(100, 1000)]
for i in range(0, len(a)):
digits = [int(x) for x in str(a[i])]
if (digits[0]**3 + digits[1]**3 + digits[2]**3) == a[i]:
print a[i]
I hope it helps.
This for only to find the three-digit Armstrong numbers in python.
import re
length = 3
arm = [e for e in range(100, 1000) if e == ((e/100)%10)**length + ((e/10)%10)**length + (e%10)**length]
print arm
Related
This is the list I have :
list_input = [432567,876323,124356]
This is the Output I need :
List_output = [321456,765212,013245]
like so,
for index, number in enumerate(list_input):
one_number = list_lnput(index)
one_digit_list = list(one_number[0])
and I don't have Idea after this step
This can be solved in a time complexity of O(1) since you're basically asking to subtract a number of 1's from an integer i, where the number is equal to the number of digits of that integer, which can be obtained by calculating int(math.log10(i)) + 1, with which you can produce the same number of 1's with (10 ** (int(math.log10(i)) + 1) - 1) // 9:
import math
def decrement_digits(i):
return i - (10 ** (int(math.log10(i)) + 1) - 1) // 9
so that decrement_digits(432567), for example, would return:
321456
so you can then map the input list to the function for output:
List_output = list(map(decrement_digits, list_input))
divmod can be used to isolate each digit in turn. Remember the decimal positions (1's, 10's, 100's, etc...) to add it back in correctly. This will be messy for zeroes. But we don't have any definition what should happen in that case, so I'm sticking with it.
Putting the logic into its own function makes it easier to write the process as a list comprehension. I think its also easier to read than trying to maintain an index.
def digit_subtract(num):
result = 0
base = 1
while num:
num, remain = divmod(num, 10)
result += (remain-1) * base
base *= 10
return result
list_input = [432567,876323,124356]
List_output = [321456,765212,13245]
test = [digit_subtract(num) for num in list_input]
print(test)
assert test == List_output
The only way to get the output with leading zeros is to cast the intS to strS.
list_input = [432567,876323,124356]
list_output = [''.join(str(int(digit)-1) for digit in str(s))
for s in list_input]
Note that this will result in a ValueError for input with negative numbers:
list_input = [-4306]
list_output = [''.join(str(int(digit)-1) for digit in str(s))
for s in list_input]
print(list_output)
Traceback (most recent call last):
File "/Users/michael.ruth/SO/solution.py", line 2, in <module>
list_output = [''.join(str(int(digit)-1) for digit in str(s))
File "/Users/michael.ruth/SO/solution.py", line 2, in <listcomp>
list_output = [''.join(str(int(digit)-1) for digit in str(s))
File "/Users/michael.ruth/SO/solution.py", line 2, in <genexpr>
list_output = [''.join(str(int(digit)-1) for digit in str(s))
ValueError: invalid literal for int() with base 10: '-'
def permutation_generate(lst):
if len(lst)== 0:
return []
if len(lst)==1:
return [1]
l =[]
for i in range(len(lst)):
m = lst[i]
remLst= lst[:i]+ lst[i+1:]
for p in permutation_generate(remLst):
l.append([m]+p)
return l
data= list(input("Please enter a 3 digits number:\n"))
print("The permutations are:")
for p in permutation_generate(data):
print(*p,sep='', end="")
#TypeError: can only concatenate list (not "int") to list
#What is the solution of the error?
On line 13 your function permutation_generate(remLst) returns a list [1]
and you start iterating over it in a for loop. So p is 1 of type int
thats why on line 14 you get the error trying to concatenate [m]+int won't work. [m]+[p] would work.
And for your task take a look at itertools module of python standard library
I got stuck on this question when I tried solving it using the numpy package. My idea was that I would multiply and keep a list of all the calculations I did of the 3 digit numbers ranging from 100 to 999, then check through the list to see which ones are a palindrome and save them. Finally, I would order the list and get the largest palindrome. Code below shows what I tried to do.
import numpy as np
def void():
list1 = np.array(range(100,999))
list2 = np.array(range(100,999))
k = []
for i,j in zip(list1,list2):
k.append(np.multiply(list1,list2))
b = []
for x in range(0,len(k)):
if(reverseNum(k[x])==k[x]):
b.append(k[x])
print(b)
print(b[-1])
def reverseNum(num):
rev = 0
while(num>0):
rem = num % 10
rev = (rev*10) +rem
num = num // 10
return rev
void()
However, when I try to check if the numbers in the list are a palindrome, I get the following bug:
Traceback (most recent call last):
File "main.py", line 40, in <module>
void()
File "main.py", line 22, in void
if(reverseNum(k[x]),k[x]):
File "main.py", line 31, in reverseNum
while(num>0):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Does this mean that it is not possible to use numpy as a method to solve this problem? If it is, where am I going wrong?
EDIT:
What I have tried so far (since it was asked):
Based on the error messages, I tried using np.equal as well as np.greater instead of checking if(reverseNum(k[x])==k[x]) and num>0 but it gives the same error.
Your issue stems from the your line including the zip. My code below isn't pretty, but attempts to follow your approach loosely.
import numpy as np
def void():
list1 = np.array(range(100,1000)) # you want to include '999'
list2 = np.array(range(100,1000))
k = []
for i,j in zip(list1,list2):
k.append(np.multiply(list1,j))
b = []
for r, row in enumerate(k):
for c, cell in enumerate(row):
if reverseNum(cell)==cell:
b.append(cell)
print(b)
print(max(b))
def reverseNum(num):
rev = 0
while(num>0):
rem = num % 10
rev = (rev*10) +rem
num = num // 10
return rev
void()
A NumPy way assuming the result has six digits (it can't have more, as 9992 is 998001):
import numpy as np
v = np.arange(100, 1000) # the range of three-digit numbers
a = np.outer(v, v) # all the products
print(a[(a // 100000 == a % 10) & # first digit == sixth digit
(a // 10000 % 10 == a // 10 % 10) &
(a // 1000 % 10 == a // 100 % 10)].max())
Prints 906609.
Double checking with pure Python:
>>> max(x*y
for x in range(100, 1000)
for y in range(100, 1000)
if str(x*y) == str(x*y)[::-1])
906609
Why does it have to use numpy?
# test if palindrome based on str
def is_palindrome(number: int):
converted_to_string = str(number)
return converted_to_string == converted_to_string[::-1]
# product of two three-digit numbers
you_right = []
values = []
for x in range(999, 99, -1):
for y in range(999, 99, -1):
product = x*y
if is_palindrome(product):
values.append((x, y))
you_right.append(product)
winner = you_right.index(max(you_right))
print(values[winner])
# output
(993, 913)
Another real NumPy solution, using your way to reverse the numbers (fixing it mostly by using .any() as suggested in the error message, which you stubbornly refused to try).
v = np.arange(100, 1000)
a = np.outer(v, v)
num = a.copy()
rev = num * 0
while (m := num > 0).any():
rev[m] = rev[m] * 10 + num[m] % 10
num[m] //= 10
print(a[rev == a].max())
Without the mask m you get the same result (906609), but it's safer with it. Otherwise products with five digits aren't reversed correctly, like 101*102=10302 becomes 203010 instead of 20301.
this is my code:
num = [x for x in input().split(',')]
for p in num:
x = int(p, 2)
if not x%5:
items.append(p)
print(','.join(items))
And the error is File < input>, line 4, in < module>. Then it states that there's a value error which is what is in the title.
Any help would be appreciated.
Your code as written requires that the input be in the form of binary numbers (0 or 1) separated by commas, e.g. 10100,1010,10,1,100. The error you got indicates that you entered two commas with nothing between them (,,).
You should make sure to strip all whitespaces off and check if each p got at least a value:
_input = '1,,,,, 101, 1, 1011, 10110001 '
#num = [x.strip() for x in input().split(',')] # remove all whitespaces arround the number
items = []
num = [x.strip() for x in _input.split(',')]
for p in num:
if not p: # if p is empty/None, skip it!
continue
x = int(p, 2)
if not x%5:
items.append(p)
print(','.join(items))
Output:
101
Not too sure what is causing this error
Using the Hackerrank 30 day challenge on day 5 and I can't seem to be able to change this so it'll work - I'm not too familiar with placeholders but have a basic understanding of how they work.
#!/bin/python3
import sys
n = int(input().strip())
for i in range(1, 10):
answer = n * i
print("{} x {} = {}".format((n, i, answer)))
Error:
Traceback (most recent call last):
File "solution.py", line 9, in <module>
print("{} x {} = {}".format((n, i, answer)))
IndexError: tuple index out of range
n = int(input().strip())
for i in range(1, 10):
answer = n * i
print("{} x {} = {}".format(n, i, answer)) # changed here
You had a tuple for n,i,answer that was passed into format(). You just need to pass what you want to print and format into the function format(), no need to wrap it in a tuple.