For loop list not updating - python-3.x

This should be a simple problem however at the moment I cannot understand why. Below is a simple code that is suppose to stripe of all strings and convert to int. However the results do not agree with what I wrote.
num = ('"28"', '"23"', '"35"', '"50"', 29488)
for i in num:
if type(i) is str:
i = i[1:-1]
print(i)
print(num)
Expected output
28
23
35
50
(28, 23, 35, 50, 29488)
Actual output
28
23
35
50
('"28"', '"23"', '"35"', '"50"', 29488)
Just found out I had a tuple, when I thought it was a list...

There are a few problems to address
Strings are immutable, so you're not really changing anything in the list, you're just reassigning the loop variable
You're not converting anything to ints, only removing characters from strings
If you want to be able to reassign elements within the nums, you need to use an actual list variable
For example
num = ['"28"', '"23"', '"35"', '"50"', 29488]
for i, n in enumerate(num):
if isinstance(n, str):
num[i] = int(n.strip('"'))
print(n)
print(num)

Re-assignment is missing to index position
Tuples are immutable, can not be set values using index position.
You can refer answer given by #cricket_007, also if you want single liner list compression way then refer below -
num = tuple(int(n.strip('"')) if isinstance(n, str) else n for n in num)
Then you will get again new tuple with values converted into int.

Related

What can I do to add a list and sort out all the prime numbers in the list? Python 3

I am creating a program that
accepts an inputted list
finds all the prime numbers and only displays them.
I tried many different methods, many derived from existing prime filters, but they have hardcoded lists rather user-inputted ones.
I just can't seem to get a filter working with inputting a list, then filtering the prime numbers.
my_list = input("Please type a list")
list(my_list)
prime=[]
for i in my_list:
c=0
for j in range(1,i):
if i%j==0:
c+=1
if c==1:
prime.append(i)
return (prime)
When you get input, you're getting a string. You can't cast a string to a list immediately. Maybe you can request the user to use a separator between the numbers then use split method and cast strings to integers like this:
my_list = input("Please enter the list of numbers and use space seperator")
s_list = my_list.split()
cast_list = [int(num) for num in s_list]
Then, you can work on your prime number task based on your preferred algorithm.
Not sure what your c variable is for, current_number? Your loop returns 'str' object cannot be interpreted as an integer for me. I have used len(my_list) to get the length for the loop.
range() defines as range(start, stop, step) - learn more - it accepts integers and parameters are partially optional.
I copied the code from https://www.codegrepper.com/code-examples/python/how+to+find+prime+numbers+in+list+python
my_list = input("Please type a list")
primes = []
for i in range(0, len(my_list)):
for j in range(2, int(i ** 0.5) + 1):
if i%j == 0:
break
else:
primes.append(i)
print(primes)
More helpful resources from SO: Python function for prime number
I hope this helps.

Palindrome problem - Trying to check 2 lists for equality python3.9

