M.S. 53 Light Poster

something like this maybe:

def hairpin(seq):
    print seq==seq[::-1]

hairpin(raw_input("Enter RNA Sequence: "))
M.S. 53 Light Poster

split the RNA sequence at the midline and reverse the second part then compare the 2parts.
something like a function that takes the sequence and returns the following:

return sequence[:len(sequence)/2]==sequence[len(sequence)/2:][::-1]
M.S. 53 Light Poster

sorry for the typo. please correct line 5 like this:

if query == "y":
M.S. 53 Light Poster

no need to open and close the file several times. for names printing in different lins you can strip the end of line symbol. a simple function is what I would use:

import random

def name_gen()
    query = raw_input("Whould you like to generate a random name? y/n")
    if query == "y" 
        a = random.randint(1, 10)
        b = random.randint(1, 10)
        first_name = open ( 'fname.txt' ).readline(a).strip("\n") 
        last_name = open ( 'lname.txt' ).readline(b).strip("\n")
        print(first_name, last_name)
        name_gen()

name_gen()

there are more solutions that far more expert people here can provide. so condider this post as one option from a novice that I am.
btw, I have not tested this and just posted it as it came to my mind :D

M.S. 53 Light Poster

@ Jacklittle01:
A friendly Advise, Spamming at the board and asking a question many times is waste of time. I think it'd be better to start learning Python by first reading some tutorials or introductory texts then pick up simple practices for every method, data type and so on.
after doing those all, jump into more complex and or multistep programs.

Good luck and Enjoy Pythoning ;-)

M.S. 53 Light Poster

Interesting! thanks for the better and more accurate solution.
btw, my code only found 5 matches! I'm confused. whould you please explain what is wrong?

M.S. 53 Light Poster

How the following code can be rewritten in a better way?

 #!/usr/bin/env python

"""Simple program for finding popular names
over last 100 years, in response to vegaseat's
last post in Projects for Beginners(9/1/2012).

It first lists the popular names and then search
for entered name by user"""

oldnames = """Mary,Helen,Margaret,Anna,Ruth
Elizabeth,Dorothy,Marie,Florence,Mildred
Alice,Ethel,Lillian,Gladys,Edna
Frances,Rose,Annie,Grace,Bertha
Emma,Bessie,Clara,Hazel,Irene
Gertrude,Louise,Catherine,Martha,Mabel
Pearl,Edith,Esther,Minnie,Myrtle
Ida,Josephine,Evelyn,Elsie,Eva
Thelma,Ruby,Agnes,Sarah,Viola
Nellie,Beatrice,Julia,Laura,Lillie
Lucille,Ella,Virginia,Mattie,Pauline
Carrie,Alma,Jessie,Mae,Lena
Willie,Katherine,Blanche,Hattie,Marion
Lucy,Stella,Mamie,Vera,Cora
Fannie,Eleanor,Bernice,Jennie,Ann
Leona,Beulah,Lula,Rosa,Ada
Ellen,Kathryn,Maggie,Doris,Dora
Betty,Marguerite,Violet,Lois,Daisy
Anne,Sadie,Susie,Nora,Georgia
Maude,Marjorie,Opal,Hilda,Velma"""

newnames = """Emily,Madison,Emma,Hannah,Abigail
Olivia,Ashley,Samantha,Alexis,Sarah
Elizabeth,Isabella,Alyssa,Grace,Lauren
Taylor,Jessica,Brianna,Kayla,Sophia
Anna,Natalie,Victoria,Chloe,Sydney
Jasmine,Hailey,Megan,Rachel,Morgan
Julia,Destiny,Ava,Jennifer,Kaitlyn
Mia,Katherine,Alexandra,Haley,Savannah
Nicole,Maria,Allison,Mackenzie,Stephanie
Brooke,Amanda,Ella,Makayla,Faith
Kaylee,Jenna,Andrea,Katelyn,Mary
Jordan,Gabrielle,Rebecca,Paige,Madeline
Kimberly,Trinity,Zoe,Michelle,Sara
Lily,Kylie,Alexa,Caroline,Vanessa
Amber,Angelina,Gabriella,Lillian,Riley
Sierra,Danielle,Leah,Jada,Autumn
Erin,Maya,Ariana,Audrey,Isabel
Sofia,Marissa,Bailey,Jacqueline,Melissa
Claire,Evelyn,Shelby,Jocelyn,Mariah
Avery,Leslie,Melanie,Arianna,Aaliyah"""



