Beispiel #1
0
 def enter(self):
     print "You do a dive roll into the Weapon Armory, crouch and scan the room" 
     print "for more Gothons that might be hiding. It's dead quiet, too quiet." 
     print "You stand up and run to the far side of the room and find the" 
     print "neutron bomb in its container. There's a keypad lock on the box" 
     print "and you need the code to get the bomb out. If you get the code" 
     print "wrong 10 times then the lock closes forever and you can't"
     print "get the bomb. The code is 3 digits."
     code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
     guess = raw_input("[keypad]> ")
     guesses = 0
     
     while guess != code and guesses < 10:
         print "BZZZZZZZZEDDDDDD"
         guesses += 1
         guess = raw_input("[keypad]> ")
         
     if guess == code:
         print "The container clicks open and the seal breaks, letting gas out." 
         print "You grab the neutron bomb and run as fast as you can to the" 
         print "bridge where you must place it in the right spot."
         return 'the_bridge'
     else:
         print "The lock buzzes one last time and then you hear a sickening" 
         print "melting sound as the mechanism is fused together."
         print "You decide to sit there, and finally the Gothons blow up the" 
         print "ship from their ship and you die."
         return 'death'
Beispiel #2
0
    def enter(self):
        print "You do a dive roll into the Weapon Armory, crouch and scan the room"
        print "for more Gothons that might be hiding. It's dead quiet, too quiet."
        print "You stand up and run to the far side of the room and find the"
        print "neutron bomb in its container. There's a keypad lock on the box"
        print "and you need the code to get the bomb out. If you get the code"
        print "wrong 10 times then the lock closes forever and you can't"
        print "get the bomb. The code is 3 digits."
        code = "%d%d%d" % (randint(1, 9), randint(1, 9), randint(1, 9))
        guess = raw_input("[keypad]> ")
        guesses = 0

        while guess != code and guesses < 10:
            print "BZZZZZZZZEDDDDDD"
            guesses += 1
            guess = raw_input("[keypad]> ")

        if guess == code:
            print "The container clicks open and the seal breaks, letting gas out."
            print "You grab the neutron bomb and run as fast as you can to the"
            print "bridge where you must place it in the right spot."
            return 'the_bridge'
        else:
            print "The lock buzzes one last time and then you hear a sickening"
            print "melting sound as the mechanism is fused together."
            print "You decide to sit there, and finally the Gothons blow up the"
            print "ship from their ship and you die."
            return 'death'
Beispiel #3
0
def page_rank(e=0.0001, depth=99999, scale=3):
    beta = float(raw_input("Beta: "))
    number = int(raw_input("Number of nodes: "))

    formula = []

    for count in range(number * number):
        temp = float(raw_input(">> "))
        formula.append(beta * temp + (1 - beta) / number)

    p = [1 / number] * number
    while True and depth >= 0:
        q = [0] * number
        for i in range(number):
            for j in range(number):
                q[i] += p[j] * formula[i * number + j]
        flag = True
        for count in range(number):
            if abs(p[count] - q[count]) >= e:
                flag = False
                break
        p = q
        depth -= 1
        if flag:
            break
    for i in range(number):
        print(p[i] * scale)
Beispiel #4
0
    def enter(self):
        print "You burst onto the Bridge with the netron destruct bomb"
        print "under your arm and surprise 5 Gothons who are trying to"
        print "take control of the ship. Each of them has an even uglier"
        print "clown costume than the last. They haven't pulled their"
        print "weapons out yet, as they see the active bomb under your"
        print "arm and don't want to set it off."

        action = raw_input("> ")

        if action == "throw the bomb":
            print "In a panic you throw the bomb at the group of Gothons"
            print "and make a leap for the door. Right as you drop it a"
            print "Gothon shoots you right in the back killing you."
            print "As you die you see another Gothon frantically try to disarm"
            print "the bomb. You die knowing they will probably blow up when"
            print "it goes off."
            return 'death'

        elif action == "slowly place the bomb":
            print "You point your blaster at the bomb under your arm"
            print "and the Gothons put their hands up and start to sweat."
            print "You inch backward to the door, open it, and then carefully"
            print "place the bomb on the floor, pointing your blaster at it."
            print "You then jump back through the door, punch the close button"
            print "and blast the lock so the Gothons can't get out."
            print "Now that the bomb is placed you run to the escape pod to"
            print "get off this tin can."
            return 'escape_pod'

        else:
            print "DOES NOT COMPUTE"
            print "the_bridge"
