I have been working on a sort of encryption tool in python. This bit of code is for the decryption feature.
The point is to take the given numbers and insert them into a list from where they will be divided by the given keys.
My idea for code is below but I keep getting the out of list index range whenever I try it out. Any suggestions? Keep in mind I'm a beginner:
need = []
detr = raw_input('What would you like decrypted?')
count = 0
for d in detr:
if (d == '.' or d == '!') or (d.isalpha() or d== " "):
count +=1
else:
need[count].append(d)
The problem is you are attempting to overwrite list values that don't exist.
list.append(item) adds item to the end of list. list[index] = item inserts item into list at position index.
list = [0,0,0]
list.append(0) # = [0,0,0,0]
list[0] = 1 # [1,0,0,0]
list[99] = 1 # ERROR: out of list index range
You should get rid of the count variable entirely. You could append None in the case of d==' ' etc. or just ignore them.
The way I understood your description you want to extract the numbers in a string and append them to a list using a for-loop to iterate over each character.
I think it would be easier doing it with regular expressions (something like r'([\d]+)').
But the way joconner said: "get rid of the count variable":
need = []
detr = input('What would you like decrypted?\n')
i = iter(detr) # get an iterator
# iterate over the input-string
for d in i:
numberstr = ""
try:
# as long as there are digits
while d.isdigit():
# append them to a cache-string
numberstr+= d
d = next(i)
except StopIteration:
# occurs when there are no more characters in detr
pass
if numberstr != "":
# convert the cache-string to an int
# and append the int to the need-array
need.append( int(numberstr) )
# print the need-array to see what is inside
print(need)
Related
I'm trying to fill in the index location of my first_guess into my d array but im unsure what goes before the replace array function. need help lol
CODE PIC
I created a new variable called f, and im using the d array as the list varible before the replace function..
I have the location of the first_guess but im unsure how to input that into the replace function to replace the '_' in the d variable with the first_guess.
replace method is for strings, not lists. If you needed replace, you could convert d to a string using d = "".join(d), or use a list comprehension - f = list((y if i == first_guess else i) for i in d)
However you don't need replace for what you are describing. Replace finds all occurences of a string, and replaces it with a different string. You are trying to assign an element to an index, regardless of its current value.
You either need: f = d[:first_guess] + [y] + d[first_guess + 1:], meaning you create a new list that takes all elements from d until index first_guess, then y, and then all elements after index first_guess
or
f = d.copy()
f[first_guess] = y
Which means "f at index first_guess gets assigned y". The reason you need to copy d in the second solution is because list assignment just creates the reference to the list, it doesn't actually a create a new one. So if you didn't copy, changing f would change d.
The issue is that replace method is for strings and not lists. Plus it replaces all instances of a character ('_' in this case) by default and you can't pinpoint the index for which the replacement has to happen.
The solution is to use list indexing to reassign values at specific list index locations that match the index of the guessed letter in the hidden_word.
Below is the code that I have come up with. I'm also a newbie to python code, so I'm pretty sure that there will be a more concise code block for this. My code takes in the possibility of repeated guesses of the same letter and improper prompts and provides appropriate "counter measures" for the same.
Cheers!
hidden_word =input('Enter a word')
x = len(hidden_word)
d = ['_']*x
print(".".join(d))
responses = []
while d.count('_')!=0:
accepted_inputs=('y','n','yes','no')
run = input("Playing? (Y = 'Yes', N = 'No')")
if not run.lower() in accepted_inputs:
print('Wrong input')
continue
if run.lower() == 'y':
guess = input('Take a Guess')
if guess in responses:
print('Already guessed, try something else')
continue
else:
responses.append(guess)
for (n,m) in enumerate(hidden_word):
if (guess == m):
d[n]=guess
print(".".join(d))
else:
break
if d.count('_')==0:
print("Congratulations you guessed it!")
I am making up a code in Python 3.7 in which I need to split an array in chunks.
The array is something similar to the following one:
['1.60500002', '1.61500001', '1.625', '1.63499999','NO',
'1.73500001','1.745', 'NO','2.04500008', '2.05499983']
I am interested to create n different slices (3 in this case) everytime the string 'NO' occurs. Then the output array should be something like:
[['1.60500002', '1.61500001', '1.625', '1.63499999'],
['1.73500001', '1.745'],
['2.04500008', '2.05499983']]
Could someone help me?
You can try iterating through the list, checking if the element is a floating point number and if so adding it to a list and if not creating a new list. Just add up all the lists you've made and that should be it.
def split_str(inp):
array_of_array = []
arr = []
for a in inp:
try:
float(a)
arr.append(a)
except Exception:
array_of_array.append(arr)
arr = []
array_of_array.append(arr)
return array_of_array
loop over the array and if the element is "NO", we split the array until the "NO" element and add it to the output. if we reached the end, the last part would be from the last "NO" to the end.
my_array = ['1.60500002', '1.61500001', '1.625', '1.63499999','NO','1.73500001', '1.745', 'NO','2.04500008', '2.05499983']
output = []
counter = 0
start = 0
for item in my_array:
if item == "NO":
output.append(my_array[start:counter])
start = counter + 1
if counter == len(my_array) - 1:
output.append(my_array[start:counter + 1])
counter += 1
Since the only split indicator is 'NO' this should be easier. All you have to do is check for 'NO' and then create a new list. You also have to handle for the first element scenario as it can be a 'NO' or a number but creation of a new list if it is 'NO' is not required
To create a new list inside a list, you can do examplelist.append([])
Then to access a specific list inside a list, you can mention the list number in square brackets before using append(). eg. examplelist[list_number].append(whatever)
Here is the code I came up with :
#Input
array = ['1.60500002', '1.61500001', '1.625', '1.63499999','NO','1.73500001', '1.745', 'NO','2.04500008', '2.05499983']
#Declaring
result = [] #empty list
list_number = 0 #to access a specific list inside a list
starting_element = True #var to handle starting scenario
for element in array:
#starting scenario
if starting_element:
result.append([])
if element != 'NO':
result[list_number].append(element)
starting_element = False
#NO scenario
elif element == 'NO':
list_number += 1
result.append([])
#Number scenario
elif element != 'NO':
result[list_number].append(element)
print(result)
I am using this code: https://pastebin.com/mQkpxdeV
wordlist[overticker] = thesentence[0:spaces]
in this function:
def mediumparser(inpdat3):
spaceswitch = 0
overticker = 0
thesentence = "this sentence is to count the spaces"
wordlist = []
while spaceswitch == 0:
spaces = thesentence.find(' ')
wordlist[overticker] = thesentence[0:spaces] # this is where we save the words at
thesentence = thesentence[spaces:len(thesentence)] # this is where we change the sentence for the
# next run-through
print('here2')
print(wordlist)
I can't figure out why it just keeps saying list index out of range.
The program seems to work but it gives an error, what am I doing wrong? I have looked through this book by Mark Lutz for an answer and I can't find one.
The "list index out of range" problem is never with list splicing, as shown in this simple test:
>>> l = []
>>> l[0:1200]
[]
>>> l[-400:1200]
[]
so the problem is with your left hand assignment wordlist[overticker] which uses a list access, not slicing, and which is subject to "list index out of range".
Just those 4 lines of your code are enough to find the issue
wordlist = []
while spaceswitch == 0:
spaces = thesentence.find(' ')
wordlist[overticker] = ...
wordlist is just empty. You have to extend/append the list (or use a dictionary if you want to dynamically create items according to a key)
Instead of doing wordlist[overticker] with wordlist being a empty list, you will need to use append instead, since indexing an empty list wouldn't make sense.
wordlist.append(thesentence[0:spaces])
Alternatively, you can pre-initiate the list with 20 empty strings.
wordlist = [""]*20
wordlist[overticker] = thesentence[0:spaces]
P.S.
wordlist[overticker] is called indexing, wordlist[1:10] is called slicing.
we've started doing Lists in our class and I'm a bit confused thus coming here since previous questions/answers have helped me in the past.
The first question was to sum up all negative numbers in a list, I think I got it right but just want to double check.
import random
def sumNegative(lst):
sum = 0
for e in lst:
if e < 0:
sum = sum + e
return sum
lst = []
for i in range(100):
lst.append(random.randrange(-1000, 1000))
print(sumNegative(lst))
For the 2nd question, I'm a bit stuck on how to write it. The question was:
Count how many words occur in a list up to and including the first occurrence of the word “sap”. I'm assuming it's a random list but wasn't given much info so just going off that.
I know the ending would be similar but no idea how the initial part would be since it's string opposed to numbers.
I wrote a code for a in-class problem which was to count how many odd numbers are on a list(It was random list here, so assuming it's random for that question as well) and got:
import random
def countOdd(lst):
odd = 0
for e in lst:
if e % 2 = 0:
odd = odd + 1
return odd
lst = []
for i in range(100):
lst.append(random.randint(0, 1000))
print(countOdd(lst))
How exactly would I change this to fit the criteria for the 2nd question? I'm just confused on that part. Thanks.
The code to sum -ve numbers looks fine! I might suggest testing it on a list that you can manually check, such as:
print(sumNegative([1, -1, -2]))
The same logic would apply to your random list.
A note about your countOdd function, it appears that you are missing an = (== checks for equality, = is for assignment) and the code seems to count even numbers, not odd. The code should be:
def countOdd(lst):
odd = 0
for e in lst:
if e%2 == 1: # Odd%2 == 1
odd = odd + 1
return odd
As for your second question, you can use a very similar function:
def countWordsBeforeSap(inputList):
numWords = 0
for word in inputList:
if word.lower() != "sap":
numWords = numWords + 1
else:
return numWords
inputList = ["trees", "produce", "sap"]
print(countWordsBeforeSap(inputList))
To explain the above, the countWordsBeforeSap function:
Starts iterating through the words.
If the word is anything other than "sap" it increments the counter and continues
If the word IS "sap" then it returns early from the function
The function could be more general by passing in the word that you wanted to check for:
def countWordsBefore(inputList, wordToCheckFor):
numWords = 0
for word in inputList:
if word.lower() != wordToCheckFor:
numWords = numWords + 1
else:
return numWords
inputList = ["trees", "produce", "sap"]
print(countWordsBeforeSap(inputList, "sap"))
If the words that you are checking come from a single string then you would initially need to split the string into individual words like so:
inputString = "Trees produce sap"
inputList = inputString.split(" ")
Which splits the initial string into words that are separated by spaces.
Hope this helps!
Tom
def count_words(lst, end="sap"):
"""Note that I added an extra input parameter.
This input parameter has a default value of "sap" which is the actual question.
However you can change this input parameter to any other word if you want to by
just doing "count_words(lst, "another_word".
"""
words = []
# First we need to loop through each item in the list.
for item in lst:
# We append the item to our "words" list first thing in this loop,
# as this will make sure we will count up to and INCLUDING.
words.append(item)
# Now check if we have reached the 'end' word.
if item == end:
# Break out of the loop prematurely, as we have reached the end.
break
# Our 'words' list now has all the words up to and including the 'end' variable.
# 'len' will return how many items there are in the list.
return len(words)
lst = ["something", "another", "woo", "sap", "this_wont_be_counted"]
print(count_words(lst))
Hope this helps you understand lists better!
You can make effective use of list/generator comprehensions. Below are fast and memory efficient.
1. Sum of negatives:
print(sum( i<0 for i in lst))
2. Count of words before sap: Like you sample list, it assumes no numbers are there in list.
print(lst.index('sap'))
If it's a random list. Filter strings. Find Index for sap
l = ['a','b',1,2,'sap',3,'d']
l = filter(lambda x: type(x)==str, l)
print(l.index('sap'))
3. Count of odd numbers:
print(sum(i%2 != 0 for i in lst))
I want to get the no. of same string in a list
Example
list = ['jack','jeen','jeen']
number_of_jeen = getnumber('jeen',list)
print(number_of_jeen)
Output
2
I have tried this so far
def getnumber(string_var,list):
if any(string_var in s for s in list):
print("This user exits !")
There's a built-in method count that does this.
number_of_jeen = list.count('jeen')
Use Counter from collections:
list = ['jack','jeen','jeen']
count = Counter(list)
print(count['jeen'])
Try just using a simple counter function. The idea is to loop through the list you have. In each iteration you are checking whether or not the name you are looking at is equal to 'jeen' in this case. If it is increment your counter, otherwise just move onto the next name. Below is an example:
listNames = ['jack','jeen','jeen']
occurrences = 0
for i in listNames:
if(i == 'jeen'):
occurrences += 1
print(occurrences)