i have to write a code for a class where i have to define a function, and the parameters come from an input(). the input is always going to be a string with numbers and letters following each other, in this form :""5 2 S 2 333 A" ". depending on the letter following the 2 numbers, i have to do use a certain function on the two previous numbers. for this i go through the string input and add each element to a list so it is easier to work with them. my issue is, that the first and last element of the last always start/end with a reverse backslash, making it impossible to int() the numbers, and i dont why and how to get rid of them. here is my code, if you know an easier way i would appreciate it but i mostly want to know where the backslashes come from...
def addition(a,b):
return a + b
def soustraction(a,b):
return a - b
def multiplication(a,b):
return a * b
if __name__ == '__main__':
c = input() #here comes the string input
ma_liste = [] #the list where i want to add the elements of my string
for i in range(0, len(c)): #checking each element of the string
if i == 0:
for j in range(len(c)):
if " " in c[i:j+2]:
ma_liste.append(c[i:j+1])
break
else:
for j in range(i,len(c)): #check if there is a space to know where the number ends
if c[i:j+1] == c[i-1:j+2].strip():
ma_liste.append(c[i:j+1])
break
for e in range(len(ma_liste)): #going through the elements of my list
if ma_liste[e].isdigit():
int(ma_liste[e])
if ma_liste[e].isalpha():
if ma_liste[e] == "S":
soustraction(int(ma_liste[e-2]),int(ma_liste[e-1]))
if ma_liste[e] == "A":
addition(int(ma_liste[e-2]),int(ma_liste[e-1]))
if ma_liste[e] == "M":
multiplication(int(ma_liste[e-2]),int(ma_liste[e-1]))
Welcome to SO. Seems like the issue here is that the end of the line '\n' gets appended when you read the data as it is directly. May be convert the whole ndarray to using numpy.asarray dtype=int. This will solve your problem. Hope it helps. :)
import numpy as np
a = ['1','2','3\n']
print(a)
b = np.asarray(a,dtype=np.int)
print(b)
input: ['1', '2', '3\n']
output: [1 2 3]
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!")
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is different in evenness, and return a position of this number.
! Keep in mind that your task is to help Bob solve a real IQ test, which means indexes of the elements start from 1 (not 0)
Examples :
iq_test("2 4 7 8 10") => 3 // Third number is odd, while the rest of the numbers are even
iq_test("1 2 1 1") => 2 // Second number is even, while the rest of the numbers are odd
My Code:
def iq_test(a):
b=[]
c=[]
for i in range(len(a)):
if a[i]%2 == 0:
b.append(a[i])
else:
c.append(a[i])
if len(b)==1:
for i in range(len(a)):
if [a[i]]==b:
return i+1
if len(c)==1:
for i in range(len(a)):
if [a[i]]==c:
return i+1
This works for the given inputs in my IDE, but when I put it in webpage IDE I obtain
Traceback (most recent call last):
File "main.py", line 3, in <module>
Test.assert_equals(iq_test("2 4 7 8 10"),3)
File "/home/codewarrior/solution.py", line 6, in iq_test
if a[i]%2 == 0:
TypeError: not all arguments converted during string formatting
What is the mistake here? Is my code correct?
The parameter given to your function is "2 4 7 8 10". You're iterating over that string and applying a modulo operation, which throws the error you're seeing since Python doesn't do automatic type conversion and can't apply a module to the string "2" (and, if it did, would throw an error at the second iteration when it'd try to apply the modulo operation to " ").
The simplest fix here is to check if it's not a space, then convert to int before the module:
for (i in range (len(a)):
if a[i] != " ":
if int(a[i])%2 == 0:
b.append(a[i])
...
By the way, the index, and range above is not neccessary for strings. You can also iterate over the string directly:
for char in a:
if char != " ":
if int(char)%2 == 0:
b.append(char)
...
You could also split the string into an array and iterate over that:
array = a.split(" ") # results in ["2","4","7","8","10"]
for (item in array):
if int(item)%2 == 0:
b.append(item)
...
In a real world application, I would also opt to check if the character at the current position is convertible to int, but for your case this solution is sufficient.
Also, as someone who recently looked over their own assignments from the first two semesters, get into the habit of using explicitly named variables. e.g instead of b use evenNumbers and instead of c use oddNumbers. This makes your code a lot more readable and better to understand what you did and why.
def iq_test(numbers):
lst = numbers.split()
evens = []
odds = []
for i in lst:
if int(i) % 2 == 0:
evens.append(int(i))
else:
odds.append(int(i))
if len(evens) == 1:
for i in lst:
if int(i) == evens[0]:
return lst.index(i)+1
if len(odds) == 1:
for i in lst:
if int(i) == odds[0]:
return lst.index(i)+1
I got it right
I am wondering if there is a way that I can compare the first letter of the string to the second; then the third to the forth ... etc.
At the moment I have this:
a=0
b=0
string = "GG EZ"
if string[a:b] == string[a+1:b+1]:
print("hello")
It works but is there a more efficient way of doing it?
You can use zip to pair up the elements
s = "GGEZ"
for a, b in zip(*[iter(s)]*2):
if a==b:
print('Hello')
More on this usage of zip here
string = "GG EZ abbdff"
for i in range(0, len(string), 2):
if string[i] == string[i+1]:
print("characters match")
Create a range of every second character in the string. Iterate over the range and compare character at the index i with the following.
Edit: If your string length is an odd number you run into an out of range exception. I let you figure that one out by yourself :)
Recently, I def a function which can compare two words in each wordlist. However, I also found some problems here.
def printcorrectletters():
x=0
for letters in correctanswer:
for letters2 in userinput:
if letters == letters2:
x = x+1
break
return x
In this function, if the correctanswer='HUNTING', and I input 'GHUNTIN', it will show 6 letters are correct. However, I want it compare words' letters 1 by 1. So, it should march 0. For example, 'H' will match first letter of userinput.. and so on.
I also think another function which can solve it by using 'zip'. However, our TA ask me to finish it without things like 'zip'.
If the strings are different lengths, you want to compare each letter of the shorter string:
shortest_length = min(len(correctanswer), len(userinput))
min just gives you the minimum of two or more values. You could code it yourself as:
def min(a, b):
return a if a < b else b
You can index a character in a string, using [index]:
>>> 'Guanfong'[3]
n
So you can loop over all the letter indices:
correct = 0
for index in range(shortest_length):
if correctanswer[index] == userinput[index]:
correct += 1
If you did use zip and sum:
correct = sum(1 for (correct_char, user_char) in zip(correctanswer, userinput)
if correct_char == user_char)
Python provides great facilities for simplifying ideas and for communicating with the computer and programmers (including yourself, tomorrow).
Without zip you can use enumerate() to loop over elements of correctanswer , and get index and element at the same time. Example -
def printcorrectletters():
x=0
for i, letter in enumerate(correctanswer):
if i < len(userinput) and letter == userinput[i]:
x = x+1
return x
Or if even enumerate() is not allowed, simply use range() loop till len(correctanswer) and get elements from each index.
I am working on a python project, where I am required to include an input, and another value (which will be manipulated).
For example,
If I enter the string 'StackOverflow', and a value to be manipulated of 'test', the program will make the manipulatable variable equal to the number of characters, by repeating and trimming the string. This means that 'StackOverflow' and 'test' would output 'testtesttestt'.
This is the code I have so far:
originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
while len(manipulateinput) < len(originalinput):
And I was thinking of including a for loop to continue the rest, but am not sure how I would use this to effectively manipulate the string. Any help would be appreciated, Thanks.
An itertools.cycle approach:
from itertools import cycle
s1 = 'Test'
s2 = 'StackOverflow'
result = ''.join(a for a, b in zip(cycle(s1), s2))
Given you mention plaintext - a is your key and b will be the character in the plaintext - so you can use this to also handily manipuate the pairing...
I'm taking a guess you're going to end up with something like:
result = ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(cycle(s1), s2))
# '\x07\x11\x12\x17?*\x05\x11&\x03\x1f\x1b#'
original = ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(cycle(s1), result))
# StackOverflow
There are some good, Pythonic solutions here... but if your goal is to understand while loops rather than the itertools module, they won't help. In that case, perhaps you just need to consider how to grow a string with the + operator and trim it with a slice:
originalinput = input("Please enter an input: ")
manipulateinput = input("Please enter an input to be manipulated: ")
output = ''
while len(output) < len(originalinput):
output += manipulateinput
output = output[:len(originalinput)]
(Note that this sort of string manipulation is generally frowned upon in real Python code, and you should probably use one of the others (for example, Reut Sharabani's answer).
Try something like this:
def trim_to_fit(to_trim, to_fit):
# calculate how many times the string needs
# to be self - concatenated
times_to_concatenate = len(to_fit) // len(to_trim) + 1
# slice the string to fit the target
return (to_trim * times_to_concatenate)[:len(to_fit)]
It uses slicing, and the fact that a multiplication of a X and a string in python concatenates the string X times.
Output:
>>> trim_to_fit('test', 'stackoverflow')
'testtesttestt'
You can also create an endless circular generator over the string:
# improved by Rick Teachey
def circular_gen(txt):
while True:
for c in txt:
yield c
And to use it:
>>> gen = circular_gen('test')
>>> gen_it = [next(gen) for _ in range(len('stackoverflow'))]
>>> ''.join(gen_it)
'testtesttestt'
What you need is a way to get each character out of your manipulateinput string over and over again, and so that you don't run out of characters.
You can do this by multiplying the string so it is repeated as many times as you need:
mystring = 'string'
assert 2 * mystring == 'stringstring'
But how many times to repeat it? Well, you get the length of a string using len:
assert len(mystring) == 6
So to make sure your string is at least as long as the other string, you can do this:
import math.ceil # the ceiling function
timestorepeat = ceil(len(originalinput)/len(manipulateinput))
newmanipulateinput = timestorepeat * manipulateinput
Another way to do it would be using int division, or //:
timestorepeat = len(originalinput)//len(manipulateinput) + 1
newmanipulateinput = timestorepeat * manipulateinput
Now you can use a for loop without running out of characters:
result = '' # start your result with an empty string
for character in newmanipulateinput:
# test to see if you've reached the target length yet
if len(result) == len(originalinput):
break
# update your result with the next character
result += character
# note you can concatenate strings in python with a + operator
print(result)