Beispiel #5
0
    def enter(self):
        print "You rush through the ship desperately trying to make it to"
        print "the escape pod before the whole ship explodes. It seems like"
        print "hardly any Gothons are on the ship, so your run is clear of"
        print "interference. You get to the chamber with the escape pods, and"
        print "now need to pick one to take. Some of them could be damaged"
        print "but you don't have time to look. There's 5 pods, which one"
        print "do you take?"

        good_pod = randint(1, 5)
        guess = raw_input("[pod #]> ")
        if int(guess) != good_pod:
            print "You jump into pod %s and hit the eject button." % guess
            print "The pod escapes out into the void of space, then"
            print "implodes as the hull ruptures, crushing your body"
            print "into jam jelly."
            return 'death'
        else:
            print "You jump into pod %s and hit the eject button." % guess
            print "The pod easily slides out into space heading to"
            print "the planet below. As it flies to the planet, you look"
            print "back and see your ship implode then explode like a"
            print "bright star, taking out the Gothon ship at the same"
            print "time. You won!"
            return 'finished'
Beispiel #6
0
    def setup_oauth(self):
        """Authorize your app via identifier."""
        # Request token
        oauth = OAuth1(client_key=TW_API_KEY, client_secret=TW_API_SECRET)
        r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
        credentials = parse_qs(r.content)

        resource_owner_key = credentials.get('oauth_token')[0]
        resource_owner_secret = credentials.get('oauth_token_secret')[0]

        # Authorize
        authorize_url = AUTHORIZE_URL + resource_owner_key
        print('Please go here and authorize: ' + authorize_url)

        verifier = raw_input('Please enter the verifier: ')
        oauth = OAuth1(client_key=TW_API_KEY,
                       client_secret=TW_API_SECRET,
                       resource_owner_key=resource_owner_key,
                       resource_owner_secret=resource_owner_secret,
                       verifier=verifier)

        # Finally, Obtain the Access Token
        r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)
        credentials = parse_qs(r.content)
        token = credentials.get('oauth_token')[0]
        secret = credentials.get('oauth_token_secret')[0]

        return token, secret
Beispiel #7
0
    def enter(self):
        print "You burst onto the Bridge with the netron destruct bomb"
        print "under your arm and surprise 5 Gothons who are trying to" 
        print "take control of the ship. Each of them has an even uglier" 
        print "clown costume than the last. They haven't pulled their" 
        print "weapons out yet, as they see the active bomb under your" 
        print "arm and don't want to set it off."
        
        action = raw_input("> ")
        
        if action == "throw the bomb":
            print "In a panic you throw the bomb at the group of Gothons" 
            print "and make a leap for the door. Right as you drop it a"
            print "Gothon shoots you right in the back killing you."
            print "As you die you see another Gothon frantically try to disarm" 
            print "the bomb. You die knowing they will probably blow up when" 
            print "it goes off."
            return 'death'
            
        elif action == "slowly place the bomb":
            print "You point your blaster at the bomb under your arm"
            print "and the Gothons put their hands up and start to sweat." 
            print "You inch backward to the door, open it, and then carefully" 
            print "place the bomb on the floor, pointing your blaster at it." 
            print "You then jump back through the door, punch the close button" 
            print "and blast the lock so the Gothons can't get out."
            print "Now that the bomb is placed you run to the escape pod to" 
            print "get off this tin can."
            return 'escape_pod'

        else:
            print "DOES NOT COMPUTE"
            print "the_bridge"
Beispiel #8
0
    def setup_oauth(self):
        """Authorize your app via identifier."""
        # Request token
        oauth = OAuth1(client_key=TW_API_KEY, client_secret=TW_API_SECRET)
        r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
        credentials = parse_qs(r.content)

        resource_owner_key = credentials.get('oauth_token')[0]
        resource_owner_secret = credentials.get('oauth_token_secret')[0]

        # Authorize
        authorize_url = AUTHORIZE_URL + resource_owner_key
        print('Please go here and authorize: ' + authorize_url)

        verifier = raw_input('Please enter the verifier: ')
        oauth = OAuth1(client_key=TW_API_KEY,
                       client_secret=TW_API_SECRET,
                       resource_owner_key=resource_owner_key,
                       resource_owner_secret=resource_owner_secret,
                       verifier=verifier)

        # Finally, Obtain the Access Token
        r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)
        credentials = parse_qs(r.content)
        token = credentials.get('oauth_token')[0]
        secret = credentials.get('oauth_token_secret')[0]

        return token, secret
