Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
import random
for i in range(5):
print(random.randint(1, 10))
Is it the number of integers that we want to print? But we didn't specify that it's the number of integers in the code, so how does python understand?
The Python for construct requires a variable name between for and in. Conventional practice is to use _ (underscore) as the variable in cases where a variable is required but not actually used/relevant. Note that _ is a valid variable name.
for i in range(5):
do this action
Is (the Python way of saying
"for each element in range(5)
do this action".
range(5) can be replaced by any iterable collection.
In this example the variable i is not used. We might write
for i in range(5):
print(i)
which would print out all the values from the expression range(5).
As you guessed, i in that code will be the number of random integers to be printed. That is because, in python, the range constructor will generate a sequence of integers when specified in the way you are showing.
If only one argument is specified, python will assume that you want to begin by the number zero, incrementing by one unit until it reaches the number one unit below the specified argument.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to pass a variable '3-123' to a method in python, but if I do str(3-123) I get '-120'. Tried iterating, but I got an error cause it's an int.
You simply pass the string "3-123".
Your expression str(3-123) tells Python to first evaluate what is in parentheses, which is very clearly the arithmetic expression 3-123. That evaluation mandates a subtraction.
UPDATE PER USER COMMENT
Since you just got it returned from REST, then it's already a string. It seems that your problem is that you're building an expression string to be evaluated in SQL. In this case, you need to build the string you're going to send to SQL, at the character level. For this one item you would extend your 3-123 string with quotation marks:
from_rest = "3-123" # In practice, this comes directly from your REST return value.
to_sql = '"' + from_rest + '"'
This leaves you with a variable that contains the string "3-123" -- seven characters, rather than the original five.
Is that what you needed?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
My code is supposed to find the occurrence of words in a text. For some reason, after using this function, the reading method from this specific textwon't work(empty lists for .readlines() method and nothing for .read()). The code is:
def counter(new):
words = dict()
lines=new.readlines()
for line in lines:
text=line.split()
for word in text:
if word not in words:
words[word]=1
else: words[word]+=1
return [tuple(x) for x in words.items()]
I haven't found any mistake that can cause this.
I am assuming new is the result of calling open(..), which should be a file handle that you are passing into the function. Calling readlines() is exhausting it, so trying to read from the file using the same handle won't work. Either open a new handle, or you can call new.seek(0) (better option than opening a completely new handle - although there are some cases where the same handle will be returned again, but lets not dive too deep into that here) to move the index to the beginning of the file.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
While learning python, I could not find the difference between the use of str() and " ".
First code
Second code
With str() function you are changing the number type to String but with "" you just pass the String.
str(3.14) # 3.14 is a number and your are converting it into String.
"3.14" is an String value.
Imagine if you had a variable
pi=3.14
then
str(pi)
would give the result 3.14
whereas
"pi"
would give the result pi. The str() function converts something to its string form. Whereas simple quotes will return the word itself.
str() returns a string representation of an object, while quotation marks indicate the value is a string. To see the difference, consider the following:
x = 3.14
print("x") #outputs the character x
print(str(x)) #string representation of the value of object x
In the first print(), the actual character 'x' is output. This has nothing to with the variable x. However, in the second print(), the value of the object x is converted to a string, so '3.14' is output.
There is no difference between the two. The program will run the same. CodeCademy requires that you use the skills (functions and methods) that it teaches you in that step in order to progress to the next one. The python script doesn't do anything differently, but the CodeCademy code analyzer notices that you didn't accomplish the task the way they wanted you too.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi I have the following text file on which I am using a csv reader:
number,obstacle,location,message
1,gobacktostart,8,Sorry but you've landed on a dangerous number, back to the start for you!
2,movetosquare42,matrix[1][0],The meaning of life is 42 or so they say, and that's where you're headed
I wish to (at the end) retrieve the number 8 from the row that starts 1,gobacktostart,8....etc.
My code is:
def gobacktostart():
with open("obstacles.txt","r") as f:
idnumber="1"
fReader=csv.reader(f)
for row in fReader:
for field in row:
if field==idnumber:
print(row[3])
player1position==row[2]
print(player1position)
and the undesired output however, is:
>>>
Sorry but you've landed on a dangerous number
1
>>>
I do need to read the value into the variable player1position in order to pass it on to another function at a different part of the program.
Any thoughts on solving this logic error? Why is it printing "1", when row[2] refers to the 8. Also, Row[3] seems to execute properly in the previous line....
You are checking for equality not assignment in player position == row[2]