I have an object x
print(x)
1
1
2
print(type(x).__name__)
int
int
int
How do I extract only the first 1 from it. If I try x[0], I get the following message
TypeError: 'int' object is not subscriptable
I found a lot of questions about the error but none of the solutions worked for me.
Here is the stdin from where x was read
3
1 2 3
1 3 2
2 1 3
Here is how it was read
q = int(input().strip())
for a0 in range(q):
x,y,z = input().strip().split(' ')
x,y,z = [int(x),int(y),int(z)]
Typically you store them in a container (for example a list) during the loop in case you want to access them later on.
For example:
q = int(input().strip())
res = []
for a0 in range(q):
x,y,z = input().strip().split(' ')
res.append([int(x),int(y),int(z)])
print(res) # all x, y and z
or to access specific elements:
print(res[0][0]) # first x
print(res[1][0]) # second x
print(res[0][1]) # first y
Related
making a function that recieves numbers separated by spaces and adds the first element to the rest, the ouput should be a list of numbers if the first element is a number
i'm trying to remove all non numeric elements of list b
examples- input: 1 2 3 4
output: [3, 4, 5] (2+1, 3+1, 4+1)
input: 1 2 b 4
output: [3, 5] (2+1,b is purged, 4+1)
input: a 1 2 3
output: Sucessor invalido
linha = input()
a = linha.split()
b = [x for x in (a[1:]) if type(x)==int]
b = [eval(x) for x in b]
c = eval(a[0])
d = []
d.append(c)
f = d*len(b)
def soma():
if type(c)!= int: return print("Sucessor invalido")
else: return list(map(lambda x, y: x + y, b, f))
g = soma()
g
> this condition always returns an empty list
if type(x)==int
sorry if im not clear, i started learning recently
Two things:
The results of input are always strings. When you split the string, you end up with more strings. So even if that string is '7', it is the string 7, not the integer 7.
If you want to check if an object is of a type, use isinstance(x,int) rather than type(x)==int.
To accomplish what it looks like you are doing, I dunno if you can get it with list comprehension, since you probably want a try:...except:... block, like this.
linha = input()
a = linha.split()
b = [] #empty list
for x in a[1:]: # confusing thing you are doing here, also... you want to skip the first element?
try:
x_int = int(x)
b.append(x_int)
except ValueError:
pass
...
You need to convert the numbers separated by lines to integers, after checking that they are valid numberic values like this:
b = [int(x) for x in (a[1:]) if x.isnumeric()]
this is because your input will be a string by default, and split() will be just a list of strings
Your input is string, you need to cast it to int and then do calculation to append it to a new list.
The function should check for the index 0 first using str.islpha() method. If it's an alphabet, return invalid input.
Use try except when iterating the input list. If some element can't be cast to int it will continue to the next index.
def soma(linha):
if linha[0].isalpha():
return f"Sucessor invalido"
result = []
for i in range(len(linha) - 1):
try:
result.append(int(linha[0]) + int(linha[i+1]))
except ValueError:
continue
return result
linha = input().split()
print(soma(linha))
Output:
1 2 3 4
[3, 4, 5]
1 2 b 4
[3, 5]
a 1 2 3
Sucessor invalido
I got a "input.txt" file that contains lines like:
1 66.3548 1011100110110010 25
Then i apply some functions column by column:
column stays the same,
column is rounding in a spesific way,
column is converted from binary to decimal,
column is converted from hexadecimal to binary.
And finaly i get this:
[1.0000000e+00 6.6340000e+01 4.7538000e+04 1.0010100e+05]
Then i write this to "fall.txt".
All the operations is working correctly. But i want to see the numbers like:
1 66.34 47538 100101
I placed the columns of the relevant rows in list_for_1. Then i applied the functions to indexes and put them to another list list_for_11. Finally i put all the answers in a matrix. I wrote the matrix to the "fall.txt".
Here's what i did:
with open("input.txt", "r") as file:
#1. TİP SATIRLAR İÇİN GEREKLİ OBJELER
list_for_1 = list()
list_for_11 = list()
#list_final_1 = list()
for line in file:
#EĞER SATIR TİPİ 1 İSE
if line.startswith("1"):
line = line[:-1]
list_for_1 = line.split(" ") #tüm elemanları 1 listede toplama
#1. tip satır için elemanlara gerekli işlemlerin yapılması
list_for_11.append(list_for_1[0]) #ilk satır 1 kalacak
list_for_11.append(float_yuvarla(float(list_for_1[1]))) #float yuvarlama
list_for_11.append(binary_decimal(list_for_1[2])) #binary'den decimal'e
list_for_11.append(hexa_binary(list_for_1[3])) #hexa'dan binary'e
m = 0
n = 0
array1 = np.zeros((6,4))
for i in list_for_11: #listedeki elemanları matrise yerleştirme
if(m > 5):
break
if(isinstance(i, str)):
x = int(i, 2)
array1[m][n] = float(i)
n += 1
if(n == 4):
n = 0
m += 1
with open("fall.txt","w") as ff:
ff.write(str(array1))
ff.write("\n")
Over here i actually send float type to matrix but it's not working:
if(isinstance(i, str)):
x = int(i, 2)
array1[m][n] = float(i)
I'm sort of a new python user, so i might write unnecessarily long and complex codes. If there's any shorter way to do what i did, i would like to get opinions for that as well.
Here's a function to format your numbers the way you want them:
def formatNumber(num):
if num % 1 == 0:
return int(num)
else:
return num
Your list of numbers:
l = [1.0000000e+00, 6.6340000e+01, 4.7538000e+04, 1.0010100e+05]
Reformatting your list of numbers:
for x in l:
print(formatNumber(x))
Output:
1
66.34
47538
100101
n = int(input())
arr = map(int, input().split())
setA = set(arr)
for x in setA:
x.sorted()
print(x)
Here is the error that I am facing
5
9 8 7 4
Traceback (most recent call last):
File "C:\Users\jnnim\OneDrive\Desktop\hacker rank\practice\untitled1.py", line 6, in <module>
x.sorted()
AttributeError: 'int' object has no attribute 'sorted'
Requirements for the program
You are given n scores. Store them in a list and find the score of the runner-up.
The first line contains n elements. The second line contains an array of integers each separated by a space.
In this program for loop, I have tried that within setA, because we have to sort setA.
I had made the array in set because it does not keeps duplicate element.
Finally when I have to find out the runner up score then I will call [-1] index and make it print as runner up score.
If you need to know more about question please comment, I will tell you anything you need.
Please help me solve this error in this program only within these lines. Don't give a full solution
First off, it's sorted(x), not x.sorted. Second of all, you can sort a list, not a number.
You need to do this: x = sorted(setA).
This code will work:
n = int(input())
arr = map(int, input().split())
arrset = set(arr)
runnerup = 0
for index, val in enumerate(sorted(arrset), start=1):
if index == len(arrset) - 1:
runnerup = val
print(runnerup)
n = int(input())
arr = (int, input().split())
arrlist = []
for t in arr:
arrlist.append(t)
num=arrlist[1]
test_list = [int(i) for i in num]
test_sorted= (sorted(test_list, reverse=True))
List = []
for i in test_sorted:
if i != max(test_sorted):
List.append(i)
print(max(List))
I want to write a for loop that iterates over variables and updates their values.
for example:
x = 1
y = 1
for varNames in [x,y]:
varNames = varNames + 1
print(x)
print(y)
Here I want to have the function print the value 2 for both x and y, but my output is still 1. It is because the varNames variable gets updated but not x and y. How do I update the values for actual variable names x and y?
Thanks for the help!
At the global level (i.e. not within a function) you could do this using the globals() function.
x = 1
y = 1
for varName in ["x","y"]:
globals()[varName] += 1
print(x) # 2
print(y) # 2
However, if you need to do that kind of thing in your program, you might want to learn more about lists and dictionaries which would be the preferred approach.
data = dict()
data["x"] = 1
data["y"] = 1
for varName in data:
data[varName] = data[varName] + 1
print(data["x"]) # 2
print(data["y"]) # 2
You can just make a list containing the variables and then you can iterate over them and print each object of the list.
x = 1
y = 3
mylist=[x,y]
for index in mylist:
print(index)
Below is the code(I know below code is wrong syntax just sharing for understanding requirement) I am using to test multiple for loop.
server = ['1']
start = 2
end = 4
for x in range(start, end + 1) and for y in serverip:
print x
print y
Requirement.
for loop iterations must not cross server list length or range .
Input 1
start = 2
end = 4
server list length = 1 that is server = ['1']
expected output 1:
print
x = 2
y = 1
Input 2
start = 2
end = 4
server list length = 2 that is server = ['1','2']
expected output 2:
print
x = 2
y = 1
x = 3
y = 2
Input 3
start = 1
end = 1
server list length = 2 that is server = ['1','2']
expected output 3:
print
x = 1
y = 1
Please help.
The easiest way is to use the built-in zip function suggested in the comments. zip creates a list, or an iterator in python 3, with the iterators “zipped” together. Until one of the iterators runs out.
server = ['1']
start = 2
end = 4
for x, y in zip(range(start, end + 1), server):
print x
print y
Output:
2
1
https://docs.python.org/2/library/functions.html#zip :
This function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables. The
returned list is truncated in length to the length of the shortest
argument sequence.