Beispiel #9
0
 def enter(self):
     print "You rush through the ship desperately trying to make it to" 
     print "the escape pod before the whole ship explodes. It seems like" 
     print "hardly any Gothons are on the ship, so your run is clear of" 
     print "interference. You get to the chamber with the escape pods, and" 
     print "now need to pick one to take. Some of them could be damaged" 
     print "but you don't have time to look. There's 5 pods, which one" 
     print "do you take?"
     
     good_pod = randint(1,5)
     guess = raw_input("[pod #]> ")
     if int(guess) != good_pod:
         print "You jump into pod %s and hit the eject button." % guess
         print "The pod escapes out into the void of space, then"
         print "implodes as the hull ruptures, crushing your body" 
         print "into jam jelly."
         return 'death'
     else:
         print "You jump into pod %s and hit the eject button." % guess 
         print "The pod easily slides out into space heading to"
         print "the planet below. As it flies to the planet, you look" 
         print "back and see your ship implode then explode like a" 
         print "bright star, taking out the Gothon ship at the same" 
         print "time. You won!"
         return 'finished'
    def handle_401(self, resp, **kwargs):
        # We only care about 401 responses, anything else we want to just
        #   pass through the actual response
        if resp.status_code != 401:
            return resp

        # We are not able to prompt the user so simple return the response
        if not self.prompting:
            return resp

        parsed = urlparse.urlparse(resp.url)

        # Prompt the user for a new username and password
        username = raw_input("User for %s: " % parsed.netloc)
        password = getpass.getpass("Password: "******"", password or "")(resp.request)

        # Send our new request
        new_resp = resp.connection.send(req, **kwargs)
        new_resp.history.append(resp)

        return new_resp
Beispiel #11
0
    def handle_401(self, resp, **kwargs):
        # We only care about 401 responses, anything else we want to just
        #   pass through the actual response
        if resp.status_code != 401:
            return resp

        # We are not able to prompt the user so simple return the response
        if not self.prompting:
            return resp

        parsed = urlparse.urlparse(resp.url)

        # Prompt the user for a new username and password
        username = raw_input("User for %s: " % parsed.netloc)
        password = getpass.getpass("Password: "******"", password or "")(resp.request)

        # Send our new request
        new_resp = resp.connection.send(req, **kwargs)
        new_resp.history.append(resp)

        return new_resp
Beispiel #12
0
def ask(message, options):
    """Ask the message interactively, with the given possible responses"""
    while 1:
        if os.environ.get("PIP_NO_INPUT"):
            raise Exception("No input was expected ($PIP_NO_INPUT set); question: %s" % message)
        response = raw_input(message)
        response = response.strip().lower()
        if response not in options:
            print("Your response (%r) was not one of the expected responses: %s" % (response, ", ".join(options)))
        else:
            return response
Beispiel #13
0
def ask(message, options):
    """Ask the message interactively, with the given possible responses"""
    while 1:
        if os.environ.get('PIP_NO_INPUT'):
            raise Exception('No input was expected ($PIP_NO_INPUT set); question: {0!s}'.format(message))
        response = raw_input(message)
        response = response.strip().lower()
        if response not in options:
            print('Your response ({0!r}) was not one of the expected responses: {1!s}'.format(
                response, ', '.join(options)))
        else:
            return response
Beispiel #14
0
def ask(message, options):
    """Ask the message interactively, with the given possible responses"""
    while 1:
        if os.environ.get('PIP_NO_INPUT'):
            raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
        response = raw_input(message)
        response = response.strip().lower()
        if response not in options:
            print('Your response (%r) was not one of the expected responses: %s' % (
                response, ', '.join(options)))
        else:
            return response
    def run(self, host, url, time=5000):
        while True:
            print("Connecting to server...")
            question = self.request_question(host, url)

            if question is not None:
                answer = raw_input(question.properties["question"])
                self.post_answer(host, question.links["answer"].url(), answer)
                print("Answer submitted...")
            else:
                print("No question to answer...")
                print("Going to sleep for %d ms..." % time)
                time.sleep(time)
def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="sample (subtract one):\n\n"
                    "#in state 1 saw 1, change it for 1, move right set current state to 1\n"
                    "1 1 1 1 1\n"
                    "# in state 1 saw 0 change it for 0, move left, set current state to 2\n"
                    "1 0 0 -1 2\n"
                    "# in state 2 saw 1 change it for 0, dont move head, set current state to end state\n"
                    "2 1 0 0 0\n"
                    "# in state 2 saw 0 change it for 0, dont move head, set current state to end state\n"
                    "2 0 0 0 0\n")
    parser.add_argument('path', metavar='path', help='path to file with turing machine description')
    parser.add_argument('tape', help='tape state of turing machine (ex: 001110100100')
    parser.add_argument('emptysymbol', help='empty symbol for tape')

    args = parser.parse_args()

    t = Turing()
    t.empty_symbol = args.emptysymbol
    t.load(args.path)

    print ('-=-=-=-=-=-\n{0}:'.format(args.path))
    print(t.show())
    print ('-=-=-=-=-=-\n')

    t.set_tape_array(str(args.tape))
    info_prompt = ''

    while True:
        print('{0}. {4}\n{2}\n'.format(t.step+1,
                                       t.state,
                                       t.show_tape,
                                       t.symbol,
                                       t.rule(t.state, t.symbol)))

        if sys.version_info[0] < 3:
            k = raw_input(info_prompt)
        else:
            k = input(info_prompt)

        if k and k.lower() == 'q':
            break

        if not t.next():
            break
