Southperry.net
Python help thread? - Printable Version

+- Southperry.net (https://www.southperry.net)
+-- Forum: Social (https://www.southperry.net/forumdisplay.php?fid=14)
+--- Forum: Rubik's Cube (https://www.southperry.net/forumdisplay.php?fid=58)
+--- Thread: Python help thread? (/showthread.php?tid=37777)

Pages: 1 2 3


Python help thread? - EarthAdept2 - 2011-03-04

I'm converting a string to an integer value. That was what I was taught, so I dunno. If input() will allow me to get an immediate integer value, I'll keep that in mind. If you have the time to give me a little extra advice to shorten the code, I'd be happy to receive that. But I'm mostly just looking for a confirmation (since it's due today lolol).

For above code:

You can use (if word[0].lower in (insert your conditions here)Smile to shorten up the line.

From what I understand, you're looking to continue the search through the entire string. If that's the case, you need to set up the string index as a variable which will add onto itself in a loop. Ex. Index = index + 1 -> word[index] So this will go through the entire string each letter at a time.

But since this site is full of python pros, I think I'll just leave it for those guys to give you an even shorter method.


Python help thread? - Fiel - 2011-03-05

You don't really need an index for a string in python unless you're going to be doing string splitting:

Code:
x='spam'
for eachLetter in x:
  print(eachLetter)

Code:
s
p
a
m

Code:
from string import *

word = raw_input("Enter the word you would like to have translated: ")
if word[0].lower == "a" or word[0].lower == "e" or word[0].lower == "i" or word[0].lower == "o" or word[0].lower == "u":
    word = word + "-" + "ay"
    print word
elif word[0].lower == "y":
    if word[1] != "a" and word[1] != "e" and word[1] != "i" and word[1] != "o" and word[1] != "u":
        word = word + "-" + "ay"
        print word
    elif word[1] == "a" or word[1] == "e" or word[1] == "i" or word[1] == "o" or word[1] == "u":
        word = word[1:] + "-" + word[0] + "ay"
        print word
elif word[0].lower != "a" or word[0].lower != "e" or word[0].lower != "i" or word[0].lower != "o" or word[0].lower != "u":
        word = word[0:] + "-" + word[0] + "ay"
        print word

Much better:

Code:
def IsVowel(letter):
  return letter in 'aeiouAEIOU'

word = raw_input("Enter the word you would like to have translated: ")
if IsVowel(word[0]):
  word += '-ay'
elif word[0] in 'yY':
  if IsVowel(word[1]): #Always try to assert POSITIVES in code. This makes it easier to debug later.
   word = word[1:] + "-" + word[0] + "ay"
  else:
   word += '-ay'
else:
  word += '-' + word[0] + 'ay'

print(word)

Code:
>>>
Enter the word you would like to have translated: Sunday
Sunday-Say
>>>
Enter the word you would like to have translated: Forget
Forget-Fay
>>>
Enter the word you would like to have translated: Yesterday
esterday-Yay
>>>

Also, make sure you have the parenthesis in there.

word[0].lower()

Otherwise you're going to receive the memory address for the method.

Code:
>>> word = 'X'
>>> word[0].lower
<built-in method lower of str object at 0x01DA7460>
>>> word[0].lower()
x

Lastly, you don't need to import string to get access to the lower method. That's a built-in.


Python help thread? - JPTheMonkey - 2011-03-05

Fiel Wrote:You don't really need an index for a string in python unless you're going to be doing string splitting

Which is what should be going on.

I can get it up to the first consonant, but I have to also strip all others up to the vowel, which is the source of my confusion. Examples would be:

Yvonne = Yvonne-ay
Yesterday = esterday-Yay
Friday = iday-Fray
always = always-ay

And for some reason he (my teacher) also has it checking for double consonants (bulldog) and removing one. Not sure if this was a typo or not, though.


Python help thread? - Fiel - 2011-03-06

Code:
def GetFirstVowelIndex(inputString):
    for i, eachLetter in enumerate(inputString):
        if IsVowel(eachLetter):
            return i
    return -1

Code:
import re

def FindDoubleConsonants(inputString):
    doubleLetters = re.findall('([a-zA-Z])\\1', inputString)
    return [eachDoubleLetter for eachDoubleLetter in doubleLetters if not IsVowel(eachDoubleLetter)]



Python help thread? - EarthAdept2 - 2011-03-14

Simple enough question:

I have two lists. I want to the 2nd one to be a sorted list of the 1st one while keeping the original as it is. Is there a function I can use or would I actually have to separately program it and manually make a new list?

Example of what I don't want happening:
Code:
c = [1,5,6,3,2,10]
c_sorted = c
c_sorted.sort()

print c
print c_sorted

They come out as both being sorted. I'm not quite understanding what's going on here.


Python help thread? - XTOTHEL - 2011-03-14

I believe all you have to do is:

c_sorted = c[:]

and that will clone the list.


Python help thread? - EarthAdept2 - 2011-03-14

Yes, exactly what I hoping for. Thanks a bunch!


Python help thread? - JPTheMonkey - 2011-03-30

New problem: Making the program print a certain number of items per line. Unfortunately I deleted my program that did this, and threw out the print-out when I was cleaning drawers and binders. The program works except for printing the items. I need it to print all the elements of 'lst' but only 7 per line, forwards and backwards.

Here it is:
Code:
lst = []
resp = raw_input("Enter a number to continue or n to exit: ")
while resp[0].lower() != "n":
    lst.append(int(resp))
    resp = raw_input("Enter a number to continue or n to exit: ")
print
print lst
print
lst.reverse()
print lst
print
sm = sum(lst)
print "The sum of the list is ", sm
print
avg = float(sm) / (len(lst))
avg = round(avg, 3)
print "The average of the list is ", avg
print
print "The largest number in the list is ", max(lst)
print
print "The smallest number in the list is ", min(lst)



Python help thread? - Fiel - 2011-03-30

http://docs.python.org/library/pprint.html


Python help thread? - JPTheMonkey - 2011-03-30

Not understanding what they're saying. Just started Python in August as a school course. I dislike those database type things because they are hard for me to understand. Tried messing with the examples they had and am not getting what I need.


Python help thread? - Alley - 2011-03-30

JPTheMonkey Wrote:Not understanding what they're saying. Just started Python in August as a school course. I dislike those database type things because they are hard for me to understand. Tried messing with the examples they had and am not getting what I need.

I feel you. Half of what my teacher gives me is total crap that never works for his assignments.


Python help thread? - Fiel - 2011-04-01

JPTheMonkey Wrote:Not understanding what they're saying. Just started Python in August as a school course. I dislike those database type things because they are hard for me to understand. Tried messing with the examples they had and am not getting what I need.

Or you could do this:

Code:
STEPPING = 7
lst = [x for x in range(40)] #Just setting up an example array
for x in range(0, len(lst), STEPPING):
    if x + STEPPING > len(lst):
        print(lst[x:])
    else:
        print(lst[x:(x+STEPPING+1)])



Python help thread? - Nikkey - 2011-04-02

EarthAdept2 Wrote:They come out as both being sorted. I'm not quite understanding what's going on here.

seq.sort() sorts the current sequence. seq.sorted() returns a sorted version of seq without modifying seq itself.

Code:
c = [1,5,6,3,2,10]
c_sorted = c.sorted()

print c
print c_sorted



Python help thread? - JPTheMonkey - 2011-04-06

Old thing, but my Pig Latin thing needs to do sentences (got that) and punctuation (don't got that). I used methods I could read based off of the response's methods. Fixed the list one, as well. Classmate pointed out eval which I'd entirely forgotten about which helped a lot:
Code:
count = 1
lst = []
resp = raw_input("Enter a number to continue or n to exit: ")
while resp[0].lower() != "n":
    lst.append(eval(resp))
    resp = raw_input("Enter a number to continue or n to exit: ")
print
for a in lst:
    print a,
    if count % 7 == 0:
        print
    count += 1
print
count = 1
lst.reverse()
for b in lst:
    print b,
    if count % 7 == 0:
        print
    count += 1
print
sm = sum(lst)
print "The sum of the list is ", sm
print
avg = float(sm) / (len(lst))
avg = round(avg, 3)
print "The average of the list is ", avg
print
print "The largest number in the list is ", max(lst)
print
print "The smallest number in the list is ", min(lst)

As for the sentence, I have:
Code:
sent = raw_input("Enter the sentence you would like to have translated: ")
broken = sent.split( )
for aword in broken:
    p1 = ""
    x = 0
    if aword[-1] in ["!", ".", "?", ",", ":", ";"]:
        aword = aword[:len(aword) - 1]
        punct = aword[-1]
    elif aword[0].lower() == "a" or aword[0].lower() == "e" or aword[0].lower() == "i" or aword[0].lower() == "o" or aword[0].lower() == "u":
            aword = aword + "-" + "ay"
            print aword,
    elif aword[0].lower() == "y":
        if aword[1] != "a" and aword[1] != "e" and aword[1] != "i" and aword[1] != "o" and aword[1] != "u":
            aword = aword + "-" + "ay"
            print aword,
        elif aword[1] == "a" or aword[1] == "e" or aword[1] == "i" or aword[1] == "o" or aword[1] == "u":
            aword = aword[1:] + "-" + aword[0] + "ay"
            print aword,
    elif aword[0].lower() != "a" and aword[0].lower() != "e" and aword[0].lower() != "i" and aword[0].lower() != "o" and aword[0].lower() != "u":
        for eachLetter in aword:
            if not eachLetter in "aeiouAEIOU":
                 p1 = p1 + eachLetter
                 x = x + 1
            else:
                break
        aword = aword[x:]
        aword = aword + "-" + p1 + "ay"
        print aword,

What comes out with a punctuation mark:
Code:
This program translates a word entered by the user into Pig Latin.

Enter the sentence you would like to have translated: The rabbit ran from the wolf.
e-Thay abbit-ray an-ray om-fray e-thay
>>>

The last word is omitted entirely. I can't figure out where I should have it add the last word, either.


Python help thread? - Alley - 2011-04-12

So, basically I have to return a string backwards. So if I input "Cookies are freaking good.", it has to return, ".doog gnikaerf era seikooC".


Here's what I think has to be done, but it isn't working.
Quote:def backwards_word(words):
index = 0
while index <= len(words):
letter = words[index]
print letter
index -= 0

words = raw_input("Word: ")

backwards_word(words)



Python help thread? - XTOTHEL - 2011-04-12

don't know too much python...but I think you can try

"index -= 1", instead of 0. or just "index--"

also you want it to be "index = len(words)"

and "while index <= 0"

you actually don't need letter, just do "print words[index]"

Code:
def backwards_word(words):
    index = len(words)
    while index <= 0:
       print words[index]
       index --
        
words = raw_input("Word: ")

backwards_word(words)

IDK HOW INDENTING WORKS, so figure that part out yourself.


Python help thread? - JPTheMonkey - 2011-04-12

Code:
words = "I am a cookie."
index = -1
for x in words:
    print words[index],
    index -= 1

This works, but with one extra space. Not sure how to get rid of that.


Python help thread? - Fiel - 2011-04-12

Use [noparse]
Code:
, not [quote][/noparse] when inputting code.

[quote=Alley]So, basically I have to return a string backwards. So if I input "Cookies are freaking good.", it has to return, ".doog gnikaerf era seikooC".


Here's what I think has to be done, but it isn't working.[/QUOTE]

[code]
def backwards_word(words):
     index = 0
     while index <= len(words):
          letter = words[index]
          print letter
          index -= 0 #Did you mean += 1 here? -= 0 doesn't change the index at all

words = raw_input("Word: ")

backwards_word(words)

Or you could use some Python-fu and do this:

Code:
inputString = "Cookies are freaking good."
inputString = inputString[::-1]
print(inputString)

@JPTheMonkey

Do:

sent.split(" ")

Alternatively:

Code:
import re

sent = raw_input("Enter the sentence you would like to have translated: ")
words = re.findall("\w+", sent)
print(words)



Python help thread? - Alley - 2011-04-13

None of that works. Closest is the revision XTOTHEL did. I think I had that earlier, it is giving the same output as I was getting originally before I started to tinker with it. I get the first letter of the input then the backwards input, but it is horizontal, then I get a traceback error. So it looks like this:
Code:
Word: crap
c
p
a
r
c

Traceback (most recent call last):
  File "G:\python\backwards.py", line 10, in <module>
    backwards_word(words)
  File "G:\python\backwards.py", line 4, in backwards_word
    letter = words[index]
IndexError: string index out of range



Python help thread? - Fiel - 2011-04-13

Start with -1, not with 0

Code:
word = 'crap'
for index in range(-1, -len(word)-1, -1):
    print(word[index]),