old_names = [name.lower() for name in (oldnames.replace("\n", ",").split(","))]

new_names = [name.lower() for name in (newnames.replace("\n", ",").split(","))]


def find_name():
    print "Popullar names in last 100 years:"
    for name in new_names:
        if name in old_names:
            print name
    print "*"*50

    name = raw_input("Enter a name:").lower()

    if (name in old_names) and (name in new_names):
        print name, "is still a popullar name over 100 years"
    elif (name in old_names) and not (name in new_names):
        print name, "is an old name"
    elif (name in new_names) and not (name in old_names):
        print name, "is a new name"
    else:
        print name, "is not in the lists"

find_name()
Lardmeister commented: nice approach +10
TrustyTony commented: Interesting of '\n' -> ',' and split approach +12
M.S. 53 Light Poster
M.S. 53 Light Poster

The very first thing to learn in any situation is THE RULES.
And Python has few rules such as Indentation, Style and.. that you need to learn first.

def some_function():
    #some notes here
    while some_condition:
        if some_other_condition:
            some=process+here
        else:
            some=other*process+here
M.S. 53 Light Poster

Using the SL4A is a simple and good choice, for securing your script you can Compile it as a *.pyc file and run it from another script via importing it. Or, you can make an apk file and then pass it toyour friends.
i think installing SL4A and Py4A is not a hard task and its about installing just two apk files. thats it.

M.S. 53 Light Poster

if you want it to work with every site,I guess you need to consider the encoding too:

print sourcecode.decode("utf8")
M.S. 53 Light Poster

I dont know why but extend adds 'devide' as another list to oper.
I couldn't find "extend" function for lists!

Strange and amazing, using new line in second example somehow works like a "+" opperator. but fails when we use a variable instead of a string.

the below works as the fist one:

c = 'c'
print('a'
         'b'+
         c)
M.S. 53 Light Poster
from os import path

PATH = "folder_path/file.txt"
if path.exists(PATH) and path.isfile(PATH):
    print "File does exist"
else:
      print "File doesn't exist!"
Gribouillis commented: best method +13
M.S. 53 Light Poster

as pyTony said, It only finds the cells containing "CYP", and ignores the cells containing "Cyp"

M.S. 53 Light Poster

I'm not familiar with AT commands, but, what if you use a longer time.sleep()? because those commands are very fast and phone needs more time to respond.

M.S. 53 Light Poster

what that -0 means ;-)

M.S. 53 Light Poster

sorry could'nt edit.my post because of timeout.

color = raw_input ( "Input a color component character: ").strip().lower()
if color in "rgb" and color != "":
    print "You have input a color component"
else:
    print "You have not input a color component"
M.S. 53 Light Poster

PyScripter is the best one in my opinion. it supports many versions of Python

code.google.com/p/pyscripter/

M.S. 53 Light Poster

a simple table:

subjects = [ 'maths' , 'fyzics' , 'history' ]
header = "<h4>Study Subjects</h4><table>"
footer = "</table>"

def write():
    f = open( 'vysvedcenie_test.html' , 'w' )
    f.write(header)
    for subject in subjects:
        body = "<tr><td>%s</td></tr>"%subject
        f.write(body)
    f.write(footer)
    f.close()
M.S. 53 Light Poster

yes, but pys60 2 is not popular and is rarely used among symbian users, thats the reason why I was trying to implement this code in pys60 1.45.
btw, I succeded in applying pyPDF in pys60 2.

M.S. 53 Light Poster

@crazy99:
have you ever tried to read documentation or any tutorials?
just vizit the links woooee gave you, then review the answers in this thread, and you'll find out how to solve your problem.

M.S. 53 Light Poster

I couldnt edit the last post, here is the corrected last line:D
any way I really thank you again and sorry for my clumsy English :)

