Hey there! Sign in to join this conversationNew here? Join for free
x Turn on thread page Beta

Comp Sci -python watch

Announcements
    Offline

    20
    ReputationRep:
    (Original post by bigmansouf)
    i put a different answer my mistake
    Are you answering the same question? Yours seems to be finding the longest word in a string.
    • Thread Starter
    Offline

    20
    ReputationRep:
    (Original post by morgan8002)
    Are you answering the same question? Yours seems to be finding the longest word in a string.
    I did i mistake i puloaded the wrong question
    however in the case of the question that you did i panicked and didnt read the question probably. I thought it was asking me to find an anagram of any word. you did a great job
    thank you
    Offline

    20
    ReputationRep:
    (Original post by bigmansouf)
    I did i mistake i puloaded the wrong question
    however in the case of the question that you did i panicked and didnt read the question probably. I thought it was asking me to find an anagram of any word. you did a great job
    thank you
    Ah ok.

    This does the same as your answer:
    Code:
    def find(s):
        d = {len(word): word for word in s.lower().split()}
        return d[max(d.keys())]
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q:
    Write a function that accepts a string which contains a particular date from the Gregorian calendar. Your function should return what day of the week it was. Here are a few examples of what the input string(Month Day Year) will look like. However, you should not 'hardcode' your program to work only for these input!

    "June 12 2012"
    "September 3 1955"
    "August 4 1843"
    Note that each item (Month Day Year) is separated by one space. For example if the input string is:
    "May 5 1992"
    Then your function should return the day of the week (string) such as:
    "Tuesday"
    Algorithm with sample example:
    # Assume that input was "May 5 1992"
    day (d) = 5 # It is the 5th day
    month (m) = 3 # (*** Count starts at March i.e March = 1, April = 2, ... January = 11, February = 12)
    century (c) = 19 # the first two characters of the century
    year (y) = 92 # Year is 1992 (*** if month is January or february decrease one year)
    # Formula and calculation
    day of the week (w) = (d + floor(2.6m - 0.2) - 2c + y + floor(y/4) + floor(c/4)) modulo 7
    after calculation we get, (w) = 2
    Count for the day of the week starts at Sunday, i.e Sunday = 0, Monday = 1, Tuesday = 2, ... Saturday = 6
    Since we got 2, May 5 1992 was a Tuesday


    A:
    Spoiler:
    Show
    Code:
    from math import floor
    def dayOftheWeek(str1):
        dict1 = {'january': 11, 'february': 12, 'march': 1, 'april': 2, 
                'may': 3, 'june': 4, 'july': 5, 'august': 6, 'september': 7,
                'october': 8, 'november': 9, 'december': 10}
        lst = str1.lower(). split()
        month = dict1.get(lst[0].lower())
        day = int(lst[1])
        full_year = int(lst[-1])
        temp_year = str(full_year)
        century = int(temp_year[:2])
        if month == 11 or month == 12: 
            year = int(temp_year[2:]) - 1
        else: 
            year = int(temp_year[2:])
        calculation = (day + (floor((2.6 * month) - 0.2) - (2 * century) + year + floor(year/4) + floor(century/4))) % 77
        dict2  = { 1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday',
                   5: 'friday', 6: 'saturday', 7: 'sunday'}
        answer = dict2.get(calculation)
        return answer
    
    dayOftheWeek("May 5 1992")
    Offline

    1
    ReputationRep:
    (Original post by bigmansouf)
    Q: Write a function named find_longest_word that receives a string as parameter and returns the longest word in the string. Assume that the input to this function is a string of words consisting of alphabetic characters that are separated by space(s). In case of a tie between some words return the last one that occurs.
    Code:
    find_longest_word = lambda s: sorted(s.split(' '), key=len)[-1]
    (Original post by bigmansouf)
    Q Write a function named test_for_anagrams that receives two strings as parameters, both of which consist of alphabetic characters and returns True if the two strings are anagrams, False otherwise. Two strings are anagrams if one string can be constructed by rearranging the characters in the other string using all the characters in the original string exactly once. For example, the strings "Orchestra" and "Carthorse" are anagrams because each one can be constructed by rearranging the characters in the other one using all the characters in one of them exactly once. Note that capitalization does not matter here i.e. a lower case character can be considered the same as an upper case character
    Code:
    def test_for_anagrams(first_word, second_word):
        return sorted(first_word) == sorted(second_word)
    (Original post by bigmansouf)
    Q
    Write a function that accepts a string which contains a particular date from the Gregorian calendar. Your function should return what day of the week it was. Here are a few examples of what the input string(Month Day Year) will look like. However, you should not 'hardcode' your program to work only for these input!
    Code:
    def get_weekday(date_string):
        return datetime.datetime.strptime(date_string, "%B %d %Y").strftime("%A")
    • Thread Starter
    Offline

    20
    ReputationRep:
    (Original post by fat_hampster)

    Code:
    def get_weekday(date_string):
        return datetime.datetime.strptime(date_string, "%B %d %Y").strftime("%A")
    awesome
    never thought this is possible in short style of coding
    thanks
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Write a function that takes a 4 digit integer (from 1000 to 9999 both inclusive) as input argument and returns the integer using words as shown below:

    Sample Examples:
    if the input integer is 7000 then the function should return the string "seven thousand"
    if the input integer is 1008 then the function should return the string "one thousand eight"
    if the input integer is 4010 then the function should return the string "four thousand ten"
    if the input integer is 1012 then the function should return the string "one thousand twelve"
    if the input integer is 4506 then the function should return the string "four thousand five hundred six"
    if the input integer is 9900 then the function should return the string "nine thousand nine hundred"
    if the input integer is 8880 then the function should return the string "eight thousand eight hundred eighty"
    if the input integer is 5432 then the function should return the string "five thousand four hundred thirty two"
    Notice that the words in the output strings should all be lower cased and separated by only one space and make sure your words match the following spellings:
    one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen,
    sixteen, seventeen, eighteen, nineteen, twenty, thirty, forty, fifty, sixty, seventy, eighty,
    ninety, hundred, thousand


    A:
    Spoiler:
    Show
    Code:
    # Type your code here
    def numTowords(int1):
        dict1 = { 1: 'one', 2: 'two', 3: 'three', 4: 'four',
                   5: 'five', 6: 'six', 7: 'seven', 8: 'eight',
                   9: 'nine', 10: 'ten', 11:'eleven', 12: 'twelve',
                   13: 'thirteen', 14: 'fourteen', 15: 'fifteen',
                   16 :'sixteen', 17: 'seventeen', 18: 'eighteen', 
                   19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty',
                   50: 'fifty', 60: 'sixty', 70:'seventy', 80: 'eighty',
                   90: 'ninety', 100: 'hundred', 1000: 'thousand'}
        str1 = str(int1)
        lst = []
        word = " "
        for i in str1:
            lst.append(i)
        for j in str1:
            if j == "0":
                lst.remove(j)
                continue
                
            elif len(lst) == 4:
                word +=  dict1.get(int(lst[0]))+ " " + dict1.get(1000) + " "
                lst.remove(j)
                    
            elif len(lst) == 3:
                word += dict1.get(int(lst[0]))+ " " + dict1.get(100)+ " "
                lst.remove(j)    
                
            elif len(lst) == 2:
                str2 = "".join(lst)
                int2 = int(str2)
                none_or_sum = dict1.get(int2)
                if none_or_sum == None:
                    temp = ['0']
                    temp.insert(0, j)
                    str3 = "".join(temp)
                    int3 = int(str3)
                    word += dict1.get(int3)+ " "
                    lst.remove(j)                
                    
                else:
                    word += none_or_sum+ " "
                    del lst[:]
                    break
            
            elif len(lst) == 1:
                a = int(j)
                word += dict1.get(a)
        word = word.strip()        
        return word
    Offline

    21
    ReputationRep:
    Loving this thread. Will be very useful over summer as I learn python and C++
    • Thread Starter
    Offline

    20
    ReputationRep:
    (Original post by TheBBQ)
    Loving this thread. Will be very useful over summer as I learn python and C++
    thanks
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q:
    Write a function named construct_dictionary_from_lists that accepts 3 one dimensional lists and constructs and returns a dictionary as specified below.
    The first one dimensional list will have n strings which will be the names of some people.
    The second one dimensional list will have n integers which will be the ages that correspond to those people.
    The third one dimensional list will have n integers which will be the scores that correspond to those people.
    Note that if a person has a score of 60 or higher (score >= 60) that means the person passed, if not the person failed.
    Your function should return a dictionary where each key is the name of a person and the value corresponding to that key should be a list containing age, score, 'pass' or 'fail' in the same order as shown in the sample output.
    For example, if the function receives the following lists:

    (["paul", "saul", "steve", "chimpy"], [28, 59, 22, 5], [59, 85, 55, 60])
    then your function should return the dictionary such as:
    {'steve': [22, 55, 'fail'], 'saul': [59, 85, 'pass'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass']}

    A:

    Code:
    Spoiler:
    Show
    def sorted_lists_of_ages_scores(ages_list, scores_list): for i in ages_list: new_list = [] new_list.append(i) for j in scores_list: new_list.append(j) lst = ['fail', 'pass'] if j >= 60: new_list.append(lst[-1]) else: new_list.append(lst[0]) scores_list.pop(scores_list.index(j)) break ages_list.pop(ages_list.index(i)) break return new_list def construct_dictionary_from_lists(names_list, ages_list, scores_list): dictionary_from_lists = dict() #lists_of_values =[] for i in names_list: dictionary_from_lists[i] = sorted_lists_of_ages_scores(ages_list, scores_list) print (dictionary_from_lists) sorted(dictionary_from_lists.items(), reverse = True) return dictionary_from_lists construct_dictionary_from_lists(["paul", "saul", "steve", "chimpy"], [28, 59, 22, 5], [59, 85, 55, 60])
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Write a function named one_to_2D which receives an input list and two integers r and c as parameters and returns a new two-dimensional list having r rows and c columns.

    Note that if the number of elements in the input list is larger than r*c then ignore the extra elements. If the number of elements in the input list is less than r*c then fill the two dimensional list with the keyword None. For example if your fuction is called as hown below:

    one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3)
    Then it should return:
    [[8, 2, 9],[4, 1, 6]]

    A:
    Spoiler:
    Show
    Code:
    def one_to_2D(some_list, r, c):
        row = r
        column = c 
        product = r * c
        if len(some_list) =< product:
            for k in range(len(some_list), product):
                some_list.append(None)
                
        list_2d = []
        num  = 0
        for i in range(row):
            new_list = []
            for j in range(column):
                new_list.append(some_list[num])
                num += 1
            list_2d.append(new_list)
        return list_2d
        
    one_to_2D([8, 2, 9, 4, 1, 6, 7, 8, 7, 10], 2, 3)
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Write a function named multiplication_table that receives a positive integer 'n' as parameter and returns a n by n multiplication table as a two-dimensional list.

    For example if the integer received by the function 'n' is:

    4
    then your program should return a two_dimensional list with 4 rows and 4 columns such as:

    [[1, 2, 3, 4],
    [2, 4, 6, 8],
    [3, 6, 9, 12],
    [4, 8, 12, 16]]


    A:
    Spoiler:
    Show
    Code:
    def multiplication_table(n):
        list_2d =[]
        for i in range(1, n+1):
            list1= []
            for j in range(1, n+1):
                list1.append(j * i)
            list_2d.append(list1)
        return list_2d
    Offline

    3
    ReputationRep:
    (Original post by bigmansouf)
    Q:
    Write a function named construct_dictionary_from_lists that accepts 3 one dimensional lists and constructs and returns a dictionary as specified below.
    Can't think of a way to sort it how you specified in a one liner, but then I ran your code and this is the output:
    {'steve': [22, 55, 'fail'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass'], 'saul': [59, 85, 'pass']}
    Code:
    def construct_dictionary_from_lists(names, ages, scores):
        return {name: [ages[i], scores[i], 'pass' if scores[i] >= 60 else 'fail'] for i, name in enumerate(names)}
    Returns:
    {'steve': [22, 55, 'fail'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass'], 'saul': [59, 85, 'pass']}
    .
    Offline

    20
    ReputationRep:
    (Original post by bigmansouf)
    Q: Write a function that takes a 4 digit integer (from 1000 to 9999 both inclusive) as input argument and returns the integer using words as shown below:
    Code:
    def integer_to_string(n):
        n, units, tens, non_standard = [int(x) for x in str(n)], ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"], ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"], ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
        return units[n[0]] + " thousand " + units[n[1]] + " hundred " * (n[1] != 0) + (non_standard[n[3] - 1] if 10 * n[2] + n[3] in [11, 12, 13, 14, 15, 16, 17, 18, 19] else tens[n[2]] + " " * (n[2] != 0) + units[n[3]])
    (Original post by bigmansouf)
    Q:
    Write a function named construct_dictionary_from_lists that accepts 3 one dimensional lists and constructs and returns a dictionary as specified below.
    Code:
    def construct_dictionary(a, b, c):
        return {a[n]: [b[n], c[n], ["fail", "pass"][int(c[n] >= 60)]] for n in range(len(a))}
    (Original post by bigmansouf)
    Q: Write a function named one_to_2D which receives an input list and two integers r and c as parameters and returns a new two-dimensional list having r rows and c columns.
    Code:
    def one_to_2D(a, r, c):
        return [a[n * c: (n + 1) * c] for n in range(r)]
    Offline

    20
    ReputationRep:
    (Original post by bigmansouf)
    Q: Write a function named multiplication_table that receives a positive integer 'n' as parameter and returns a n by n multiplication table as a two-dimensional list.
    Code:
    def multiplication_table(n):
        return [[i * j for i in range(1, n + 1)]for j in range(1, n + 1)]
    • Thread Starter
    Offline

    20
    ReputationRep:
    (Original post by Push_More_Button)
    Can't think of a way to sort it how you specified in a one liner, but then I ran your code and this is the output:
    {'steve': [22, 55, 'fail'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass'], 'saul': [59, 85, 'pass']}
    Code:
    def construct_dictionary_from_lists(names, ages, scores):
        return {name: [ages[i], scores[i], 'pass' if scores[i] >= 60 else 'fail'] for i, name in enumerate(names)}
    Returns:
    {'steve': [22, 55, 'fail'], 'paul': [28, 59, 'fail'], 'chimpy': [5, 60, 'pass'], 'saul': [59, 85, 'pass']}
    .
    thanks i cheated a bit by looking at stackover flow


    im not good at one liner
    • Thread Starter
    Offline

    20
    ReputationRep:
    (Original post by morgan8002)
    Code:
    def multiplication_table(n):
        return [[i * j for i in range(1, n + 1)]for j in range(1, n + 1)]
    great
    im going to find a question u cant one-line
    • Thread Starter
    Offline

    20
    ReputationRep:
    Q: Write a function that accepts a filename as input argument and reads the file and saves each line of the file as an element in a list (without the new line ("\n")character) and returns the list. Each line of the file has comma separated values: For example if the content of the file looks like this:

    Lucas,Turing,22
    Alan,Williams,27
    Layla,Trinh,21
    Brayden,Huang,22
    Oliver,Greek,20
    then your function should return a list such as
    ['Lucas,Turing,22', 'Alan,Williams,27', 'Layla,Trinh,21', 'Brayden,Huang,22', 'Oliver,Greek,20']

    A:
    Spoiler:
    Show
    Code:
    # Type your code here
    def list_from_file(file_name):
        # Make a connection to the file
        file_pointer = open(file_name, 'r')
        # You can use either .read() or .readline() or .readlines()
        data = file_pointer.readlines()
        # NOW CONTINUE YOUR CODE FROM HERE!!!
        list_of_lines = []
        for line in data: 
            list_of_lines.append(alpha_string(line))
        return list_of_lines
    def alpha_string(n):
        alpha_num = "abcdefghijklmnopqrstuvwxyz,1234567890"
        new_line = ""
        for i in n.lower():
            if i in alpha_num:
                new_line += i 
        return new_line.title()



    i got the right answer but the auto-corrector says no i think it is right
    Offline

    20
    ReputationRep:
    (Original post by bigmansouf)
    Q: Write a function that accepts a filename as input argument and reads the file and saves each line of the file as an element in a list (without the new line ("\n"character) and returns the list. Each line of the file has comma separated values:
    Code:
    def open_file(file_name):
        return open(file_name).readlines()
    • Thread Starter
    Offline

    20
    ReputationRep:
    (Original post by morgan8002)
    Code:
    def open_file(file_name):
        return open(file_name).readlines()

    you forgot to remove the \n newline at the end
    Code:
    def list_from_file(file_name):
        # Make a connection to the file
        file_pointer = open(file_name, 'r')
        # You can use either .read() or .readline() or .readlines()
        data = file_pointer.readlines()
        # NOW CONTINUE YOUR CODE FROM HERE!!!
        list_of_lines = []
        for line in data: 
            list_of_lines.append(line.strip())
        return list_of_lines
 
 
 
Reply
Submit reply
Turn on thread page Beta
Updated: May 29, 2016
Poll
Do I go to The Streets tomorrow night?

The Student Room, Get Revising and Marked by Teachers are trading names of The Student Room Group Ltd.

Register Number: 04666380 (England and Wales), VAT No. 806 8067 22 Registered Office: International House, Queens Road, Brighton, BN1 3XE

Write a reply...
Reply
Hide
Reputation gems: You get these gems as you gain rep from other members for making good contributions and giving helpful advice.