Beispiel #17
0
    def enter(self):
        print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
        print "your entre crew. Your are the last surviving memnber and your last "
        print "mission is to get the neutron destruct bomb from the Weapons Armory"
        print "put it in the bridge, and blow the ship up after getting into an "
        print "escape pod."
        print "\n"
        print "You're running down the central corrider to the Weapons Armory when"
        print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
        print "flowing around his hate filled body. He's blocking thedoor to the"
        print "Armory and about to pull a weapon to blast you."

        action = raw_input("> ")

        if action == "shoot!":
            print "Quick on the draw you yank out your blaster and fire it at the Gothon."
            print "His clown costume is flowing and moving around his body, which throws"
            print "off your aim. Your laser hits his costume but misses him entirely. This"
            print "completely ruins his brand new costume his mother bought him, which"
            print "makes him fly into an insane rage and blast you repeatedly in the face until"
            print "you are dead. Then he eats you."
            return 'death'

        elif action == "dodge!":
            print "Like a world class boxer you dodge, weave, slip and slide right"
            print "as the Gothon's blaster cranks a laser past your head."
            print "In the middle of your artful dodge your foot slips and you"
            print "bang your head on the metal wall and pass out."
            print "You wake up shortly after only to die as the Gothon stomps on"
            print "your head and eats you."
            return 'death'

        elif action == "tell a joke!":
            print "Lucky for you they made you learn Gothon insults in the academy."
            print "You tell the one Gothon joke you know:"
            print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
            print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
            print "While he's laughing you run up and shoot him square in the head"
            print "putting him down, then jump through the Weapon Armory door."
            return 'laser_weapon_armory'

        else:
            print "DOES NOT COMPUTE"
            print "central_corride"
Beispiel #18
0
 def enter(self):
     print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
     print "your entre crew. Your are the last surviving memnber and your last "
     print "mission is to get the neutron destruct bomb from the Weapons Armory"
     print "put it in the bridge, and blow the ship up after getting into an "
     print "escape pod."
     print "\n"
     print "You're running down the central corrider to the Weapons Armory when"
     print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
     print "flowing around his hate filled body. He's blocking thedoor to the"
     print "Armory and about to pull a weapon to blast you."
     
     action = raw_input("> ")
     
     if action == "shoot!":
         print "Quick on the draw you yank out your blaster and fire it at the Gothon."
         print "His clown costume is flowing and moving around his body, which throws"
         print "off your aim. Your laser hits his costume but misses him entirely. This"
         print "completely ruins his brand new costume his mother bought him, which" 
         print "makes him fly into an insane rage and blast you repeatedly in the face until"
         print "you are dead. Then he eats you."
         return 'death'
         
     elif action == "dodge!":
         print "Like a world class boxer you dodge, weave, slip and slide right" 
         print "as the Gothon's blaster cranks a laser past your head."
         print "In the middle of your artful dodge your foot slips and you" 
         print "bang your head on the metal wall and pass out."
         print "You wake up shortly after only to die as the Gothon stomps on" 
         print "your head and eats you."
         return 'death'
     
     elif action == "tell a joke!":
         print "Lucky for you they made you learn Gothon insults in the academy." 
         print "You tell the one Gothon joke you know:"
         print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
         print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
         print "While he's laughing you run up and shoot him square in the head" 
         print "putting him down, then jump through the Weapon Armory door." 
         return 'laser_weapon_armory'
     
     else:
         print "DOES NOT COMPUTE"
         print "central_corride"
Beispiel #19
0
def display_rawurl(session):
    if (len(sys.argv) < 3):
        usage()
    rawurl_id = int(float(sys.argv[2]))
    rawurl = session.query(Rawurl).get(rawurl_id)
    
    if rawurl is None:
        print('No such rawurl')
        return
    
    print('id: %d' % rawurl.id)
    print('downloaded: %s' % str(rawurl.download_date))
    print('state: %d' % rawurl.state)
    print('url: %s' % rawurl.url)
    
    choice = raw_input('display html content? [y/n]: ')
    if choice in ['yes', 'y', 'Y']:
        soup = BeautifulSoup(rawurl.html_content)
        print(soup.prettify())
    elif choice in ['no', 'n', 'N']:
        print('ok')
    else:
        print('assuming no')