M.S. 53 Light Poster

before all, thank you so much for your help pyTony,
about pyPDF, unfortunately cant use it on my mobile, because Python-symbian or pys60 is based on python 2.2.2 and pyPDF module works only on python 2.4 and up.
and yes, the output is not what I expected.

any way, this doent

M.S. 53 Light Poster

dear pyTony, whould you please do this task for me?, I'ld really appreciate it.
I myself tried many times but messed the whole code up.
I'm actually not familiar with OOP, and all my experience is with functions.

thanks again.

M.S. 53 Light Poster

yes line 6 to 26 got an extra tab indentation, its my mistake in pasting the code(those lines have to be unindented one tab)

really thank you dear pyTony for your kind reply.
if you please make all those as a function that asks the user for each one, say:

   def opts(self):
       opt1 = raw_input('enter page size')
       opt2= ...
       optN= raw....
       return opt1, opt2,..., optn

OR of course something that you think is better,
then I can manage them and change them further for a mobile interface like a setting form or read/write from a setting file.

again thank you so much

M.S. 53 Light Poster

Hi

I found this script from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189858

it uses getopt module for managing cmd arguments, but I need it to work on mobile phones. I want to make a Mobile app using this script but I cant figure out how to change the comand Args to simple raw_inputs. can somebody please help me in this(i.e. removing parseArgs() and argsCallBack()?

I know that its not a polite request, but I really appreciate any help.

thanks in advance

class pyText2Pdf:

    def __init__(self):
        # version number
        self._version="1.1.1"
            self._IsoEnc=0
            # formfeeds flag
            self._doFFs=0
            self._progname="PyText2Pdf"
            self._appname = "".join((self._progname, " Version ", str(self._version)))
            # default font
            self._font="/Courier"
            # default font size
            self._ptSize=10
            # default vert space
        # iso encoding flag
            self._IsoEnc=0
            # formfeeds flag
            self._doFFs=0
            self._progname="PyText2Pdf"
            self._appname = "".join((self._progname, " Version ", str(self._version)))
            # default font
            self._font="/Courier"
            # default font size
            self._ptSize=10
            # default vert space
        self._vertSpace=12
        self._lines=0
        # number of characters in a row
        self._cols=80
        self._columns=1
        # page ht
        self._pageHt=792
        # page wd
        self._pageWd=612
        # input file 
        self._ifile=""
        # output file 
        self._ofile=""
        # default tab width
        self._tab=4
        # input file descriptor
        self._ifs=None
        # output file descriptor
        self._ofs=None
        # landscape flag
        self._landscape=0

        # marker objects
        self._curobj = 5
        self._pageObs = [0]
        self._locations = [0,0,0,0,0,0]
        self._pageNo=0

        # file position marker
        self._fpos=0

    def argsCallBack(self, argslist, listoftuples=False):
        """ Callback function called by argument parser.
        Helps to remove duplicate code """

        x = 0
        while x<len(argslist):
            item = argslist[x]

            if listoftuples:
                o, a = item
            else:
                o = item

            if o == '-h':
                self.ShowHelp()
            elif o == '-I': …
M.S. 53 Light Poster

for printing all even numbers bellow 412 you can do this:

~~~for i in range(0,412):
if i%2==0:
print i~~~

and for a specific list of numbers:

~~~for num in num_list:
if (num<412) and (num%2==0):
print num~~~

M.S. 53 Light Poster

I'm using Samsung galaxy tab, with Opera, Dolphine browser, Android default browser, UCweb browser with a variety of virtual keyboards, but no luck.

M.S. 53 Light Poster

these tricks might work for a Desktop, but not for a mobile user.
I use my phone for coding, making threads and posting in the forum and unfortunately these new changes in daniweb, makes it a hard job.
there is no ctrl+a then indent or any other shortcuts on my phones python shell or other code editors.

M.S. 53 Light Poster
def middle(name):
    names = name.split(' ')
    if not (len(names) <=2):
        middle_names = names[1:-1]
        return ' '.join(middle_names)
    else:
        return 'There is no middle name in %s'%name

print middle("Michael smith Jordan Jones")
print middle("Michael Jordan Jones")
print middle("Michael Jordan")
print middle(raw_input("Enter a name"))

Note: it is assumed that the "name" entered has no extra spaces.

M.S. 53 Light Poster

here is what comes to my mind, but you need to add some codes to take the inputs and check their correctness:

import random

def distance(minlen, maxlen, steps):
    total_distance = 0
    step_count = 0
    while step_count < steps:
        step_length = random.randint(minlen, maxlen)
        total_distance += step_length
        step_count += 1
    return total_distance
  
print distance(2, 6, 100)
M.S. 53 Light Poster

for writing into file, I suggest codecs:

import codecs
out_file = codecs.open("some_file.txt", 'w', 'utf8')
out_file.write('español')
M.S. 53 Light Poster

@snippsat:

thank you dear snippsat.
I unmarked the thread back to unsolved to ask just one more question.
regex method is great but can you please tell how can I manage the re expression to extract the CELL's first number for every vCard(instead of VOICE numbers).

thanks again

M.S. 53 Light Poster

YES! it worked greatly thank you bros.

M.S. 53 Light Poster

oh thanks PyTony, I didnt notice other changes you made to that code.
Ill try your revision and tell the result from the whole 250 vcards file.

M.S. 53 Light Poster

thank you Gribouillis for your kind reply, but unfortunately it doesnt work on my mobile.

regex may help but im totaly unfamilliar with regexp.


@PyTony: this code of mine is very poor and cant handle a file with multiple vcards and also vcards with extra lines like the third one I pasted in the first post.

M.S. 53 Light Poster

I tried many times but no luck. I want to parse a text file with a vcard format (from my phone contacts).

the text file looks like this:

BEGIN:VCARD
VERSION:2.1
REV:20110913T095232Z
UID:aac119d5fe3bc9dc-00e17913379d6cc8-3
N;X-EPOCCNTMODELLABEL1=First name:;Maj;;;
TEL;VOICE:09120000000
X-CLASS:private
END:VCARD
BEGIN:VCARD
VERSION:2.1
REV:20110228T083215Z
UID:aac119d5fe3bc9dc-00e17b0693898c98-4
N;X-EPOCCNTMODELLABEL1=First name:;Ali jahan;;;
TEL;VOICE:09120000001
X-CLASS:private
END:VCARD
BEGIN:VCARD
VERSION:2.1
REV:20110228T083510Z
UID:aac119d5fe3bc9dc-00e17b069df653a0-5
N;X-EPOCCNTMODELLABEL0=Last name;X-EPOCCNTMODELLABEL1=First name:Eqlimi;Mostafa;;;
TEL;CELL;1:+989120000002
TEL;VOICE:09180000003
X-CLASS:private
TEL;CELL;2:09390000004
X-CLASS:private
END:VCARD

I pasted three different pieces of data and i bolded the info i want to extract.
the output i like to have is a dict like this:
name_numbers = {'Maj':'09120000000', 'Ali jahan':'09120000001', 'Eqlimi Mostafa':'09120000002'}

the code i made so far is:

data = open('contacts.vcf', 'r')
name = ''
number = ''
if data:
    for l in data:
        if l.startwith('N;'):
            name = l.split(':')[1].strip(';')
        if l.startwith('TEL'):
            number = l.split(':')[1]
    print "%s: %s"%(name, number)

P.S: Im using python on my phone and the python on my phone is python 2.2.2

by the way, I need this for a free application for symbian nokia phones and its not a homework.

thanks in advance for any help

M.S. 53 Light Poster
def generateNumber(num):
    result = []
    for i in range(num+1):
        result.append(i)
    return result
M.S. 53 Light Poster

you can write scripts or develop apps in python for android; but they need the sl4a and py4a to run.

it is necessary to have them installed in order to run python apps.

M.S. 53 Light Poster

there are some ports of python for cellphones:

PyS60 for Symbian phones(you can find many many apps written in python for this OS)

Python for MeeGo.

python for Maemo

Python for Android a.k.a Py4A based on SL4A project

M.S. 53 Light Poster

in python 2.x:

test = []
for i in raw_input("Enter numbers separated by a coma(,):").split(','):
    test.append(int(i))
neg_sum(test)

EDIT: sorry Moders, while I was posting, it got solved.

M.S. 53 Light Poster

it could be much shorter:

#User and Pass files:

userN = open('username.txt', 'r').read()
pasN = open('password.txt', 'r').read()

# First make your Functions and Then Use Them the way you want:

def username():
    pin = raw_input ("Please insert your username: ")
    while True:
        if pin == userN:
            print 'You Did It!'
            break
        else:
            print 'Wrong Username!!!'
            return

def password():
    pin = raw_input ("Please insert your password number: ")
    while True:
        if pin == pasN:
            print 'Correct!\nNow Enter Username'
            username()
            break
        else:
            print 'Wrong Password!!!'
            return

password()
M.S. 53 Light Poster

Edit Timed Out!!!

Heres the result:

This program calculates a numeric value for a name.


----------
w = 23
i = 9
l = 12
l = 12
i = 9
a = 1
m = 13
s = 19
s = 19
m = 13
i = 9
t = 20
h = 8
----------
williams = 98
----------
smith = 69
----------
williams smith = 167

M.S. 53 Light Poster

My Beginners' Solution:

def main():
    print "This program calculates a numeric value for a name.\n"
    first, last = raw_input("Enter your first and last name (with a space): ").lower().split()
    print "\n","-"*10
    totalFirst = 0
    totalLast = 0
    for ch in first:
        totalFirst += ord(ch)-96
        print ch,"=",ord(ch)-96

    for ch in last:
        totalLast += ord(ch)-96
        print ch,"=",ord(ch)-96

    print "-"*10,"\n",first,"=",totalFirst
    print "-"*10,"\n",last,"=",totalLast
    print "-"*10,"\n",first,last, "=",totalFirst+totalLast

main ()
M.S. 53 Light Poster

oh sorry I didnt noticed the space(" " instead of "") char in newMessage's default value.
I corrected it and its OK now.

M.S. 53 Light Poster

Also that "+=" what is that? We have not covered this at all. Is there another way of possibly doing it without using this.

that "+=" means add something to original variable.
You can use something like this: newMessage = newMessage + (str(encoded) + " ")

a = "Hello"
a+=" World"
print a

#is the same with:

a = "Hello"
b = " World"
a = a + b

print a

But as I said Lets wait for masters' reply

M.S. 53 Light Poster

Let's wait for masters to give you a more efficient Hint.
but for now this works for me:

#declare and initialize variables
#string message
newMessage = "" # why three variables
#Intro

print(",---.                   |              ,---.                              ")
print("|--- ,---.,---.,---.,---|,---.,---.    |---',---.,---.,---.,---.,---.,-.-.")
print("|    |   ||    |   ||   ||---'|        |    |    |   ||   ||    ,---|| | |")
print("`---'`   '`---'`---'`---'`---'`        `    `    `---'`---|`    `---^` ' '")
print("                                                      `---'               ")


#Prompt the user for the message
message = raw_input("Please enter the message you would like to encode: ")# Or just input in python 3.x

#Loop through message
for ch in message:
    encoded = ord(ch)* 6 - 5
    newMessage += str(encoded)+ " "

#Print and calculate the new value of message
print(newMessage)

#Open a the file “encryptedmessage.txt”
outfile = open("encryptedmessage.txt", "w")

#Write to file “encryptedmessage.txt”
outfile.write(newMessage)

#Close the file
outfile.close()
M.S. 53 Light Poster

A hint:
(Im a newbie too:D)

message = raw_input('Enter Message:')

newMessage = ''
for char in message:
    crypted = ord(char)
    newMessage += str(crypted)

outfile = open('CryptedMessage.txt', 'w')
outfile.write(newMessage)
outfile.close()
M.S. 53 Light Poster

for the other part of your question:

word = raw_input('word: ')
word.split()
print '*'.join(word)+'*'

#>>> H*E*L*L*O*
M.S. 53 Light Poster

Yesss! thats it:D
my problem solved with pyTony's Set class.
Thanks so much