Home > Mobile >  list comprehension always returns empty list
list comprehension always returns empty list

Time:11-20

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

CodePudding user response:

Two things:

  1. 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.

  2. 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
...

CodePudding user response:

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

CodePudding user response:

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
  • Related