Beispiel #20
0
def display_article(session):
    if (len(sys.argv) < 3):
        usage()
    article_id = int(float(sys.argv[2]))
    article = session.query(Article).get(article_id)
    
    if article is None:
        print('No such article')
        return
    
    print('id: %d' % article.id)
    print('date: %s' % str(article.date))
    print('state: %d' % article.state)
    print('source: %s' % article.source)
    print('author: %s' % article.author)
    print('url: %s' % article.url)
    
    choice = raw_input('display content? [y/n]: ')
    if choice in ['yes', 'y', 'Y']:
        print(article.content)
    elif choice in ['no', 'n', 'N']:
        print('ok')
    else:
        print('assuming no')
Beispiel #21
0
from pip.backwardcompat import raw_input

print('PygLatin Game')

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    print(original)
    word = original.lower()
    first = word[0]
    last = word[len(word) - 1]
    new_word = last + word[1:(len(word) - 1)] + first + pyg

    print(new_word)
else:
    print('empty')

print("Go away from here!")
Beispiel #22
0
from pip.backwardcompat import raw_input

__author__ = 'muli'

number = 23
guess = int(raw_input('Enter an integer : '))

if guess == number:
    print ('Congratulations, you guessed it.') # New block starts here
    print ("(but you do not win any prizes!)") # New block ends here
elif guess < number:
    print ('No, it is a little higher than that') # Another block
    # You can do whatever you want in a block ...
else:
    print ('No, it is a little lower than that')
    # you must have guess > number to reach here

print ('Done')
# This last statement is always executed, after the if statement is executed
Beispiel #23
0
conn = MySQLdb.connect(host = s_ip, user = s_name, passwd = s_passwd, db = s_db)

# 循环输入,至到输入正确
while True :
    try :
        cursor = conn.cursor()
        print("#" * 15 + " Mysql DB " + "#" * 15)
        cursor.execute("SHOW TABLES")

        # 显示现有的数据表名称
        for tn in cursor.fetchall() :
            # 格式化输出,首字母大写
            print("{0:-<39}".format(str(tn).split("'")[1]).capitalize() + "#")

        # 输入一个名称
        tabname = raw_input("Please input table name : ")
        sqlone = "SELECT DISTINCT t1 FROM " + tabname
        cursor.execute(sqlone)

        # 统计开始
        print("#" * 16 + " Result " + "#" * 16)
        for row in cursor.fetchall() :
            key = "SELECT COUNT(*) t1 FROM " + tabname + " WHERE t1="
            sql = key + "\"" + str(row).split("'")[1] + "\""
            cursor.execute(sql)
            for s in cursor.fetchall() :
                print("{0:-<37}{1:0}".format(str(row).split("'")[1], s[0]))
        print("#" * 17 + " End " + "#" * 17)
        break
    except :
        print("输入错误,请重新输入!")
Beispiel #24
0
from pip.backwardcompat import raw_input

__author__ = 'muli'

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    s = raw_input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
    # Other work can continue as usual here
except EOFError:
    print ('\nWhy did you do an EOF on me?')
except ShortInputException as x:
    print ('ShortInputException: The input was of length %d, \
          was expecting at least %d' % (x.length, x.atleast))
else:
    print ('No exception was raised.')

Beispiel #25
0
from pip.backwardcompat import raw_input
import urllib5
from json import load 

url = "http://api.npr.org/query?apiKey="
key = "API_KEY"
url = url + key
url += "&numResults=3"
url += "&format=json"
url += "&id="
npr_id = raw_input("Which NPR ID do you want to query?")
url += npr_id

response = urlopen(url)
json_obj = load(response)

for story in json_obj['list']['story']:
    print (story['title']['$text'])
Beispiel #26
0
__author__ = 'Fotty'
"""
Write a program that prompts a user for their name (first name and family name separately) and then welcomes them.
This time, the program should always welcome so that both the first name and the last name begin with a capital letter
and the rest of the letters are small, regardless of how the name was entered (only in small letters, in large or mixed).
Program should compute initials from entered full name and display them.
Also a program should find and print out the number of vowels (letters A, E, I, O, U)
in the name (in both, first and family, names).
 Enter first name: mAriNa
 Enter family name: lePp
 Hello Marina Lepp
 Your initials are M L
 The number of vowels in your name is 4

"""
first_name = str(raw_input("Enter you name: "))
last_name = str(raw_input("Enter your last name: "))
rearrange_words = first_name.lower().capitalize() + " " + last_name.lower(
).capitalize()
initials = first_name[0].upper() + last_name[0].upper()
vowels = "aeiouAEIUO"
summ = 0

