I am trying to create a function that will add two list such that if list1 is [9,1,2] and list2 is [8,5,3] then the two lists added together would produce a list yielding. ]1,7,6,5] since 912+853= 1765.
The following is the code I have written:
def list_addition(list1,list2):
otlist1=''
otlist2=''
for items1 in list1:
otlist1+= items1
for items2 in otlist2:
otlist2+= items2
strinum = int(otlist1)+ int(otlist2)
return strinum
print(list_addition(['3','6','7'], ['4','9','0']))
I keep getting this error:
Traceback (most recent call last):
File "C:/Users/Chuck/PycharmProjects/arrayaddition/Arrays.py", line 13, in <module>
list_addition(['3','6','7'], ['4','9','0'])
File "C:/Users/Chuck/PycharmProjects/arrayaddition/Arrays.py", line 10, in list_addition
strinum = int(otlist1)+ int(otlist2)
ValueError: invalid literal for int() with base 10: ''
I obviously know my code even if it did work as written wouldn't be complete as I would still need to put in the final codes to convert the integer variable 'strinum' back to a list, but I can't get there if my code is failing to properly add the two converted lists. When I break down the code and write the two for loops separately, convert them to integers and add them everything works perfectly fine. So the code below was good:
list1=['7','9','6']
otlist1=''
for items1 in list1:
otlist1+= items1
print(otlist1)
ist1=['5','7','0']
otlist2=''
for items1 in ist1:
otlist2+= items1
print(otlist2)
print(int(otlist1) + int(otlist2))
But for some reason when I try to put the two for loops inside a single function I get the error. I am a complete newbie to programming and I want to know what I am not understanding about function syntax. Any help will be greatly appreciated.
Related
I'm trying to open a txt file and get all the words in it, assign it to a list, and filter the list of duplicates. The code in the snippet is what I thought would work, but I'm getting a traceback error and it says list index is out of range. How can I modify my code to avoid that error?
Any help is appreciated.
fname = input("Enter file name: ")
fh = open("romeo.txt")
lst = list()
for line in fh:
nlst = (line.rstrip()).split()
lst = lst + nlst
for i in [*range(len(lst))]:
if lst.count(lst[i]) > 1:
while lst.count(lst[i]) > 1:
print(lst[i])
lst.remove(lst[i])
else:
continue
print(lst)
edit 1:
Okay so I thought the cause of the problem was lst.count(lst[i]) having a value of one or more and the inequality is (>1) so it's saying that it's out of range, but I tried 0 instead of 1, and it still gave me the same error.
vsc snippet
but i'm getting a traceback error and it says list index is out of range
First, whenever you're asking about a traceback, include the actual error message in your question. In this case, that looks like:
Traceback (most recent call last):
File ".../countwords.py", line 9, in <module>
if lst.count(lst[i]) > 1:
~~~^^^
IndexError: list index out of range
There are several issues that get us into this situation. Broadly, you're iterating over the number of words in the document. For each word, you're using lst.count to find occurrences of the word in lst...and then removing duplicates. Whenever you find a duplicate, lst gets shorter, but your outer loop doesn't know this. Eventually, you ask for lst[i] when i is larger than the length of the list and your code explodes.
We can fix this while preserving your current logic by making a couple of changes.
First, let's fix that outer loop; you've written for i in [*range(len(lst)], but that's operationally equivalent to for i in range(lst), which is simpler to read.
Instead of trying to update lst, let's populate a new variable lst_no_dupes; this avoids issues with modifying lst while at the same time trying to iterate over it:
Instead of using lst.count, we can use the in operator to check for the presence of a word in a list.
Those changes get us:
lst_no_dupes = []
for i in range(len(lst)):
if lst[i] not in lst_no_dupes:
lst_no_dupes.append(lst[i])
print(lst_no_dupes)
This works, but it's inefficient, because checking to see if a word is contained in the list is an O(n) operation. As the number of words grows larger, it will take longer and longer to look up items in the list.
There's a much simpler way to produce a list of unique items from a list as long as you don't care about their order: just turn them into a set:
fh = open("romeo.txt")
lst = list()
for line in fh:
nlst = (line.rstrip()).split()
lst = lst + nlst
lst = set(lst)
print(lst)
A set is "an unordered collection of distinct objects"; lookups in a set are O(1) so the time required to check for a duplicate is independent of the number of words.
Ultimately, you could simplify everything down to this:
with open('romeo.txt') as fh:
lst = set(word for line in fh for word in line.split())
print(lst)
Here, we're iterating over lines in the file (for line in fd) and then words in each line (for word in line.split()). This is an example of a generator expression (which is like a list comprehension).
I'm new at Python and trying some exercises I found on-line. The one I'm busy with requires an text input first, folowed by an ineteger input.
I get stuck on the integer input which raises an error.
I've started by modifying the code slightly to test myself when I first got the error.
Eventually changed it backed to be exactly like the example/exercise had it, but both resulted in the same error, on the same line.
The error raised was:
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
I've checked around a bit and found it get's triggered when the input is empty, but according to what I've read the the rest of the code should handle that.
numOfGuests = int(input())
if numOfGuests:
I expected the code to ask for the input again if nothing was entered, but get the error instead.
Much appreciated.
Update:
I've managed to figure out a work-around, and even though it isn't a answer to my question, I'll take it.
For anyone that's interested, here's what I did:
I changed:
numOfGuests=int(input())
to:
numOfGuests=input()
Only once something was entered did I convert it:
numOfGuests=int(numOfGuests)
so the final block is:
numOfGuests=''
while not numOfGuests:
print('How many guests will you have?')
numOfGuests = input()
numOfGuests=int(numOfGuests)
Any ideas to improve it, or some insight, would be appreciated.
I know this question is 10 months old but I just want to share the reason why you are having an error ValueError.
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
Is because the input() function reads any value and convert it into a string type. Even if you try to input empty or blank.
Sample code:
any_input = input("Input something: ")
print(f"Your input is: [{any_input}]")
Ouput:
Input something:
Your input is: []
Then the blank or empty string will be passed inside the int() function. The int() function will try convert string into an integer with a base of 10. As we all know, there is no blank or empty numbers. That is why it is giving you a ValueError.
To avoid this, we need to use try-except/EAFP in your code:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
except:
# Handle Value Error
And put inside a While-loop to repeat until input is valid.
Sample code:
while True:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
# If input is valid go to next line
break # End loop
except:
# Handle Value Error
print("Invalid input!")
print(f"The number of guest/s is: {numOfGuests}")
Ouput:
How many guest will you have? 3
The number of guest/s is: 3
Basically I have a variable equal to a number and want to find the number in the position represented by the variable. This is what I
numbertocheck =1
loopcriteria = 1
while loopcriteria == 1:
if numbertocheck in ticketnumber:
entryhour.append[numbertocheck] = currenttime.hour
entryminute.append[numbertocheck] = currenttime.minute
print("Thank you. Your ticket number is", numbertocheck)
print("There are now", available_spaces, "spaces available.")
loopcriteria = 2
I get this error (in pyCharm):
Traceback (most recent call last): File
"/Users/user1/Library/Preferences/PyCharmCE2017.3/scratches/scratch_2.py",
line 32, in entryhour.append[numbertocheck] =
currenttime.hour TypeError: 'builtin_function_or_method' object does
not support item assignment
How do I do what I'm trying to do?
Though you haven't provided the complete code, I think you only have problem with using append. You cannot use [] just after an append. To insert into a particular position, you need insert
Putting the relevant lines you need to replace below...
entryhour.insert(numbertocheck,currenttime.hour)
entryminute.insert(numbertocheck,currenttime.minute)
# available_spaces-=1 # guessing you need this too here?
P.S. your loop doesn't seem to make sense, I hope you debug it yourself if it doesn't work the way you want.
How to solve ValueError is not in List problem? I don't understand what is wrong with my code.
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://uk.reuters.com/business/quotes/financialHighlights? symbol=AAPL.O")
bsObj = BeautifulSoup(html,"html.parser")
tag = bsObj.findAll("td")
tagList = []
for tagItem in tag:
tagList.append(tagItem)
print(tagList.index("<td>Dec</td>"))
Error:
Traceback (most recent call last):
File "/Users/home/Desktop/development/x/code.py", line 11, in <module>
print(tagList.index("<td>Dec</td>"))
ValueError: '<td>Dec</td>' is not in list
Process finished with exit code 1
You're creating a list of <class 'bs4.element.Tag'> objects. Their string representation seems to match the string you're looking for, except that objects are not equal since they have different types.
(note that printing the list yields [<td>Dec</td>, <td>Dec</td>], note the absence of quotes, printing the same list but with strings yields ['<td>Dec</td>', '<td>Dec</td>'])
Quickfix: create your list as string
for tagItem in tag:
tagList.append(str(tagItem))
or as list comprehension:
tagList = [str(tagItem) for tagItem in tag]
Now index works: returns "0"
Note that you could keep your list unconverted (if you want to keep the objects, not coerce to strings), and use the following to find the first index compared to a string:
print(next(i for i,x in enumerate(tagList) if str(x)=="<td>Dec</td>"))
I have tried to understand this by looking in previous threads but I still don't understand why I get this error for only one of two variables in the following piece of code (the code sucks I know):
alfaphet=('abcdefghijklmnopqrstuvxyz')
cryptalfaphet=('defghjiklmnopqrstuvxyzabc')
spaceNumber=[]
textCopy=[]
def crypt():
textCopy=[]
print('print the text that you want to encrypt:')
text=input()
for i in range(len(text)):
for j in range(len(alfaphet)):
if text[i]==alfaphet[j]:
textCopy.append(cryptalfaphet[j])
if text[i]==' ':
spaceNumber.append(i)
for i in range(len(spaceNumber)):
for j in range(len(text)):
if list(range(len(text)))[j]==int(spaceNumber[i]):
textCopy.insert(j, ' ')
textCopy=''.join(textCopy)
print(textCopy)
crypt()
This code works fine, but if I remove the
textCopy=[]
asignment from the beginning of the def-block, I get an error like this:
Traceback (most recent call last):
File "C:/Python33/dekrypt.py", line 26, in <module>
crypt()
File "C:/Python33/dekrypt.py", line 13, in crypt
textCopy.append(cryptalfaphet[j])
UnboundLocalError: local variable 'textCopy' referenced before assignment
My question is why this doesn't happen with the spaceNumber variable. spaceNumber is as far I can see also referenced before asignment with the
spaceNumber.append(i)
asignment? It is referenced before the def-block, but so was the textCopy vaiable right? What is the difference, they're both empty lists from the beginning and I use the .append() method on both, but Python seems to treat them differently!?
You can avoid this error by adding the following line at beginning of your function
def crypt():
global textCopy
...
however, this isn't a python best practice. See this post for further details.