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.
Related
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.
i have made a list by using while list and then used if statements. In the first two conditions, the code runs perfectly without any error. But in the third condition it is showing that the list is empty. I have no clue what is wrong here.
CODE:
# time table generator with python
import random
no_of_classes = int(input("Please enter the number of classes in a day: "))
name_of_classes = input("Please enter the subject name/name of classes (please separate then by commas): ")
class_name_list = name_of_classes.split(",")
days_in_week = int(input("Enter the number of days in a week for which the school is working:"))
list_1 = [] `list with the problem`
x = 1
while x <= no_of_classes:
list_1.append(x)
x += 1
final_list = []
for j in range(days_in_week):
subject_list = []
if no_of_classes > len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a - 1), i)
for m in range(no_of_classes - len(class_name_list)):
b = random.choice(class_name_list)
subject_list.append(b)
final_list.append(subject_list)
elif no_of_classes == len(class_name_list):
for i in class_name_list:
a = random.choice(list_1)
subject_list.insert((a-1), i)
final_list.append(subject_list)
else: `having problem with this condition`
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
for k in range(days_in_week):
print(final_list[k])
OUTPUT:
Traceback (most recent call last):
File "/Users/arungupta/Documents/trial (delete).py", line 24, in <module>
a = random.choice(list_1)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py", line 301, in choice
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
THANK YOU FOR YOUR HELP. MUCH APPRECIATED!!!
You just forgot to fill the final_list : final_list.append(subject_list)
else:
temp_class_list = []
list_2 = class_name_list
for m in range(no_of_classes):
n = random.choice(list_2)
a = random.choice(list_1)
list_1.remove(a)
list_2.remove(n)
subject_list.insert((a-1), n)
final_list.append(subject_list)
There are two problems actually:
You forgot final_list.append(subject_list) as noted by Castiell
You emptied list_1, which makes your program crash in the next iteration (and actually, the error message you showed is due to this)
Here is my proposed correction: make a copy of list_1 before you empty it:
else:
temp_class_list = []
list_2_copy = class_name_list.copy()
list_1_copy = list_1.copy()
for m in range(no_of_classes):
n = random.choice(list_2_copy)
a = random.choice(list_1_copy)
list_1_copy.remove(a)
list_2_copy.remove(n)
subject_list.insert((a-1), n)
final_list.append(subject_list)
(I also made a copy of class_name_list because I suspect it is the source of another undiscovered bug)
I am trying to solve this Dynamic Array problem on HackerRank. This is my code:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'dynamicArray' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER n
# 2. 2D_INTEGER_ARRAY queries
#
def dynamicArray(n, queries):
lastAnswer = 0
a = []
array_result = []
for k in range(n):
a.append([])
for i in queries:
x = i[1]
y = i[2]
if i[0] == 1:
seq = ((x ^ lastAnswer) % n)
a[seq].append(y)
elif i[0] == 2:
seq = ((x ^ lastAnswer) % n)
lastAnswer = a[seq][y]
array_result.append(lastAnswer)
return array_result
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
q = int(first_multiple_input[1])
queries = [] # 1 0 5, 1 1 7, 1 0 3, ...
for _ in range(q):
queries.append(list(map(int, input().rstrip().split())))
result = dynamicArray(n, queries)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
I am getting a runtime error:
Traceback (most recent call last):
File "Solution.py", line 50, in
fptr.write('\n'.join(map(str, result)))
TypeError: 'NoneType' object is not iterable
Can anyone help me with this, I can't seem to find a solution.
This is the input:
2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
Thanks.
Update: It seems like this input is working now, thanks to #cireo but the code is not working for other test cases. What the problem with this code?
you can try this, it works totally fine.(no runtime error)
Replace your dynamicArray function with this code. Hopefully this will be helpful for you (^_^).
def dynamicArray(n, queries):
col = [[] for i in range(n)]
res = []
lastanswer = 0
for q in queries:
data = (q[1]^lastanswer)%n
if q[0] == 1:
col[data].append(q[2])
elif q[0] == 2:
ind_x = q[2]%len(col[data])
lastanswer = col[data][ind_x]
res.append(lastanswer)
return res
The answer to your question lies in the boilerplate provided by hackerrank.
# The function is expected to return an INTEGER_ARRAY.
You can also see that result = dynamicArray(n, queries) is expected to return a list of integers from map(str, result), which throws the exception.
In your code you do print(lastAnswer), but you probably want
+ ret = []
...
- print(lastAnswer)
+ ret.append(lastAnswer)
+ return ret
instead.
Since you do not return anything, the function returns None by default, which cannot be iterated over by map.
def dynamicArray(n, queries):
# Write your code here
arr=[[]for i in range(0,n)]
lastAnswer=0
answers=[]
for query in queries:
if query[0]==1:
idx= (query[1]^lastAnswer)%n
arr[idx].append(query[2])
if query[0]==2:
idx= (query[1]^lastAnswer)%n
lastAnswer= arr[idx][query[2]% len(arr[idx])]
answers.append(lastAnswer)
return answers
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
here is my code :
if __name__ == '__main__':
n = int(input())
for i in range(n):
name = input()
score = float(input())
python_students = [[name, score]]
z=len(python_students)
for i in range(z):
if python_students[i][1]<python_students[i+1][1]:
list = [python_students[1]]
list.sort()
print(list)
error : Traceback (most recent call last):
File "solution.py", line 9, in <module>
if python_students[i][1]<python_students[i+1][1]:
IndexError: list index out of range
i am literally confused with this type of error , kindly explain and help me with this code.
i am trying to fetch names in alphabetical order from the list
z should be len(python_students)-1. At the last iteration, python_students[i+1][1] goes outside the bounds of the list.
Below is simplifed code, your code has lots of loopholes. you shouldn't use list to store list elements, since list is build class provided by python. its not good practice. also use append to append elements into the list.
if __name__ == '__main__':
python_students = []
n = int(input())
for i in range(n):
name = input()
score = float(input())
python_students.append([name,score])
#python_students = [[name, score]]
z=len(python_students) - 1
p_s = []
for i in range(0,z):
if python_students[i][1]<python_students[i+1][1]:
p_s.append(python_students[1])
p_s.sort()
print(p_s)