Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

How to fetch values in quotes using python?

How to fetch values in quotes using python?


xml_strg = """<?xml version="1.0"?>
<xml_api_reply version="1">
    <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
        <forecast_information>
            <city data="Baton Rouge, LA"/>
            <postal_code data="baton rouge,la"/>
            <latitude_e6 data=""/>
            <longitude_e6 data=""/>
            <forecast_date data="2011-02-22"/>
            <current_date_time data="2011-02-22 20:06:59 +0000"/>
            <unit_system data="US"/>
        </forecast_information>
        <current_conditions>
            <condition data="Cloudy"/>
            <temp_f data="72"/>
            <temp_c data="22"/>
            <humidity data="Humidity: 73%"/>
            <icon data="/ig/images/weather/cloudy.gif"/>
            <wind_condition data="Wind: N at 5 mph"/>
        </current_conditions>
    </weather>
</xml_api_reply>
"""       

import xml.etree.cElementTree as et

root =  et.fromstring(xml_strg)
result = []
for elem in root.find('./weather/current_conditions'):
    if elem.tag in ('humidity', 'icon', 'wind_condition'):
        result.append(elem.get('data'))
print result

['Humidity: 73%', '/ig/images/weather/cloudy.gif', 'Wind: N at 5 mph']

'humidity data="Humidity: 73%" icon data="/ig/images/weather/cloudy.gif" wind_condition data="Wind: N at 5 mph"'

import re
re.findall('"(.+?)"', in_string)

#!/usr/bin/env python

from xml.etree.ElementTree import XML
import sys
data = """<?xml version="1.0"?>
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
    <forecast_information>
        <city data="Baton Rouge, LA"/>
        <postal_code data="baton rouge,la"/>
        <latitude_e6 data=""/>
        <longitude_e6 data=""/>
        <forecast_date data="2011-02-22"/>
        <current_date_time data="2011-02-22 20:06:59 +0000"/>
        <unit_system data="US"/>
    </forecast_information>
    <current_conditions>
        <condition data="Cloudy"/>
        <temp_f data="72"/>
        <temp_c data="22"/>
        <humidity data="Humidity: 73%"/>
        <icon data="/ig/images/weather/cloudy.gif"/>
    </current_conditions>
</weather>
</xml_api_reply>
"""

tree = XML(data)
conditions = tree.findall("weather/current_conditions")
results = []
for c in conditions:
    curr_results = {}
    for child in c.getchildren():
        curr_results[child.tag] = child.get('data')
    results.append(curr_results)

print results

<?xml version="1.0"?><xml_api_reply version="1"><weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" ><forecast_information><city data="Baton Rouge, LA"/><postal_code data="baton rouge,la"/><latitude_e6 data=""/><longitude_e6 data=""/><forecast_date data="2011-02-22"/><current_date_time data="2011-02-22 20:06:59 +0000"/><unit_system data="US"/></forecast_information><current_conditions><condition data="Cloudy"/><temp_f data="72"/><temp_c data="22"/><humidity data="Humidity: 73%"/><icon data="/ig/images/weather/cloudy.gif"/><wind_condition data="Wind: N at 5 mph"/>

import re

with open('joeljames.txt','rb') as f:
    RE = ('humidity data="([^"]*)"/>'
          '<icon data="([^"]*)"/>'
          '<wind_condition data="([^"]*)"/>')
    print re.search(RE,f.read()).groups()

import re
print re.search(('humidity data="([^"]*)"/>'
                 '<icon data="([^"]*)"/>'
                 '<wind_condition data="([^"]*)"/>'),
                open('joeljames.txt','rb').read()).groups()

('Humidity: 73%', '/ig/images/weather/cloudy.gif', 'Wind: N at 5 mph')

import re
print dict(re.findall('(humidity data|icon data|wind_condition data)'
                      '="([^"]*)"/>',open('joeljames.txt','rb').read()))

{'humidity data': 'Humidity: 73%', 'icon data': '/ig/images/weather/cloudy.gif', 'wind_condition data': 'Wind: N at 5 mph'}