I'm writing a program to check if a given user input is a palindrome or not. if it is the program should print "Yes", if not "no". I realize that this program is entirely too complex since I actually only needed to check the whole word using the reversed() function, but I ended up making it quite complex by splitting the word into two lists and then checking the lists against each other.
Despite that, I'm not clear why the last conditional isn't returning the expected "Yes" when I pass it "racecar" as an input. When I print the lists in line 23 and 24, I get two lists that are identical, but then when I compare them in the conditional, I always get "No" meaning they are not equal to each other. can anyone explain why this is? I've tried to convert the lists to strings but no luck.
def odd_or_even(a): # function for determining if odd or even
if len(a) % 2 == 0:
return True
else:
return False
the_string = input("How about a word?\n")
x = int(len(the_string))
odd_or_even(the_string) # find out if the word has an odd or an even number of characters
if odd_or_even(the_string) == True: # if even
for i in range(x):
first_half = the_string[0:int((x/2))] #create a list with part 1
second_half = the_string[(x-(int((x/2)))):x] #create a list with part 2
else: #if odd
for i in range(x):
first_half = the_string[:(int((x-1)/2))] #create a list with part 1 without the middle index
second_half = the_string[int(int(x-1)/2)+1:] #create a list with part 2 without the middle index
print(list(reversed(second_half)))
print(list(first_half))
if first_half == reversed(second_half): ##### NOT WORKING BUT DONT KNOW WHY #####
print("Yes")
else:
print("No")
Despite your comments first_half and second_half are substrings of your input, not lists. When you print them out, you're converting them to lists, but in the comparison, you do not convert first_half or reversed(second_half). Thus you are comparing a string to an iterator (returned by reversed), which will always be false.
So a basic fix is to do the conversion for the if, just like you did when printing the lists out:
if list(first_half) == list(reversed(second_half)):
A better fix might be to compare as strings, by making one of the slices use a step of -1, so you don't need to use reversed. Try second_half = the_string[-1:x//2:-1] (or similar, you probably need to tweak either the even or odd case by one). Or you could use the "alien smiley" slice to reverse the string after you slice it out of the input: second_half = second_half[::-1].
There are a few other oddities in your code, like your for i in range(x) loop that overwrites all of its results except the last one. Just use x - 1 in the slicing code and you don't need that loop at all. You're also calling int a lot more often than you need to (if you used // instead of /, you could get rid of literally all of the int calls).

Convert numbers string in list to number int

In Python, I want to convert all strings in a list to integers.
So if I have:
list1 = ['10,20,30']
How do I make it:
list1 = [10,20,30]
try this:
list1 = [int(i) for i in list1[0].split(',')]
First of all you have to define what the array contains, for how you have wrote the questions the array is:
0: 10,20,30
if your array is made of strings like that then you should make a regex to identify the numbers in every string and then convert the number into an integer.
But I think that your array is actually:
0: 10
1: 20
2: 30
In this case you would want to do:
for every number in the array
make the number an integer
which would be
for num in list:
# if the value is a string
if type(num) == str: # just to be sure
num = int(num)
In python every data type is easily changeable through int, float or str, but remember to assign the number after you have converted it.
int(num) would make a number an integer but would not actually convert it because have not stored it, you should do num = int(num) because those are functions that return what to want, to really understand how they works mean you should search about dynamically typed languages and functions

using bisect with tuples in python

I am trying to understand the use of bisect function in the python's bisect module and how to use it with tuples. I have seen that it takes a list and a value to find the index to place the value. In my case the value is a tuple. This is from leetcode 981 https://leetcode.com/problems/time-based-key-value-store/. A is a list of tuple and the tuple will contain (int,string) as its data.
class TimeMap(object):
def __init__(self):
self.M = collections.defaultdict(list)
def set(self, key, value, timestamp):
self.M[key].append((timestamp, value))
def get(self, key, timestamp):
A = self.M.get(key, None)
if A is None: return ""
i = bisect.bisect(A, (timestamp, chr(127)))
return A[i-1][1] if i else ""
I understand what they are trying to do for solving the question . I just want to understand why use chr(127). I tried using None but it gives an error. I am guessing that it will always take the first int value in the tuple because the chr(127) will always be unqualified somehow for bisect to accept. But I am not able to find the correct reason for this. also IDLE shows chr(127) as \x7f and found out its a non ascii character.
Python compares tuples element by element and from left to right. For example:
(1, 2) > (1, 1) is True
(1, 2) > (1, 2) is False
I guess, they use chr(127), to make the second item in the tuple larger than any other character.
(1, chr(127)) > (1, 'z') is True
finally found some understanable solution in leetcode discussion forum. all credits go to leetcode users
https://leetcode.com/slvher/ and https://leetcode.com/jcodem/
The ascii code range of lower char is [97, 122], thus chr(127) can be used to make sure the located index from bisect.bisect(A, (timestamp, chr(127))) can satisfy the condition: timestamp_prev <= timestamp. In fact, chr(ascii_v) can also be used here where ascii_v's range is [123, 127].

TypeError: list indices must be integers or slices, not str. While selecting item from loop for

I´ve been trying for a while to select an item from a list with the variable of the for loop. But I keep getting this error:
TypeError: list indices must be integers or slices, not str
The issue dissapears when I change the i for a number, but that's not what I want to do. I´ve been looking for similar issues but couldn't manage to get it working. Advise please.
I want this to result as: ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5']
listcont=[]
cont=0
while cont<=5:
for i in list:
listcont.append(list[i]+str(cont))
cont+=1
return listcont
n=5
list=['q','p']
print(concat(list,n))´´´
First, when you write for i in list you're already iterating over the elements of the list, not the indices. So you can use the item directly:
listcont.append(i + str(cont))
Second, you shouldn't name things list since it shadows the built-in of that name and will cause all kinds of trouble.
Third, the while loop would be better written as a for with a range
n = 5
my_list = ['q', 'p']
listcont = []
for counter in range(1, n+1):
for item in my_list:
listcont.append(item + str(counter))
Finally, you can simplify all of this into a list comprehension and make it look neater with an f-string:
def make_list(my_list, limit):
return [f'{item}{counter}' for counter in range(1, limit+1) for item in my_list]
make_list(['p', 'q'], 5)
When you use for loop, you must know that if you are using for i in list it means that i here is the element of the list, and the loop will traverse each element of the list.
While, what you want to do is for i in range(len(list)), this will traverse the list with i as a number which can gain a value, less than or equal to len(list) - 1.
You can learn this very basic thing about for loop here and hold yourself back from asking such questions.
Hope it helps, thanks.
You have a variable called list which is a bad idea because list is the type of a list in Python. But this isn't the issue. I'm guessing the function you have there, which is missing the declaration, is the function def concat(list, n), and you intended to write while cont <= n.
If all this is the case, when you do
for i in list:
i is going to be members of the list, so 'q', then 'p'. In this case list['p'] doesn't make any sense.
To get the output you're going for I would do (to be easy to read):
def concat(lst, n):
result = []
for i in range(n):
for v in lst:
result.append('{}{}'.format(v, i+1))
return result
You could do the whole thing in one line with:
['{}{}'.format(value, count + 1) for count in range(n) for value in lst]

Resources