for v in vowels:
    v = rearrange_words.count(v)
    summ += v
print(
    "Hello {0}\nYour initials are {1}\nThe number of vowels in your name is {2}"
    .format(rearrange_words, initials, str(summ)))
"""
Every University of Tartu user (student or member of staff), which has username for Study Information System,
    try:
        c = str(temp).strip()
        f = (str(float(temp) * 9/5 + 32))
        print("Celsius: %s Fahrenheit: %s" %(c, f))
        #Celsius: 32.0 Fahrenheit: 89.6

    except:
        print("Invalid input")



"""
Exercise 2. Numbered lines
Write a program which prompts the user for filename and outputs all lines from the file with the line number.
Make sure that program works nicely with all files which exist and do not exist (use try-except)."""



try:
    question = raw_input('Enter the name of the file to read: ')
    xxfile = open(question, 'r')
    var = 0
    for txt in xxfile:
        acc = txt.strip()
        var += 1
        print(str(var)+ "." + acc)

except:
        print("The file is empty or it might be missing :( ")

Beispiel #28
0
from pip.backwardcompat import raw_input

print("Vigenere Cipher")
#text input for text
text = input()
text = text.lower()
textArray = list(text)
#int input for key length
keyLength = int(raw_input())


#dot product
def dot(list1, list2):
    RL = []
    size = 0
    for i in range(0, len(list1)):
        RL.append(list1[i] * list2[i])
    for item in RL:
        size += item
    return size


#returns a shifted list, shifted by the shift value
def shift(list, shift):
    RL = []
    for i in range(shift, len(list)):
        RL.append(list[i])
    for i in range(0,shift):
        RL.append(list[i])
    return RL
__author__ = 'Sergii'
# Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail
# messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent
# the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number
# of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using
# a maximum loop to find the most prolific committer.
from pip.backwardcompat import raw_input

name = raw_input("Enter file:")
if len(name.strip()) < 1:
    name = 'mbox-short.txt'
fileHandler = open(name)
emailList = list()

for line in fileHandler:
        if not line.startswith("From") or line.startswith("From:"):
            continue
        words = line.split()
        emailList.append(words[1])
emailDict = dict()
for email in emailList:
    emailDict[email] = emailDict.get(email, 0) + 1

popularEmail = None
popularEmailCount = None

for email, count in emailDict.items():
    if popularEmailCount is None or count > popularEmailCount:
        popularEmail = email
        popularEmailCount = count
print(popularEmail, popularEmailCount)
Beispiel #30
0
from math import sqrt
from pip.backwardcompat import raw_input

__author__ = 'Tong'
a = float(raw_input("a: "))
b = float(raw_input("b: "))

print(a + b > 70)
print((a * a + b * b) > ((100 - a) * (100 - a) + (40 - b) * (40 - b)))
Beispiel #31
0
    return randint(0, len(board) - 1)


for x in range(0, 5):
    board.append([])
    for y in range(0, 5):
        board[x].append('O')
print_board(board)

ship_col = random_col(board)
ship_row = random_row(board)

for turn in range(4):
    print("Turn: ", (turn + 1))

    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

    if guess_row == ship_row and guess_col == ship_col:
        print("Congratulations! You sunk my battleship!")
    else:
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0
                                                or guess_col > 4):
            print("Oops, that's not even in the ocean.")
        elif board[guess_row][guess_col] == "X":
            print("You guessed that one already.")
        else:
            print("You missed my battleship!")
            board[guess_row][guess_col] = "X"
        # Print (turn + 1) here!
        print_board(board)
Beispiel #32
0
# By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million,
# find the sum of the even-valued terms.
from pip.backwardcompat import raw_input

fibonacci = [1, 2]


def make_fibonacci(max_fibo):
    for i in range(0, max_fibo, 1):
        new_fibo = fibonacci[i] + fibonacci[i + 1]
        if new_fibo <= max_fibo:
            fibonacci.append(new_fibo)
        else:
            print('Fibonacci maker ended at value %s.' % new_fibo)
            print (fibonacci)
            break


def sum_even_fibo():
    fibo_sum = 0
    for i in range(0, len(fibonacci)):
        if fibonacci[i] % 2 == 0:
            fibo_sum += fibonacci[i]
    print('Sum of even Fibonaccis in this sequence is %s.' % fibo_sum)


max_fibo = int(raw_input('Enter a value to end the Fibonacci sequence at:'))
make_fibonacci(max_fibo)
sum_even_fibo()
def decrypt():
    yol ="/home/oktay/d/a.txt.enc";
    dosya = yol;
    aes_modu = AES.MODE_CBC
    key =  "abcde12345f6g7h8"
    outname = dosya[:-4]

    with open(dosya, 'rb') as sifreli_dosya:
        karakter_sayisi = struct.unpack('<Q', sifreli_dosya.read(struct.calcsize('Q')))[0]
        baslangic_vektoru = sifreli_dosya.read(AES.block_size)
        decryptor = AES.new(key, aes_modu, baslangic_vektoru)

        with open(outname, 'wb') as yeni_dosya:
            while True:
                chunk = sifreli_dosya.read(64)
                if len(chunk) == 0:
                    break
                yeni_dosya.write(decryptor.decrypt(chunk))

            yeni_dosya.truncate(karakter_sayisi)

encOrDec = raw_input("şifreleme için 1, şifreyi kaldırmak için 2 : ")
if encOrDec == '1':
    encrypt()
elif encOrDec == '2':
    decrypt()
else:
    print ("Geçerli bir seçim değil")
    sys.exit(1)
Beispiel #34
0
from pip.backwardcompat import raw_input

__author__ = 'muli'
while True:
    s = raw_input("Enter somthing :")
    if s == "abc":
        break
    print("length of the string is", len(s))
print("Done")
    yol = "/home/oktay/d/a.txt.enc"
    dosya = yol
    aes_modu = AES.MODE_CBC
    key = "abcde12345f6g7h8"
    outname = dosya[:-4]

    with open(dosya, 'rb') as sifreli_dosya:
        karakter_sayisi = struct.unpack(
            '<Q', sifreli_dosya.read(struct.calcsize('Q')))[0]
        baslangic_vektoru = sifreli_dosya.read(AES.block_size)
        decryptor = AES.new(key, aes_modu, baslangic_vektoru)

        with open(outname, 'wb') as yeni_dosya:
            while True:
                chunk = sifreli_dosya.read(64)
                if len(chunk) == 0:
                    break
                yeni_dosya.write(decryptor.decrypt(chunk))

            yeni_dosya.truncate(karakter_sayisi)


encOrDec = raw_input("şifreleme için 1, şifreyi kaldırmak için 2 : ")
if encOrDec == '1':
    encrypt()
elif encOrDec == '2':
    decrypt()
else:
    print("Geçerli bir seçim değil")
    sys.exit(1)
        return True
    if check('char', 1, 4, 7):
        return True
    if check('char', 2, 5, 8):
        return True

    if check('char', 0, 4, 8):
        return True
    if check('char', 2, 4, 6):
        return True


count = 0
while count < 10:
    while True:
        input1 = raw_input("Enter the spot:")  # takes input
        input1 = int(input1)

        if board[input1] != 'X' and board[input1] != 'O':
            board[input1] = 'X'

            if checkall('X') == True:  # Winner check
                print("X wins. Here X means Player")
                break

            while True and count < 9:
                random.seed()  # Generating random number
                computer = random.randint(0, 8)

                if board[computer] != 'O' and board[computer] != 'X':
                    board[computer] = 'O'
def checkForMaxNumber(intNum, smallest):
    if smallest is None:
        smallest = intNum
    elif intNum < smallest:
        smallest = intNum


def printResults():
    # print "Maximum", largest
    print("Maximum is ", largest)
    print("Minimum is ", smallest)


while True:
    rawNum = raw_input("Enter a number: ")
    if rawNum == "done":
        break
    try:
        intNum = int(rawNum)
    except Exception:
        print("Invalid input")
        continue

    if largest is None:
        largest = intNum
    elif intNum > largest:
        largest = intNum

    if smallest is None:
        smallest = intNum
Beispiel #38
0
# 读取文件内容,一次读取出所有内容
print(file.read())

# 读取到最后会返回 ""
print(file.readline() == "")

file = open(path, "w")
file.truncate()
file.write("hello world")
file.flush()

file.close()


#复制文件
src=raw_input("src file:")
dest=raw_input("dest file:")
srcFile = open(src)
destFile=open(dest,"w")
destFile.write(srcFile.read())
destFile.flush()
srcFile.close()
destFile.close()
#复制文件2
src=raw_input("src file:")
dest=raw_input("dest file:")
srcFile=open(src,"r")
destFile=open(dest,"w")


Beispiel #39
0
from pip.backwardcompat import raw_input

print('PygLatin Game')

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    print(original)
    word = original.lower()
    first = word[0]
    last = word[len(word)-1]
    new_word = last + word[1:(len(word) - 1)] + first + pyg

    print(new_word)
else:
    print('empty')

print("Go away from here!")
Beispiel #40
0
        title = self.getPageTitle(pageNum)
        #根据title建立一个即将用于写入的文件
        self.newFileAccTitle(title)
        author = self.getPageAuthor(pageNum)
        #第三步:获取帖子各个楼层的内容
        contents = self.getContent(pageNum)
        #第四步:开始写入文件中
        try:
            self.writedata2File(contents)
        except:
            print("写入文件发生异常")
        finally:
            print("写入文件完成!")


#测试代码如下:
#url=raw_input("raw_input:")
url = "http://www.tieba.baidu.com/p/4197307435"
seeLZ = input("input see_lz:")
pageNum = input("input pageNum:")
floorTag = raw_input("input floorTag:")
baidutieba = BaiduTieBa(url, seeLZ, floorTag)  #实例化一个对象
baidutieba.start(pageNum)
#content=baidutieba.getPageContent(pageNum)#调用函数
#开始解析得到帖子标题
#baidutieba.getPageTitle(1)
#开始解析得到帖子的作者
#baidutieba.getPageAuthor(1)
#baidutieba.getPageTotalPageNum(1)
#解析帖子中的内容
#baidutieba.getContent(pageNum)
__author__ = 'Serg'
from pip.backwardcompat import raw_input

__author__ = 'Sergii'
hrs = raw_input("Enter Hours\n")
try:
    h = float(hrs)
except Exception:
    print("You shouda entered numbers!")
    quit()
rateInput = raw_input("Enter Rate\n")
try:
    rate = float(rateInput)
except Exception:
    print("You shouda entered numbers!")
    quit()
try:
    if h <= 40:
        print(h * rate)
    else:
        print(str(40 * rate + (h - 40) * rate * 1.5))
except Exception:
    print("We can not do mathematical operations to words!")
    quit()
__author__ = 'Serg'
from pip.backwardcompat import raw_input

inp = raw_input("Europe floor?\n")
usf = int(inp)+1
print("US floor:\n", usf)
"""
Write a program that prompts a user for their name (first name and family name separately) and then welcomes them.
This time, the program should always welcome so that both the first name and the last name begin with a capital letter
and the rest of the letters are small, regardless of how the name was entered (only in small letters, in large or mixed).
Program should compute initials from entered full name and display them.
Also a program should find and print out the number of vowels (letters A, E, I, O, U)
in the name (in both, first and family, names).
 Enter first name: mAriNa
 Enter family name: lePp
 Hello Marina Lepp
 Your initials are M L
 The number of vowels in your name is 4