>>> from lxml import etree
>>> filePath = 'c:/test.xml'
>>> root = etree.parse(filePath)
>>> keypairs = dict((r.tag, r.get('data')) for r in root.xpath('//*[@data]'))

>>> print keypairs
{'city': 'Baton Rouge, LA', 'forecast_date': '2011-02-22', 'latitude_e6': '', 'l
ongitude_e6': '', 'temp_c': '22', 'humidity': 'Humidity: 73%', 'postal_code': 'b
aton rouge,la', 'unit_system': 'US', 'temp_f': '72', 'current_date_time': '2011-
02-22 20:06:59 +0000', 'condition': 'Cloudy', 'icon': '/ig/images/weather/cloudy
.gif'}

>>> print keypairs['humidity']
Humidity: 73%

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.



'''
sum1=0
total=0
average=0
a=raw_input('Enter a number:')
while a!='done':
    try:
        a=float(a)
        sum1=sum1+a
        total=total+1
    except:
        print "Please insert a number"
    a=raw_input("Enter a number:")
print "Sum:",sum1
print "Total:",total
print "Average:",float(sum/total)

Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.

Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.




a=raw_input('Enter a number:')
min=a
max=a
while a!='done':
    try:
        a=float(a)
        if(float(a)>float(max)):
            max=a
        if(float(a)<float(min)):
            min=a
    except:
        print "Please insert a number"
    a=raw_input("Enter a number:")
print "Max:",max
print "Min:",min

How To Write a program in Python that asks user to input 5 lines of numbers. Your program should represent these lines as a table.

Write a program in Python that asks user to input 5 lines of numbers. Your program should represent these lines as a table.


#function that checks if n is float or not
def float_or_not(n):
    for char in n:
        if char == ".":
            return True

table = []

for i in range(5):
    numbers = input("Enter some numbers: ").split(" ")
    for x, y in enumerate(numbers):
        if float_or_not(y) == True:
            numbers[x] = float(y)
        else:
            numbers[x] = int(y)
    table.append(numbers)

print(table)

Write a function average() that takes no input but requests that the user enters a sentence, i.e. a string. Your function should return the average length of a word in the sentence.

Write a function average() that takes no input but requests that the user enters a sentence, i.e. a string. Your function should return the average length of a word in the sentence.


Usage:
>>> average()
Enter a sentence: Most modern calendars mar the sweet
simplicity of our lives by reminding us that each day
that passes is the anniversary of some perfectly
uninteresting event
5.115384615384615

So far I have this:

def average():
    wordCount = input('Enter a sentence: ')
    sum = 0
    if wordCount != 0:
        average = sum / wordCount
    else:
        average = 0
    return(average)

How to write a static python getitem method?

How to write a static python getitem method?



class A:
    @staticmethod
    def __getitem__(val):
        return "It works"

print A[0]

class MetaA(type):
    def __getitem__(cls,val):
        return "It works"

class A(object):
    __metaclass__=MetaA
    pass

print(A[0])
# It works

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.



'''
f1=open('words.txt')
d1=dict()
i=0
for line in f1:
    words=line.split()
    for i in range(len(words)):
        d1[words[i]]=i
print d1
print 'abc' in d1

Write a recursive Python function, given a non-negative integer N, to count and return the number of occurrences of the digit 7 in N.

Write a recursive Python function, given a non-negative integer N, to count and return the number of occurrences of the digit 7 in N.



For example:
count7(717) -> 2
count7(1237123) -> 1
count7(8989) -> 0


--------

def count7(N):
    Holder = N
    LastDigit = Holder % 10 #get the last digit using mod
    #if the last digit is 7 then add a tally and use the function again
    if LastDigit == 7:
        return (1 + count7(int(Holder/10))
    else:
        return (0 + count7(int(Holder/10))
   

count7(717)

Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value.

Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. 

(Note: there is a builtin function named max but pretend you cannot use it.)


RUNSAVELOADSHOW CODELENS
"""
.comimport random

alist=[]
def listRandomFill(list):
    for i in range(100):
        list.append(random.randrange(0,1001))
    return(list)

def max(list):
    max=0
    for el in list:
        if max<el:
            max=el
    return max
print(max(listRandomFill(alist)))

Write a Python function named interleaveChars that is given two lines read from a text file, and returns a single string containing the characters of each string interleaved.

Write a Python function named interleaveChars that is given two lines read from a text file, and returns a single string containing the characters of each string interleaved.


def interleaveChars(name1, name2):

    ''' Returns a single string containing the characters of name1 and name2
        interleaved '''
       
    string = ''

    if len(name1) > len(name2):
        shortest = name2
        longest = name1
    else:
        shortest = name1
        longest = name2

    for i in range(len(shortest)):
        string = string + name1[i] + name2[i]
    string = string + longest[len(shortest):]
   
    return string

# main

input_file = open('P5_text.txt', 'r')

name1 = input_file.readline()[:-1]

while name1 != '':
    name2 = input_file.readline()[:-1]
    print(interleaveChars(name1, name2))
    name1 = input_file.readline()[:-1]

Write a Python class to find the three elements that sum to zero from a set of n real numbers.

Write a Python class to find the three elements that sum to zero from a set of n real numbers. 


Input array : [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
"""


class Calculator(object):
    def do_work(self, my_array):
        pass

   
my_calc = Calculator()
my_calc.do_work([-25, -10, -7, -3, 2, 4, 8, 10])

assert(my_calc.do_work([-25, -10, -7, -3, 2, 4, 8, 10]) == [[-10, 2, 8], [-7, -3, 10]])
assert(my_calc.do_work([]) == [])

Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because

Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because


1 ∗ 10^3 + 2 ∗ 10^2 + 3 ∗ 10^1 + 4 ∗ 10^0.
"""

def general_poly(L):
    """
    L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0
    """
    def helper(x):
        add = 0
        k = max(range(len(L)))#len(L)-1
        for i in L:#range(len(L)):
            add += i*x**k
            k -= 1
        return add
    return helper

Write a Python function that takes in two lists and calculates whether they are permutations of each other. The lists can contain both integers and strings.

Write a Python function that takes in two lists and calculates whether they are permutations of each other. The lists can contain both integers and strings. We define a permutation as follows:


the lists have the same number of elements
list elements appear the same number of times in both lists
If the lists are not permutations of each other, the function returns False.
If they are permutations of each other, the function returns a tuple consisting
of the following elements:

the element occuring the most times
how many times that element occurs
the type of the element that occurs the most times
If both lists are empty return the tuple (None, None, None). If more than one
element occurs the most number of times, you can return any of them.
"""


def is_list_permutation(L1, L2):
    '''
    L1 and L2: lists containing integers and strings
    Returns False if L1 and L2 are not permutations of each other.
            If they are permutations of each other, returns a
            tuple of 3 items in this order:
            the element occurring most, how many times it occurs, and its type
    '''
    if helper_permutation(L1,L2) == False:
        return False
    elif not L1:
        return (None, None, None)
    else:
        most = max(set(L1), key=L1.count) 
        num = L1.count(most)
        typ = type(most)
        return (most, num, typ)
   
def helper_permutation(L1,L2):
    if len(L1) != len(L2): # UNEQUAL LENGTH MEANS PERMUTATIONS OF EACH OTHER IS NOT POSSIBLE
        return False; 
    for i in range(0, len(L1)):
        if L1.count(L1[i]) != L2.count(L1[i]):
            return False

Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.

Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.


For example, if s = "This is great!" then print_without_vowels will print
Ths s grt!. If s = "a" then print_without_vowels will print the empty string .
"""

def print_without_vowels(s):
    '''
    s: the string to convert
    Finds a version of s without vowels and whose characters appear in the
    same order they appear in s. Prints this version of s.
    Does not return anything
    '''
    vowels = "aeiou"
    s1 = ""
    for i in s:
        if i not in vowels and i not in vowels.upper():
            s1 += i
    print(s1)
    return None

Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d.

Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d.


Here are two examples:

If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]}
If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]}
If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]}
"""

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}
    for i in d:
        if d[i] not in result:
            result[d[i]] = []
        result[d[i]].append(i)
    return result

# GOT 18 OUT OF 20
"""
Test: dict_invert({8: 6, 2: 6, 4: 6, 6: 6})
Your output:
{6: [8, 2, 4, 6]}
Correct output:
{6: [2, 4, 6, 8]}
"""

Write a python script that takes input.txt as input, parses it, and produces output.txt as output.

Write a python script that takes input.txt as input, parses it, and produces output.txt as output.


The script should be a general script that works on any file supplied with the format of input.txt.

The script should be run like this:

cat input.txt | python script.py > output.txt

[-- input.txt is below --]

* This is an outline

. It's not a very good outline

.. I've seen better

.. I've seen worse

... I saw a really bad one back in 2008

* This is the second numbered item in the outline

. This is sub text that spans multiple lines

This should be included with the previous line

And this line too

.. That is more sub text

* Numbers

. Some text

** Lots

. Some more text

. And some more

*** And lots

. One

.. Two

... Three

**** Of numbers

. Another line

** Less Numbers

. Text

*** More Numbers

. Blah

* One number again

. The last line

[-- output.txt is below this line --]

1 This is an outline
  + It's not a very good outline
   - I've seen better
   + I've seen worse
    - I saw a really bad one back in 2008
2 This is the second numbered item in the outline
  + This is sub text that spans multiple lines
    This should be included with the previous line
    And this line too
   - That is more sub text
3 Numbers
  - Some text
3.1 Lots
  - Some more text
  - And some more
3.1.1 And lots
  + One
   + Two
    - Three
3.1.1.1 Of numbers
  - Another line
3.2 Less Numbers
  - Text
3.2.1 More Numbers
  - Blah
4 One number again
  - The last line

Write a Python program that implements the ‘Shiritori" (first letter. last letter) game.

Write a Python program that implements the ‘Shiritori" (first letter. last letter) game. In this game, a person starts with a word. and the next person has to come up with a word that starts with the last letter of the previous word. (e.g.. If the first person starts with "apple", the next person has to come up with a word that starts with the letter ‘e'.)

Rules of the game:
1. Word must be a valid word.
2. Word must not have been used before.
3. Word must begin with the last letter of the previous word.

The Python program should take in an input word and check whether it exists in the database of words. If the word does not violate any rule of the game. it is deemed valid and the game continues. Else. the game ends.

The database of words would be the provided "word_list.txt" file. The program should open the "word_list.txt" file for reading, then read and store the contents of the file into a suitable Python data type.

The following illustrates what the game sessions might look like:

Please type a word: apple

Please type a word: egg

Please type a word: ear

You didn't type a word starting with '9'.
>>>

Please type a word: sun

Please type a word: new

Please type a word: won

Please type a word: new

You typed a word that has been typed before.
>>>

Please type a word: pear

Please type a word: rar

You didn't type a word found in word_list.txt.
>>>

Please make your code as clear and readable as possible. Comments to explain the workings of your code would be very much appreciated.

Write a Python program that encrypts or decrypts a given text into/from a secret language?

Write a Python program that encrypts or decrypts a given text into/from  a secret language?


Individual words in the text are encrypted according to the following rules:

If the word starts with a vowel append 'tan' to the word.  The vowels are a, e, i, o, u.
Otherwise, take the first letter of the word, move it to the end and then append 'est'.
So:

apple becomes appletan
orange becomes  orangetan
banana becomes ananabest
python becomes ythonpest
For simplicity we'll assume that the input text is in lowercase and that it does not contain any punctuation (no commas, periods, etc...)

Your program will first ask the user to make a choice between encryption into the secret language (E) or decryption from the secret language (D).

When the user specifies 'E' for encryption, the program will translate each word in the input text into the secret language, will put the translated words in reverse order into one translated message and will print out the translated message.  The translated message will have exactly one space character between words.

When the user specifies 'D' for decryption', the program will attempt to recover  the original words from the input text.  This is only possible if the words have a specific format:  they start with a vowel and end with tan or they end with a consonant followed by est.  If one or more word does not have this format, the decryption fails and the message 'Invalid Message' is printed.

Testing:
Make sure that you test your solution before you submit it.   Here are a few test cases with the expected output.  Feel free to add your own.

Test case 1 - encryption is correct for words starting with a vowel
Please type E to encrypt or D to decrypt a message: E
Please enter your message: apple
The secret message is: appletan

Test case 2 -  encryption is correct for words starting with a consonant (non vowel)
Please type E to encrypt or D to decrypt a message: E
Please enter your message: banana
The secret message is:  ananabest

Test case 3 - encryption is correct for phrases with multiple words
Please enter your message: python is fun
The secret message is: unfest istan ythonpest

Test case 4 - encryption is correct when words are separated by more than one space character
Please enter your message: simple     is better than complex
The secret message is: omplexcest hantest etterbest istan implesest

Test case 5 - decryption is correct for words ending with 'tan'
Please type E to encrypt or D to decrypt a message: D
Please enter your message: orangetan
The secret message is: orange

Test case 6 -  decryption is correct for words ending with a consonant followed with 'est'
Please type E to encrypt or D to decrypt a message: D
Please enter your message: ryptographycest
The secret message is: cryptography

Test case 7 - decryption is correct for phrases with multiple words
Please type E to encrypt or D to decrypt a message: D
Please enter your message: omplexcest hantest etterbest istan implesest
The secret message is: simple is better than complex

Test case 8 - The user is repeatedly prompted for input until they enter a valid choice (E or D)
Please type E to encrypt or D to decrypt a message: K
Invalid choice
Please type E to encrypt or D to decrypt a message: x
Invalid choice
Please type E to encrypt or D to decrypt a message: e
Invalid choice
Please type E to encrypt or D to decrypt a message: E
Please enter your message: hello
The secret message is: ellohest

Test case 9 - An invalid message is not decrypted
Please type E to encrypt or D to decrypt a message: D
Please enter your message: this is fun
Invalid Message

Write a Python program that prints the SHA256 hash of "Hello World" in hexadecimal.

Write a Python program that prints the SHA256 hash of "Hello World" in hexadecimal.


import hashlib
import codecs

def sha256(s):
    encoded = s.encode()
    hash_object = hashlib.sha256(encoded)
    print(hash_object.digest())
    return(hash_object.digest())

encoded_digest = sha256("Hello World")
print("Hexadecimal of SHA256 hashed message:", codecs.encode(encoded_digest, 'hex'))

# ```
# 21:14:28 › python3 hello_world.py
# b'\xa5\x91\xa6\xd4\x0b\xf4 @J\x01\x173\xcf\xb7\xb1\x90\xd6,e\xbf\x0b\xcd\xa3+W\xb2w\xd9\xad\x9f\x14n'
# Hexadecimal of SHA256 hashed message: b'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
# ```

Write a Python function that returns a list of keys in a Dict that map to integer values that are unique?

Write a Python function that returns a list of keys in a Dict that map to integer values that are unique (i.e. values appear exactly once in a Dict). The list of keys you return should be sorted in increasing order.
(If aDict does not contain any unique values, you should return an empty list.)

We are returning the key - not the value. We need to determine whether the key
relates to a value which is unique.

This function takes in a dictionary and returns a list.
"""
def uniqueValues(aDict):
    '''
    aDict: a dictionary
    '''
    sortList=[]
    outList=[]
    # Place values into a list
    #If there is only one of the values, then add to list. Otherwise, don't
    sortList = list(aDict.values())
    #need a loop to remove all instances of a duplicate
    #the length of the list will go down every time I remove an element
    #for i in range(len(sortList)):
    #    while sortList[i] in sortList[i+1:len(sortList)]:
    #        sortList.remove(sortList[i])
    #for i in range(len(sortList)):
    for i in sortList:
        if sortList.count(i) > 1: #if the item i appears in the list  > 1
            while i in sortList: #while that item is in the list
                sortList.remove(i) #remove that item!
   
    for k, v in aDict.items():
        if v in sortList:
            outList.append(k)
           
    outList.sort()
    return outList
   
testDict = {8: 3, 1: 3, 2: 2}
print(str(uniqueValues(testDict)))