"""
first_name = str(raw_input("Enter you name: "))
last_name = str(raw_input("Enter your last name: "))
rearrange_words = first_name.lower().capitalize() + " " + last_name.lower().capitalize()
initials = first_name[0].upper() + last_name[0].upper()
vowels = "aeiouAEIUO"
summ = 0

for v in vowels:
    v = rearrange_words.count(v)
    summ += v
print("Hello {0}\nYour initials are {1}\nThe number of vowels in your name is {2}".format(rearrange_words, initials,
                                                                                          str(summ)))

"""
Every University of Tartu user (student or member of staff), which has username for Study Information System,
has home directory and can create webpage using university server.
Beispiel #44
0
#coding=gbk
from os.path import os

from pip.backwardcompat import raw_input

straa = raw_input("Enter your input: ");
print ("Received input is : ", straa)

#input([prompt]) 函数和raw_input([prompt]) 函数基本可以互换,但是input会假设你的输入是一个有效的Python表达式,并返回运算结果。
strbb = input("Enter your input: ");
print ("Received input is : ", strbb)
#文件操作
pathfile = "D:" + os.sep + "workspace\\git\\PythonProject\\PythonProject\\src\\foo.txt"
fo = open(pathfile, "a+")
print ("Name of the file: ", fo.name);

'''Write()方法
Write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
Write()方法不在字符串的结尾不添加换行符('\n'):
'''
fo.write( "Python is a great language.\nYeah its great!!\n");

# 关闭打开的文件
fo.close()

fo = open(pathfile, "r+");

strRead = fo.read(30);
print (strRead)

strReada = fo.read();
from pip.backwardcompat import raw_input

__author__ = 'Sergii'
# 7.1 Write a program that prompts for a file name, then opens that file and reads through the file,
# and print the contents of the file in upper case.
# Use the file words.txt to produce the output below.
# You can download the sample data at http://www.pythonlearn.com/code/words.txt
fileName = raw_input("Enter file name: ").strip()
try:
    fileName = open(fileName)
except:
    print("File cannot be opened", fileName)
    exit()
for line in fileName:
    line = line.upper().rstrip()
    print(line)