blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
78a6692323c23224843718e96be5991a39cca86d
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/TinaB/lessonTwo_TB/FizzBuzz.py
1,153
4.3125
4
# Goal: # Write a program that prints the numbers from 1 to 100 inclusive. # But for multiples of three print “Fizz” instead of the number. # For the multiples of five print “Buzz” instead of the number. # For numbers which are multiples of both three and five print “FizzBuzz” instead. # Fizzbuzz to 100 def fizzbuzz(): counter = 1 while counter <= 100: if counter % 3 == 0 and counter % 5 == 0: print("FizzBuzz") counter += 1 elif counter % 3 == 0: print("Fizz") counter += 1 elif counter % 5 == 0: print("Buzz") counter += 1 else: print(counter) counter += 1 # Fizzbuzz dynamic number def fizzbuzz_with_entry(number): counter = 1 while counter <= number: if counter % 3 == 0 and counter % 5 == 0: print("FizzBuzz") counter += 1 elif counter % 3 == 0: print("Fizz") counter += 1 elif counter % 5 == 0: print("Buzz") counter += 1 else: print(counter) counter += 1
true
04c2d0a0d8be7b9ad2db4ae0ee4b001c1e6b5ecc
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Sean_Tasaki/Lesson3/strformat_lab.py
1,638
4.5
4
""" Sean Tasaki 5/10/2018 Lesson03.strformat_lab """ def task_one(): tuple1 = (2, 123.4567, 10000, 12345.67) results = 'file_{:0>4d} : {:3.2f} , {:.2e} , {:03.2e}'.format(*tuple1) print("Task One results:") print(results) def task_two(): results = ('file_0002', 123.46, 1.00e+04, 1.23e+04) print("Task Two results:") print(f'{results[0]:s} : {results[1]:.2f}, {results[2]:.2e}\, {results[3]:.2e}') def task_three(tuple): list = [] for i in tuple: list.append(i) l = len(list) print("Task Three results:") print(("The {} numbers are: " + ",".join(["{}"] * l)).format(l, * list)) def task_four(): n = (4, 30, 2017, 2, 27) print("{3:02d} {4} {2} {0:02d} {1}".format(*n)) def task_five(): print("__________Task Five__________") list1 = ['oranges', 1.3, 'lemons', 1.1] # Write an f-string that will display: # The weight of an orange is 1.3 and the weight of a lemon is 1.1 print(f'The weight of an {list1[0] [:-1]} is {list1[1]} and the weight\ of a {list1[2] [:-1]} is {list1[3]}') print() # displays the names of the fruit in upper case, and the weight 20% higher print(f'The weight of an {list1[0] [:-1].upper()} is {list1[1]*1.2} and the\ weight of a {list1[2] [:-1].upper()} is {list1[3]*1.2}') def task_six(): print("__________Task Six__________") list_names = ['Brandon', 'Jared', 'Matt', 'John'] list_ages = [10, 33, 99, 100] list_costs = [450.0000, 200000.00, 14.65, 100000.00] for i in range(len(list_names)): print(f'{list_names[i]:10s} {list_ages[i]:10n} {list_costs[i]:20n}')
false
9aef7bd624c31ca29c7ea9ef05178381e9e8c0d6
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ian_letourneau/Lesson03/slicing_lab.py
1,825
4.40625
4
#!/usr/bin/env python3 # Ian Letourneau # 4/26/2018 # A script with various sequencing functions def exchange_first_last(seq): """A function to exchange the first and last entries in a sequence""" return seq[-1:] + seq[1:-1] + seq[:1] def remove_every_other(seq): """A function to remove every other entry in a sequence""" return seq[::2] def remove_four(seq): """A function that removes the first 4 and last four entries in a sequence, and then removes every other entry in the remaining sequence""" return seq[4:-4:2] def reverse(seq): """A function that reverses a seq""" return seq[::-1] def thirds(seq): """A function that splits a sequence into thirds, then returns a new sequence using the last, first, and middle thirds""" length = len(seq) return seq[int(length/3*2):] + seq[0:int(len(seq)/3)] + seq[int(len(seq)/3):int(len(seq)/3*2)] if __name__ == '__main__': """A testing block to ensure all functions are operating as expected""" a_string = "this is a string" a_tuple = (2, 54, 13, 15, 22, 63, 75, 20, 8, 12, 5, 32) s_third = "123456789" t_third = (1, 2, 3, 4, 5, 6, 7, 8, 9) assert exchange_first_last(a_string) == "ghis is a strint" assert exchange_first_last(a_tuple) == ( 32, 54, 13, 15, 22, 63, 75, 20, 8, 12, 5, 2) assert remove_every_other(a_string) == "ti sasrn" assert remove_every_other(a_tuple) == (2, 13, 22, 75, 8, 5) assert remove_four(a_string) == " sas" assert remove_four(a_tuple) == (22, 75) assert reverse(a_string) == "gnirts a si siht" assert reverse(a_tuple) == (32, 5, 12, 8, 20, 75, 63, 22, 15, 13, 54, 2) assert thirds(s_third) == "789123456" assert thirds(t_third) == (7, 8, 9, 1, 2, 3, 4, 5, 6) print("All tests passed my fellow coders!")
true
6674a268183ec7ca465b28e57ba8b49e1ab8546c
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AurelPerianu/Lesson4/trigrams.py
2,662
4.5
4
#!/usr/bin/env python3 # Lesson 4 - Trigrams import random import string def main_fct(): #input_file = input("Please enter the name of a file (with extension):\n") input_file='sherlock_small.txt' with open(input_file, 'r') as f: text = f.read() #remove unprintable characters filter(lambda x: x in string.printable, text) # lower-case everything to remove that complication: text = text.lower() # define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' no_punct = "" for char in text: if char not in punctuations: no_punct = no_punct + char else: no_punct = no_punct + ' ' text=no_punct #split into words words = text.split() word_dict=trigram(words) text_new=generate_text(word_dict) print (text_new) def trigram(words): """build a trigram dict from the passed-in text""" # Dictionary for trigram results: # The keys will be all the word pairs # The values will be a list of the words that follow each pair word_dict = {} # loop through the words for i in range(len(words) - 2): pair = tuple(words[i:i+2]) third = words[i+2] # use setdefault() to append to an existing key or to generate a new key word_dict.setdefault(pair, []).append(third) return word_dict def generate_text(word_dict): """generate new text from the word_dict""" trigram_text = '' #generate a random number - text length will be dependent by this number #we cab adjust param: 10,5 random_prop = random.randint(len(word_dict.keys())//10,len(word_dict.keys())//5) for i in range(random_prop): # do thirty sentences #pick a word pair to start the sentence fragm = random.choice(list(word_dict.keys())) sentence=[] sentence.append(fragm[0]) sentence.append(fragm[1]) rand2=len(word_dict.keys())//10 for j in range(1,rand2): value= word_dict.get(fragm) if value==None: break if len(value)>1: ln=random.randint(1,len(value))-1 else: ln=len(value)-1 #create new word key from the old key and value fragm=(fragm[1],value[ln],) sentence.append(fragm[1]) sentence=list(sentence) # capitalize the first word: sentence[0] = sentence[0].capitalize() # add the period sentence[-1] += ". " sentence = " ".join(sentence) #add the complete sentence trigram_text+=sentence return trigram_text if __name__=='__main__': main_fct()
true
da5e4f291652ac9ade4aa67d9932e20c79fc47e7
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Dennis_Coffey/lesson03/list_lab.py
2,920
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 5 21:07:54 2018 @author: denni """ """Lesson 3 - List Lab assignment - Series of 4 steps modifying a list of fruits""" #Series 1: #Create list of fruits fruits = ['Apples','Pears','Oranges','Peaches'] print(fruits) #Copy original fruits list for use in Series 4 fruits_original = fruits.copy() #Prompt user for new fruit and then add to list response = input("Please enter a fruit > ") fruits.append(response) print(fruits) #Prompt user for number and display that number and corresponding fruit in list response = input("Please enter a number between 1 and " + str(len(fruits)) + " > ") print(response + ": " + fruits[int(response)-1]) #Add another fruit to the beginning of the list using “+” and display the list. fruits = ["Banana"] + fruits print(fruits) #Add another fruit to the beginning of the list using insert() and display the list. fruits.insert(0,"Papaya") print(fruits) #Display all the fruits that begin with “P”, using a for loop. for fruit in fruits: if fruit.lower().startswith('p'): print(fruit) #Copy Series 1 fruits list result for use in later results series1_fruits = fruits.copy() #Series 2: #Display the list from Series 1 print(fruits) #Remove the last fruit from the list and display. del fruits[-1] print(fruits) #Ask the user for a fruit to delete, find it and delete it. response = input("Enter a fruit to delete > ") fruits.remove(response) print(fruits) #Series 3: #Again, using the list from series 1: #Ask the user for input displaying a line like “Do you like apples?” for each fruit in the list (making the fruit all lowercase). #For each “no”, delete that fruit from the list. #For any answer that is not “yes” or “no”, prompt the user to answer with one of those two values (a while loop is good here) #Display the list. series3_fruits = series1_fruits.copy() for fruit in series1_fruits: response = input("Do you like " + fruit + "? ") while response.lower() not in ['yes','no']: response = input("Please answer with a yes or no > ") if response.lower() == "no": series3_fruits.remove(fruit) print(series3_fruits) #Series 4: #Make a copy of the list from series 1 and reverse the letters in each fruit in the copy. #Delete the last item of the original list. Display the original list and the copy. series4_fruits = [] for fruit in series1_fruits: # series4_fruits.append(''.join(sorted(fruit))) series4_fruits.append(fruit[::-1]) #Delete last item from original series 1 list. The last item from the original #list is Peaches fruits_original.pop() print("Print of resultant series 1 fruit list with letters for each fruit reversed") print(series4_fruits) print("Print of original series 1 fruit list with last fruit from list (Peaches) deleted") print(fruits_original)
true
23ff6a6c03b18dacce7e2262092f331ed56f6f5b
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/carlos_novoa/lesson03/list_lab.py
2,955
4.125
4
#!/usr/bin/env python3 """ Lesson3, List Lab Excercises """ def is_int(str): """Helper function to check that input can be cast into int""" try: int(str) return True except ValueError: return False def series1(): print("::: Series 1 :::::::") # print intial list fruits = ['Apples', 'Pears', 'Oranges', 'Peaches'] print(fruits) # add fruit to end and print af = input('Type a fruit to add to the end of the list: ') fruits.append(af) print(fruits) # print fruit at inputted index fruit_number = 0 while not 1 <= fruit_number <= len(fruits): try: fruit_number = int(input("Enter a number: ")) except ValueError: print("Not a valid number: ") print(fruits[fruit_number - 1]) # concat lists fruits = ['Grapes'] + fruits print(fruits) # insert item fruits.insert(0, 'Mango') print(fruits) # print items starting with 'P' for fruit in fruits: if fruit[:1] == 'P': print(fruit) series2(fruits) # run next series def series2(fruits): print("::: Series 2 :::::::") # print list from series1 print(fruits) # remove last fruit fruits = fruits[:len(fruits) - 1] print(fruits) # remove inputted fruit rf = input('Type a fruit name to delete: ') prompt = "Type the exact fruit name from this list {}: " found = False while not found: if rf in fruits: fruits.remove(rf) print(fruits) found = True else: rf = input(prompt.format(fruits)) # multiply list and remove every instance of inputted fruit fruits = fruits * 2 print(fruits) rf = input('Type another fruit name to delete: ') found = False while not found: if rf in fruits: while rf in fruits: fruits.remove(rf) found = True else: rf = input(prompt.format(fruits)) print(fruits) series3(fruits) # run next series def series3(fruits): print("::: Series 3 :::::::") # create copy of list fcopy = fruits[:] print(fcopy) # do you like x for fruit in fcopy: answer = input('Do you like {}?: '.format(fruit.lower())) while answer != 'no' and answer != 'yes': question = 'Do you like {}? (Type "yes" or "no"):' answer = input(question.format(fruit.lower())) # delete unliked fruits if answer == 'no': fruits.remove(fruit) print(fruits) series4(fruits) # run next series def series4(fruits): print("::: Series 4 :::::::") # reverse letters in each item of copy fcopy = fruits[:] for i, fruit in enumerate(fcopy): fcopy[i] = fruit[::-1] # remove last item from original fruits = fruits[:len(fruits) - 1] print(fruits) print(fcopy) series1() # start everything
true
9454d2775fbfff92a7abd259490189e8280430e3
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/stefan_lund/Lesson_2/series.py
1,585
4.3125
4
# python3 # series.py # functions to produce Fibonacci and Lucas number series def fibonacci(n): """ recursively computes the n'th value in the Fibonacci serie: 0, 1, 1, 2, 3, 5, 8, 13, ... """ if n == 0 or n == 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2) def lucas(n): """ recursively computes the n'th value in the Lucas serie: 2, 1, 3, 4, 7, 11, 18, 29, ... """ if n == 0: return 2 else: return fibonacci(n - 1) + fibonacci(n + 1) def sum_series(n, i, j): """ recursively computes the n'th value in the serie: n'th: 0, 1, 2, 3, 4, 5, 6 value: i, j, i + j, i + 2j, 2i + 3j, 3i + 5j, 4i + 8j ... for i = 0, j = 1 sum_series returns the fibonacci(n) for i = 2, j = 1 sum_series returns the lucas(n) """ if n == 0: return i elif n == 1: return j else: return sum_series(n - 1, i, j) + sum_series(n - 2, i, j) def test_sum_series(n): """ n: test values in the range 0 to n - 1 test if there are any dicrepancies in fiboncci and lucas series and the sum_series function. """ for i in range(n): assert (fibonacci(i) == sum_series(i, 0, 1)), "If you read this, there is a bug!" assert (lucas(i) == sum_series(i, 2, 1)), "If you read this, there is a bug!" print("Values matched when tested for all n including {}". format(n - 1)) if __name__ == '__main__': test_sum_series(31)
false
0e8b5ff1fc9c1bcb1d0bf2260afc794c997ef982
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/mark_luckeroth/lesson03/list_lab.py
1,791
4.15625
4
#!/usr/bin/env python3 #series 1 list1 = ['Apples','Pears','Oranges','Peaches'] print(list1) add_fruit = input("Please input the name of a fruit to add to the list: ") list1.append(str(add_fruit)) print(list1) while True: list_position = input("Enter a number between 1 and 5 to select a fruit from the list: ") try: list_position = int(list_position) except: print("invalid entry, enter number between 1 and 5 in integer form") continue if 0 < list_position < 6: break else: print("invalid entry, number must be one of the following: 1,2,3,4,5") print('fruit index: {}'.format(list_position)) print('fruit name: {}'.format(list1[list_position-1])) list1 = ['Plums'] + list1 print(list1) list1.insert(0, 'Papaya') print(list1) for item in list1: if item[0] == 'P': print(item, end=" ") print() #series 2 list2 = list1[:] print(list2) list2.pop() print(list2) while True: remove_fruit = input("Enter the name of one of the fruits from the list above to be removed: ") if remove_fruit in list2: break else: print("invalid entry, entry must be one of the following: {}".format(list2[:5])) list2 = list2*2 while remove_fruit in list2: list2.remove(remove_fruit) print(list2) #series 3 list3 = list1[:] for item in list3[:]: while True: like = input("yes or no: Do you like {}? ".format(item)) if like in ['yes','no']: break else: print("invalid entry, entry must be 'yes' or 'no'") if like == 'no': list3.remove(item) print(list3) #series 4 list4=list1[:] for i, item in enumerate(list1): list4[i] = item[::-1] list1.pop() print("Origninal list: {}".format(list1)) print("Copied list: {}".format(list4))
true
53c6eb5356e7537754f45f0e4babf3457d0a8641
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Craig_Morton/lesson08/Circle.py
2,109
4.1875
4
# ------------------------------------------------- # # Title: Lesson 8, pt 1/2 Circle # Dev: Craig Morton # Date: 9/23/2018 # Change Log: CraigM, 9/23/2018, pt 1/2 Circle # ------------------------------------------------- # from math import pi from functools import total_ordering import random import time @total_ordering class Circle: """ Compute the circle’s area Print the circle and get something nice Be able to add two circles together Be able to compare two circles to see which is bigger Be able to compare to see if there are equal (follows from above) be able to put them in a list and sort them """ def __init__(self, the_radius): self._radius = the_radius self._diameter = the_radius * 2 @classmethod def from_diameter(cls, diameter): self = cls(diameter / 2) return self @property def radius(self): return self._radius @radius.setter def radius(self, value): self._radius = value self._diameter = self._radius * 2 @property def diameter(self): return self._diameter @diameter.setter def diameter(self, value): self._diameter = value self._radius = self._diameter / 2 @property def area(self): return self._diameter * pi def __str__(self): return "Circle with radius: {}".format(self.radius) def __repr__(self): return "Circle({})".format(self.radius) def __add__(self, other): bigger_circle = Circle(self.radius + other.radius) return bigger_circle def __iadd__(self, other): self.radius = self.radius + other.radius return self def __lt__(self, other): return self.radius < other.radius def __eq__(self, other): return self.radius == other.radius def __mul__(self, num): return Circle(self.radius * num) def __imul__(self, num): self.radius = self.radius * num return self def __rmul__(self, num): return self * num def sort_key(self): return self._radius
true
5a7a6bf9fe258e1fdbf0009b0f08883ea90731ee
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/luyao_xu/lesson04/trigrams.py
2,102
4.1875
4
import random def read_file(filename): """ Read file into a new list of words :param f: filename :returns: read file """ with open(filename, 'r') as f: text = f.read() return text def trigram_dict(s): """ set up a trigram dictionary :param s:the split word :param result: final dictionary :param bigram: key :returns: a trigram dictionary with first two words use as key,and then associate third word with the key """ # split words s = s.split() # Grab the first two words and use that as a key, then associate third word with the key result = {} for i in range(0, len(s) - 2): bigram = '{} {}'.format(s[i], s[i + 1]) v = result.get(bigram, False) if not v: result[bigram] = [s[i + 2]] else: # move the next word and do the same result[bigram].append(s[i + 2]) return result def formulate(trigrams): """ create a new text :param trigrams: the dictionary :param k: random key in the dic :param words: split the random key :param third: a split word chose from the random key :param new_word: continue grabbing a word pair based on the last two words in your new text :param words: the new text :returns: a new text form from trigrams """ k = random.choice(list(trigrams.keys())) words = k.split() third = random.choice(trigrams.get(k)) words.append(third) while True: new = " ".join(words[-2:]) next_word = trigrams.get(new) if next_word is None: break words.append(random.choice(next_word)) return " ".join(words) # Write new text to file def write_file(filename, content): """ Write file :param f: filename :param content: the new text :returns: write file into a new text form """ with open(filename, 'w') as f: f.write(content) if __name__ == '__main__': s = read_file('sherlock_short.txt') d = trigram_dict(s) result = formulate(d) write_file('output.txt', result)
true
818f6cb4660de46b9a0f1f282b08298a097ea508
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/smckellips/lesson08/circle.py
1,843
4.125
4
#!/usr/bin/env python import math class Circle(object): def __init__(self, radius): self._radius = float(radius) def get_radius(self): return self._radius def get_diameter(self): return self._radius * 2 def set_diameter(self,diameter): self._radius = float(diameter /2) def get_area(self): return math.pi * 2 * self._radius def __str__(self): return f"Circle with radius: {self._radius}" def __repr__(self): return f"Circle({self._radius})" def __add__(self,other): return Circle(self._radius + other._radius) def __mul__(self, multiple): return Circle(self._radius * multiple) def __rmul__(self, multiple): return Circle(self._radius * multiple) def __eq__(self, other): return self._radius == other._radius def __ne__(self, other): return self._radius != other._radius def __gt__(self, other): return self._radius > other._radius def __ge__(self, other): return self._radius >= other._radius def __lt__(self, other): return self._radius < other._radius def __le__(self, other): return self._radius <= other._radius def __iadd__(self, other): self._radius += other._radius return self def __imul__(self, multiple): self._radius *= multiple return self radius = property(get_radius) diameter = property(get_diameter, set_diameter) area = property(get_area) class Sphere(Circle): def get_volume(self): return float(4 / 3 * math.pi * self._radius ** 3) def get_area(self): raise NotImplementedError def __str__(self): return f"Sphere with radius: {self._radius}" def __repr__(self): return f"Sphere({self._radius})" volume = property(get_volume)
false
0d515d74112d4d194e16552c9b480226aaba161e
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Craig_Morton/lesson03/strformat_lab.py
2,578
4.15625
4
# ------------------------------------------------- # # Title: Lesson 3, pt 3/4, String Formatting Exercise # Dev: Craig Morton # Date: 8/20/2018 # Change Log: CraigM, 8/20/2018, String Formatting Exercise # ------------------------------------------------ # # !/usr/bin/env python3 def first_task(): """First task - Tuple format string""" tuple_one = (2, 123.4567, 10000, 12345.67) # create a string formatter to produce: # 'file_002 : 123.46, 1.00e+04, 1.23e+04' print("file_{:0>3d} : {:.2f}, {:.2e}, {:.3e}".format(tuple_one[0], tuple_one[1], tuple_one[2], tuple_one[3])) def second_task(): """Second task - Using results from first task, use a different type of format string""" tuple_two = (2, 123.4567, 10000, 12345.67) print(f"file_{tuple_two[0]:0>3d} : {tuple_two[1]:.2f}, {tuple_two[2]:.2e}, {tuple_two[3]:.3e}") def third_task(tuple_value): """Third task - Dynamically building format strings""" tuple_three = "the {} numbers are: ".format(len(tuple_value)) if len(tuple_value) > 0: tuple_three += "{}".format(tuple_value[0]) for val in tuple_value[1:]: tuple_three += ", {}".format(val) return tuple_three def fourth_task(tuple_value_two): """Fourth task - Five element tuple and string formatting""" print("{n3:0>2d} {n4:0>2d} {n2:0>2d} {n0:0>2d} {n1:0>2d}".format( n0=tuple_value_two[0], n1=tuple_value_two[1], n2=tuple_value_two[2], n3=tuple_value_two[3], n4=tuple_value_two[4])) def fifth_task(): """Fifth Task - Using f-strings""" orange = ("orange", 1.3) lemon = ("lemon", 1.1) print(f"The weight of an {orange[0]} is {orange[1]} and the weight of a {lemon[0]} is {lemon[1]}") print( f"The weight of an {orange[0].upper()} is {orange[1] * 1.2} " f"and the weight of a {lemon[0].upper()} is {lemon[1] * 1.2}") def sixth_task(): """Sixth Task - Displaying data in columns and string formatting""" lst = list() lst.append(("Frodo", 25, 53)) lst.append(("Bilbo", 71, 142)) lst.append(("Gandalf", 82, 1089)) lst.append(("Aragorn", 40, 24593)) lst.append(("Elrond", 183, 542099)) lst.append(("Durin", 97, 1000000)) for d in lst: print("{:<20} {:>3d} ${:>15.2f}".format(*d)) extra_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) print(("{:5d}" * 10).format(*extra_tuple)) first_task() second_task() print(third_task(())) print(third_task((0,))) print(third_task((1, 2, 3))) print(third_task((4, 5, 6, 7, 8, 9))) fourth_task((4, 30, 2017, 2, 27)) fifth_task() sixth_task()
false
48e5ee6bcb8c0c9fb10f54fd96f4e96e9056a5f4
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/ChelseaSmith/Lesson2/series.py
1,524
4.34375
4
def fibonacci(n): if n == 0: # initializes the series return 0 elif n == 1: return 1 else: return fibonacci(n-2) + fibonacci(n-1) # function recursion to calculate values beyond the first two def lucas(n): if n == 0: # initializes the series return 2 elif n == 1: return 1 else: return lucas(n-2) + lucas(n-1) # function recursion to calculate values beyond the first two def sum_series(n, a=0, b=1): # establishes default values for optional parameters if n == 0: # initializes the series return a elif n == 1: return b else: return sum_series(n-2, a, b) + sum_series(n-1, a, b) # a and b included so default values aren't used print("Fibonacci test") print(fibonacci(0)) # this and the following test make sure that the if and elif statements work right print(fibonacci(1)) print(fibonacci(6)) # verifies that the recursion part of the function works correctly print("Lucas test") print(lucas(0)) # this and the following test make sure that the if and elif statements work right print(lucas(1)) print(lucas(5)) # verifies that the recursion part of the function works right print("Sum series test") print(sum_series(0)) # this and the following test make sure that the function works with only the required parameter print(sum_series(5)) print(sum_series(0, 2, 1)) # these tests check that the test works for various optional paramenters print(sum_series(5, 2, 1)) print(sum_series(5, 1, 1))
true
499e0dfc7e4970bea55e30cbd0c29c4036b9ecd1
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Wieslaw_Pucilowski/lesson03/list_lab.py
1,960
4.21875
4
#!/usr/bin/env python3 __author__ = "Wieslaw Pucilowski" # Series 1 fruits=["Apples", "Pears", "Oranges", "Peaches", "Pineapples"] list_fruits=fruits print("List of fruits:") print(list_fruits) list_fruits.append(input("What fruit would you like to add to the list: ")) print("List of fruits:") print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) num=input("Enter the number but not greater than "+str(len(list_fruits))+": ") print("The number", num, "is for fruit",list_fruits[int(num)-1]) list_fruits=["Plums"]+list_fruits print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) list_fruits.insert(0,"Mangos") print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) for fruit in list_fruits: if fruit[0] == "P": print(fruit) # Series 2 list_fruits=fruits print("Series 2") print("Removing last item fron the list") list_fruits=list_fruits[:-1] print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) del_fruit=input("What fruit to remove from the list:") if del_fruit in list_fruits: list_fruits.remove(del_fruit) else: print(del_fruit,"Fruit not found in the list") print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) # Series 3 list_fruits=fruits print("Series 3") for fruit in list_fruits: answer="None" while answer.lower() not in ['yes','no']: answer=input("Do you like "+fruit.lower()+" ? [yes/no]:") if answer.lower()=='no': list_fruits.remove(fruit) print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) # Series 4 list_fruits=fruits print("Series 4") list_fruits_reverse=[] for i in list_fruits: list_fruits_reverse.append(i[::-1]) del list_fruits[-1] #list_fruits.pop() print(list_fruits) print(", ".join(["{}"]*len(list_fruits)).format(*list_fruits)) print(list_fruits_reverse) print(", ".join(["{}"]*len(list_fruits_reverse)).format(*list_fruits_reverse))
false
dd7882ce1afedab638dc354fa42ffb62c3903f74
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/csdotson/lesson08/circle.py
2,014
4.53125
5
#!/usr/bin/env python3 import math class Circle: """Create a Circle class representing a simple circle""" def __init__(self, radius): if radius < 0: raise ValueError("radius can't be less than 0") self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, val): if val < 0: raise ValueError("radius can't be less than 0") self._radius = val @property def diameter(self): return 2 * self.radius @diameter.setter def diameter(self, val): self.radius = val / 2 @classmethod def from_diameter(cls, diameter): return ( cls(diameter/2) ) @property def area(self): return (math.pi * math.pow(self.radius, 2)) def __lt__(self, other): """ Define less than comparator for circles """ return (self.radius < other.radius) def __eq__(self, other): return(self.radius == other.radius) def __add__(self, other): """ Add radii of two circles """ if isinstance(other, Circle): return Circle(self.radius + other.radius) else: raise TypeError("Both objects need to be circles") def __sub__(self, other): """ Subtract radii of two circles """ if isinstance(other, Circle): return Circle(self.radius - other.radius) else: raise TypeError("Both objects need to be circles!") def __mul__(self, val): """ Multiply self by val: Circle * 4 """ return Circle(self.radius * val) def __rmul__(self, val): """ Multiply val by self: 4 * Circle """ return Circle(self.radius * val) def __truediv__(self, val): """ Divide self by val: Circle / 4 """ return Circle(self.radius / val) def __str__(self): return "Circle with radius: {}".format(self.radius) def __repr__(self): return "Circle({})".format(self.radius)
true
093e571055ae258dd05a5c4aa608fd79683f1815
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/rgpag/lesson04/trigrams.py
1,570
4.1875
4
#!/usr/bin/env python3 import random # txt file to be used text_in = 'sherlock_full.txt' with open(text_in) as f: msg = f.read() # manipulate text file to be more trigram friendly string = msg.lower() string = string.replace("\n", " ") string = string.replace("--", " ") string = string.replace("-", " ") spl_string = string.split(" ") # init vals i = 0 j = 0 str_dict = {} for i in range(0, len(spl_string)-2): key = spl_string[i] + " " + spl_string[i+1] str_dict.setdefault(key, []).append(spl_string[i+2]) def rand_start(): rand_key = random.choice(list(str_dict.keys())) return rand_key def get_next(x, key): out = "" for i in range(x): if key in str_dict: next_word_list = str_dict[key] # select random index from next word list rand_index = random.randint(0, len(next_word_list)-1) next_word_rand = next_word_list[rand_index] split_key = key.split(" ") key = split_key[1] + " " + next_word_rand out = out + " " + next_word_rand else: key = rand_start() return out def trigrams(x): start = rand_start() print(get_next(x, start)) if __name__ == "__main__": print("you are in trigram main") print("you are currently using text from {}".format(text_in)) while_asking_for_size = 1 while while_asking_for_size == 1: sel = int(input("what size trigram do you want? ('0' to quit) ")) if sel == 0: while_asking_for_size = 0 else: trigrams(sel)
false
7886724d68b0a852164116395ed4b8af843d916e
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Sahlberg/Lesson8/Circle.py
1,826
4.375
4
class Circle(object): """For manipulating circles""" import math as m def __init__(self, radius): """Initialize radius""" self._radius = radius @property def radius(self): """radius property""" return self._radius @property def diameter(self): """Diameter property""" return self._radius*2 @property def area(self): """Area property""" return float(f'{Circle.m.pi * self._radius**2:.4f}') @diameter.setter def diameter(self, diameter): """Set diameter""" self._radius = _diameter/2 @classmethod def from_diameter(cls, diameter): """Returns radius from diameter""" radius = diameter/2 return cls(radius) def __str__(self): """Returns new string""" return f'Circle with radius: {self._radius:.6f}' def __repr__(self): """Returns string of Circles radius""" return f'Circle({self._radius:.0f})' def __add__(self,circle_x): """Addition of circle objects""" new_circle = Circle(self._radius + circle_x.radius) return new_circle def __mul__(self, other): """multiplication of circle objects""" if isinstance(other, Circle): return Circle(self._radius * other._radius) else: return Circle(self._radius * other) __rmul__ = __mul__ def __lt__(self, other): """Allows less than to work with circle objects""" return self._radius < other.radius def __gt__(self, other): """Allows greater than to work with circle objects""" return self._radius > other.radius def __eq__(self, other): """Allows equivalence comparison of circle objects""" return self._radius == other.radius
false
c90f77973cf02908e094e2609026fb9ec39eab1b
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/TressaHood/lesson04/dict_lab.py
1,331
4.15625
4
#!/usr/bin/env python3 # Activity 1 Dictionary and Set lab def main(): # Dictionaries 1 # create a dictionary d = {"name": "Chris", "city": "Seattle", "cake": "Chocolate"} print(d) # remove last item d.pop("cake") print(d) # add new item d["fruit"] = "Mango" print(d) # display the keys print(d.keys()) # display the values print(d.values()) # if "cake" in d: print("There is cake, not deleted") else: print("There is no cake") # if "Mango" in d.values(): print("There is a Mango, not deleted") else: print("There is no Mango") # Dictionaries 2 d = {"name": None, "city": None, "cake": None} for item in d: d[item] = item.lower().count("t") print(d) # Sets 1 # make sets s2 = set(range(0, 21, 2)) s3 = set(range(0, 21, 3)) s4 = set(range(0, 21, 4)) print(s2) print(s3) print(s4) # subset? print(s3.issubset(s2)) print(s4.issubset(s2)) # Sets 2 s = set() for i in "Python": s.update(i) # add 'i' s.update('i') print(s) # create a frozen set fs = frozenset(('m', 'a', 'r', 'a', 't', 'h', 'o', 'n')) print(s.union(fs)) print(s.intersection(fs)) if __name__ == '__main__': main()
true
192fabca7fb01a38c0bad5f30ed010c6330c0d6c
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/srepking/Lesson04/kata.py
1,779
4.1875
4
import random trigram = {} # Read in a file line by line and create a dictionary of trigrams. string_words = '' with open('sherlock.txt', 'r') as from_file: for line in from_file: word = '' for char in line: if char.isalpha(): word += char.lower() else: word += ' ' # Add a space if character is not alphanumeric string_words += word # Create a comma separated list of all the words in the book. list_words = string_words.split() # Create a dictionary with first two words as key, and third word as value. for i in range(int(len(list_words)) - 2): dict_key = list_words[i] + ' ' + list_words[i + 1] if dict_key not in trigram: trigram[dict_key] = [list_words[i + 2]] else: trigram[dict_key].append(list_words[i + 2]) str_trigram = str(trigram) # Printed to a file for verification of correct algorithm. with open('trigram.txt', 'w') as to_file: to_file.write(str(trigram)) # Now that your dictionary of trigrams has been created, you can start # writing a story. Start by choosing a random key to start the story. random_key = random.choice(list(trigram.keys())) # Start new story.... # Specify how may words you want in the story story_length = 200 new_story = random_key.split() + trigram[random_key] for i in range(story_length): pick_one = random.choice(trigram[new_story[-2] + ' ' + new_story[-1]]) new_story = new_story + \ [random.choice(trigram[new_story[-2] + ' ' + new_story[-1]])] # Print the new story to a new text file. with open('New_Story.txt', 'w') as to_file: to_file.write(" ".join(new_story)) print("Check you working directory for a text file named 'New Story.txt'" " to see the results of the kata.")
true
a1d4b01c4e9369f66536905d2eaee6bba29bc6bf
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/AurelPerianu/Lesson3/string_lab.py
1,433
4.34375
4
#!/usr/bin/env python3 #string formatting #task1 # Write a format string that will take the following four element tuple: tuple1 = (2, 123.4567, 10000, 12345.67) # and format it formatted1= 'file_{0:03d}: {1:.2f}, {2:.2e}, {3:.2e}'.format(*tuple1) # results: 'file_002 : 123.46, 1.00e+04, 1.23e+04' print (formatted1) #task2 - alternate type of string formatting print('\nTask two') print(f'file_{tuple1[0]:03d}: {tuple1[1]:.2f}, {tuple1[2]:.2e}, {tuple1[3]:.2e}') #task3 - dianmically build aup format strings def display_seq(seq): l=len(seq) print (("There are {} items, and there are: "+", ".join(["{}"]*l)).format(l,*seq)) print('\nTask three') t = (1,2,3) display_seq(t) #task4 - tuple of numbers print('\nTask four') tuple2 = (4, 30, 2017, 2, 27) print("{3:02d} {4} {2} {0:02d} {1}".format(*tuple2)) #task5 - f-strins example print('\nTask five') list1 = ['oranges', 1.3, 'lemons', 1.1] print(f'The weight of an {list1[0] [:-1]} is {list1[1]} and the weight\ of a {list1[2] [:-1]} is {list1[3]}\n') print(f'The weight of an {list1[0] [:-1].upper()} is {list1[1]*1.2} and the\ weight of a {list1[2] [:-1].upper()} is {list1[3]*1.2}\n') #task6 - columns print('\nTask six') names = ['Name1','Name11', 'Name111'] age = [5, 51, 101] cost = [23000.50,12.00,7609.11] for i in range(len(names)): print(f'{names[i]:20s} {age[i]:20n} {cost[i]:20n}') #extra print(' '.join(('%*s' % (5, i) for i in range(10))))
false
e2df6228ccc92fe905762ff250f2e235e6cde07f
Shubh250695/Python-modules
/M01.py
1,197
4.34375
4
# write a Python program to read data from a file which has text containing emails, # write only the emails from the file into another file. # You can use 're' module to extract emails from the text file. import re fileToRead = 'Sample01.txt' fileToWrite = 'Output01.txt' delimiterInFile = [',', ';'] def validateEmail(strEmail): # .* Zero or more characters of any type. if re.match("(.*)@(.*).(.*)", strEmail): return True return False def writeFile(listData): file = open(fileToWrite, 'w+') strData = "" for item in listData: strData = strData+item+'\n' file.write(strData) listEmail = [] file = open(fileToRead, 'r') listLine = file.readlines() for itemLine in listLine: item =str(itemLine) for delimeter in delimiterInFile: item = item.replace(str(delimeter),' ') wordList = item.split() for word in wordList: if(validateEmail(word)): listEmail.append(word) if listEmail: print(len(listEmail),"emails collected and you get it in Output01.txt.") print("\n") print(listEmail) writeFile(listEmail) else: print("No email found.")
true
2646cdfc686be5545fa88d83ab336baa9f71a3e1
L1ves/pythonNaPrimere
/empty_list.py
1,534
4.25
4
#empty_list.py """ Создайте пустой список с име- нем nums. Предложите поль- зователю последовательно вводить числа. После ввода каждого числа добавьте его в конец списка nums и вы- ведите список. После того как пользователь введет три числа, спросите, хочет ли он оставить последнее введенное число в списке. Если пользователь от- ветит «no», удалите последний элемент из списка. Выведите список. """ nums = [] """ print("Пожалуйста вводите последовательно числа: \n") nums.append(int(input("Введите число: \n"))) print(nums) nums.append(int(input("Введите число: \n"))) print(nums) nums.append(int(input("Введите число: \n"))) print(nums) ask = input("Вы хотите оставить последнее число в списке?") if ask == "no": nums.remove(nums[2]) print(nums) """ count = 0 while count < 3: print("Пожалуйста вводите последовательно числа: \n") num = (int(input("Введите число: \n"))) nums.append(num) print(nums) count = count + 1 ask = input("Вы хотите оставить последнее число в списке?") if ask == "no": nums.remove(num) print(nums)
false
356e403b4bff5a5e92fc596a80ce1e7f1a17d1b3
xurror/365-days-of-code
/projects/Classic_Algorithms/closest_pair_problem.py
1,030
4.15625
4
from math import pow, sqrt #calculate the distance between 2 points def distance(tuple1, tuple2): x1, y1 = tuple1[0], tuple1[1] x2, y2 = tuple2[0], tuple2[1] d = pow((x1 - x2), 2) + pow((y1 - y2), 2) d = sqrt(d) return d def createPoint(x, y): point = () """point.append""" def compareDistance(points): if (len(points)/2)%2 == 0: #Create two sublist middle = int(len(points)/2) #left sublist left_points = [points[i] for i in range(middle)] # right sublist right_points = [points[i] for i in range(middle, len(points))] for i in range(0, middle, 2): left_point = (left_points[i], left_points[i+1]) right_point = (right_points[i], right_points[i+1]) print(distance(left_point, right_point)) print(left_points) print(right_points) if __name__ == "__main__": points = list(map(int, input("Enter all points seperated with commas\n> ").split(', '))) compareDistance(points)
false
9796ce2512388ee195f7283fa67b6c69f1363dc6
ragulkesavan/python-75-hackathon
/RECURSION/recursion.py
406
4.15625
4
'''PROBLEM: Calculate the total number of possible squares in a chess board of n*n size (n is got from user)''' def chess(n): if n==1: return 1 else : return (n*n)+chess(n-1) n=int(input("give the n-chess board size : ")) print("\nthe chess board has "+str(chess(n))+" possible squares") ''' OUTPUT: give the n-chess board size : 8 the chess board has 204 possible squares '''
true
4f881d4928f10da1ead7e189b60e6b24fed50c4a
ragulkesavan/python-75-hackathon
/TUPLES/tuple.py
1,513
4.5
4
#tuples '''TUPLES ARE UNCHANGABLE ORDERED COLLECTION OF DATA VALUES ONCE TUPLES ARE CREATED NEW VALUES CANNOT BE ADDED,EXISTING VALUES CANNOT BE DELETED OR RE-ORDERED OR CHANGED TUPLES ARE REPRESENTED USING ROUND BRACES () INBETWEEN VALUES ARE SEPERATED BY COMMA TUPLES ARE IMMUTABLE''' #TUPLE CREATION t=(1,2,3,4,5,"talent","accurate") #ACCESSING TUPLES BY INDEXING print "THE SECOND ELEMENT IN THE TUPLE IS : ",t[1] #ACCESSING TUPLES BY INDEXING FORM LAST -indexing form last starts from -1 and goes as -2,-3 print "THE LAST ELEMENT IN THE TUPLE IS : ",t[-1] #LENGTH OF TUPLE -len(t) print "THE LENGTH OF THE TUPLE IS : ",len(t) #count(x) in tuple -counts the no of times x occurs in tuple print "THE TOTAL NUMBER OF TIMES GIVEN VALUE IS IN THE TUPLE : ",t.count(1) #index(x) function in tuple -gives the index of the element x print "THE INDEX OF GIVEN VALUE IS IN THE TUPLE talent : ",t.index("talent") #element present in tuple if "accurate" in t: print "yes present" else : print "no" #for loop for tuple for i in t: print i #concatenation of tuple t[a:b]-creates new tuple from ath elemnt to b-1th element of t print "sliced tuple : ",t[0:5] #deletion of tuple del(t) ''' OUTPUT: THE SECOND ELEMENT IN THE TUPLE IS : 2 THE LAST ELEMENT IN THE TUPLE IS : accurate THE LENGTH OF THE TUPLE IS : 7 THE TOTAL NUMBER OF TIMES GIVEN VALUE IS IN THE TUPLE : 1 THE INDEX OF GIVEN VALUE IS IN THE TUPLE talent : 5 yes present 1 2 3 4 5 talent accurate (1, 2, 3, 4, 5) '''
true
c63fffe0abbdf509e9cd70df059b1aee770ffed5
ragulkesavan/python-75-hackathon
/INHERITANCE/hybrid_inheritance.py
1,454
4.4375
4
#MULTIPLE INHERITANCE #When a child class inherits from multiple parent classes, it is called as multiple inheritance. class orders:#DEFINITION PARENT CLASS l=[] def order(self): product_name=input("enter the name of product : ") quantity=int(input("enter the quantity of product : ")) address=input("enter delivery address :") self.l.append([product_name,quantity,address]) def display_orders(self): for i in self.l: print i class customer(orders): #DEFINITION PARENT CLASS def get_cust(self): cus_name=input("cust name : ") self.order() class vendor(orders): #DEFINITION PARENT CLASS def get_vendor(self): vend_name=input("vendor name : ") self.display_orders() class amazon(customer,vendor): #DEFINITION CHILD CLASS -IT INHERITS MORE THEN 1 PARENT def __init__(self): print "customer->1 \nvendor->2" n=int(input("give choice : ")) if n==1: self.get_cust() elif n==2: self.get_vendor() else : print "wrong choice" a=amazon() a.__init__() ''' SAMPLE I/O: customer->1 vendor->2 give choice : 1 cust name : "cust_1" enter the name of product : "mi note 4" enter the quantity of product : 1 enter delivery address : "tce mens hostel" customer->1 vendor->2 give choice : 2 vendor name : "vend_1" ['mi note 4', 1, 'tce mens hostel'] '''
true
cae545f616c84d80dfad4a056af570cee0f7e3fb
ericgtkb/design-patterns
/Python/TemplateMethod/HouseBuilder/house.py
1,052
4.1875
4
import abc class House(abc.ABC): def build_house(self): # Can be set as final in python 3.8 using the final decorator self.build_foundation() self.build_pillars() self.build_walls() self.build_windows() print('The house is built!') def build_foundation(self): print('Building foundation...') def build_windows(self): print('Building glass windows...') @abc.abstractmethod def build_pillars(self): pass @abc.abstractmethod def build_walls(self): pass class WoodenHouse(House): def build_pillars(self): print('Building wooden pillars...') def build_walls(self): print('Building wooden walls...') class GlassHouse(House): def build_pillars(self): print('Building glass pillars...') def build_walls(self): print('Building glass walls...') if __name__ == '__main__': house = WoodenHouse() house.build_house() print('=' * 40) house = GlassHouse() house.build_house()
true
a0c07a217df2219053dd65579c8eaa88af670eae
carlson9/python-washu-2014
/day1/class1.py
373
4.15625
4
def is_triangle(first, second, third): lengths = sorted([first,second,third]) if lengths[2] <= lengths[0]+lengths[1]: print "Yes" else: print "No" def prompt(): first = int(raw_input("Input first side: ",)) second = int(raw_input("Input second side: ",)) third = int(raw_input("Input third side: ",)) is_triangle(first, second, third)
true
d3dde4521bea8c8385cc0dc12a8ad01351c199d6
carlson9/python-washu-2014
/assignment1/school.py
1,534
4.3125
4
class School(): def __init__(self, school_name): #initialize instance of class School with parameter name self.school_name = school_name #user must put name, no default self.db = {} #initialize empty dictionary to store kids and grades def add(self, name, student_grade): #add a kid to a grade in instance of School if student_grade in self.db: #need to check if the key for the grade already exists, otherwise assigning it will return error self.db[student_grade].add(name) #add kid to the set of kids within the dictionary else: self.db[student_grade] = {name} #if the key doesn't exist, create it and put kid in def sort(self): #sorts kids alphabetically and returns them in tuples (because they are immutable) sorted_students={} #sets up empty dictionary to store sorted tuples for key in self.db.keys(): #loop through each key sorted_students[key] = tuple(sorted(self.db[key])) #add dictionary entry with key being the grade and the entry the tuple of kids return sorted_students def grade(self, check_grade): if check_grade not in self.db: return None #if the key doesn't exist, there are no kids in that grade: return None return self.db[check_grade] #if None wasn't returned above, return elements within dictionary, or kids in grade def __str__(self): #print function will display the school name on one line, and sorted kids on other line return "%s\n%s" %(self.school_name, self.sort())
true
f33052966054b29233e4301dac759c420d324953
magnusjacobsen/algopy
/sorting/mergesort.py
1,133
4.28125
4
''' Mergesort - first the list is recursively divided down to pairs of 2 - then sorts those pairs, and then - merges all the pairs until the entire list is mergesorted ''' def sort(a, inplace=True): if not inplace: a = list(a) n = len(a) aux = [None] * n rec_sort(a, aux, 0, n - 1) return a def rec_sort(a, aux, lo, hi): # first sort a[lo .. hi] if hi <= lo: return mid = lo + (hi - lo) // 2 rec_sort(a, aux, lo, mid) # sort left half rec_sort(a, aux, mid + 1, hi) # sort the right half merge(a, aux, lo, mid, hi) # merge the two halfs def merge(a, aux, lo, mid, hi): i = lo j = mid + 1 # copy a[lo .. hi] to aux[lo .. hi] k = lo while k <= hi: aux[k] = a[k] k += 1 # merge back to a[lo .. hi] k = lo while k <= hi: if i > mid: a[k] = aux[j] j += 1 elif j > hi: a[k] = aux[i] i += 1 elif aux[j] < aux[i]: a[k] = aux[j] j += 1 else: a[k] = aux[i] i += 1 k += 1
false
42270d36edde93effd9f08251a53bef71acb341c
agodi/Algorithms
/Python/TreeCommonAncestor.py
248
4.25
4
def appendsums(lst): """ Repeatedly append the sum of the current last three elements of lst to lst. """ for i in range(25): aux = lst[-1] + lst[-2] + lst[-3] lst.append(aux) print(lst[20]) appendsums([0, 1, 2])
true
13478c287305f67d016828532cc7f5d44fcdcbec
AJohnson24/CodingPractice
/DailyCodingProblem/10.py
585
4.21875
4
#!/usr/bin/env python3 # Good morning! Here's your coding interview problem for today. # This problem was asked by Apple. # Implement a job scheduler which takes in a function f and an # integer n, and calls f after n milliseconds. import time import sys def scheduler(f, n): print(f"waiting {n} milliseconds") time.sleep(n/1000) f() def sequence(): for i in range(0,10): print(i) def main(): arg = sys.argv[1] try: delay = int(arg) except ValueError: print("error: please enter an integer") exit(1) scheduler(sequence, delay) if __name__ == '__main__': main()
true
51f660859a5a037a94e9d2abe4c108adcfad35c1
KojoBoat/Global-code
/while_loop.py
853
4.25
4
#while loops #i=6 #while(i < 19): ## i += 1 # print (i) # i = 13 # print ("Even numbers between 12 and 20 \n# i = 13 # print ("Even numbers between 12 and 20 \n") # while (i < 20): # if i % 2 == 0: # print(i) # i = i + 1") # while (i < 20): # if i % 2 == 0:# i = 13 # print ("Even numbers between 12 and 20 \n") # while (i < 20): # if i % 2 == 0: # print(i) # i = i + 1 # print(i) # i = i + 1 #function that takes two numbers and prints the even numbers between them # def evens(num1,num2): # num1 += 1 # while(num1 < num2): # if(num1 % 2 == 0): # print (num1) # num1 += 1 # evens (1,11) def reverse_evens(num1,num2): num1 += 1 num2 -= 1 while(num2 >= num1): if(num2 % 2 == 0): print (num2) num2 -= 1 reverse_evens(1,10)
false
88df0b5d81710743a62ed140443aded52ae5ceda
enriqueboni80/puc-python-exercicio_01
/exercicio1.py
1,303
4.3125
4
from collections import deque print("") print("-----------------") print("") print("Enrique Bonifacio") print("") print("Exemplo de Lista:") thislist = {"apple", "banana", "cherry"} print(thislist) print("") print("Exemplo de Tuplas:") thistuple = ("apple", "banana", "cherry") print(thistuple) print("") print("exemplo FIFO") waitlist2 = deque() waitlist2.append('Erin') waitlist2.append('Samantha') waitlist2.append('Joe') waitlist2.append('Martin') waitlist2.append('Helena') waitlist2.popleft() print("Resultado da FILA (FIFO)- Primeiro a entrar é o primeiro a sair") print(waitlist2) print("") print("Exemplo de LIFO:") waitlist = deque() waitlist.append('Erin') waitlist.append('Samantha') waitlist.append('Joe') waitlist.append('Martin') waitlist.append('Helena') waitlist.pop() print("Resultado da PILHA (LIFO) - Ultimo a entrar é o primeiro a sair") print(waitlist) print("") print("Algorítmo numeros primos") for n in range(2,10): for x in range(2,n): if n % x == 0: print(n,'equals', x, '*', n//x) break else: print(n, 'is a prime number') print("Resposta do exercício: o else esta identado fora do for por causa do break existente dentro do primeiro FOR > IF") print("Quando o numero é primero ele já sai do primeiro loop e imprime a Msg")
false
66ca1583771051ee8a700364e081cf06025c9670
mejn0ur/novetres
/cosseno_angulo.py
1,229
4.21875
4
#Este programa calcula o cosseno de um angulo #lido atraves do TGT - Teorema Geral da Trigonometria #Antes de tudo, importamos a biblioteca math import math print 'Entre com o angulo cujo cosseno calcularemos:' angulo = float(raw_input('> ')) print 'O resultado pode obtido de 3 maneiras:' print ' ' print '1. Calculando (cos(x))^2 = 1 - (sen(x))^2 // com o sen(x) calculado a partir da funcao math.sin()' print '2. Calculando cos(x) = 1 - sen(x) // com o sen(x) lido, caso seja um angulo conhecido.' print '3. Usando a funcao math.cos() pura.' print ' ' print 'O angulo tem seno conhecido? (sim/nao)' resp = raw_input('> ') if resp == 'nao': print 'Deseja calcular pela funcao math.sin() - 1 - ou pela funcao math.cos() - 2 - ?' resp2 = raw_input('> ') if resp2 == '1': cos = math.sqrt(1 - math.sin(angulo)) print 'O cosseno do angulo dado e: ', cos elif resp2 == '2': cos = math.cos(angulo) print 'O cosseno do angulo dado e: ', cos elif resp == 'sim': print 'Por favor entre com o seno do angulo:' sen = float(raw_input('> ')) cos = math.sqrt(1 - (sen**2)) print 'O cosseno do angulo dado e: ', cos print 'Obrigado por usar nosso programa!'
false
7626d15bb5d26ad5b39034b4e74f1eb0e7cfe865
mejn0ur/novetres
/le_imprime_matriz.py
610
4.1875
4
#programa recebe numeros de uma matriz e retorna a matriz print 'Este programa recebe uma matriz e imprime-a.' print '' matriz = [] linha = [] print 'Entre com a quantidade de linhas:' lin = int(raw_input('-> ')) print 'Entre com a quantidade de colunas:' col = int(raw_input('-> ')) print 'E agora a matriz.' for i in range (1, lin + 1): print 'linha: ', i for j in range (1, col + 1): print 'Entre com o termo numero: ', j num = float(raw_input('-> ')) linha = linha + [num] matriz = matriz + [linha] linha = [] print 'Segue matriz.' for l in matriz: print l
false
558ffc3400d66cf7dca027ac72850387a047fe2e
lephdao/cracking-coding-interview
/Array and String/length_of_longest_substring.py
980
4.1875
4
''' Given a string s, find the length of the longest substring without repeating characters. Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. ''' def lengthOfLongestSubstring(s): if len(s) == 1: return 1 if s == "" or s == " ": return 0 result = 0 countStr = "" i = 0 while len(s) > 1: i = 1 countStr = "" countStr = countStr + s[0] while s[i] not in countStr: countStr = countStr + s[i] if i < len(s) - 1: i = i + 1 if len(countStr) > result: result = len(countStr) s = s[1:] return result s1 = "abcabcbb" n1 = lengthOfLongestSubstring(s1) print(n1) s2 = "pwwkew" n2 = lengthOfLongestSubstring(s2) print(n2) # two special cases s3 = "" n3 = lengthOfLongestSubstring(s3) print(n3) s4 = "f" n4 = lengthOfLongestSubstring(s4) print(n4)
true
6a9b1dcf902cd8beac2fdb728539bd21ddba9bfc
mambalong/Algorithm_Practice
/SlidingWindow/0438_findAnagrams.py
1,430
4.125
4
''' 438. Find All Anagrams in a String Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". ''' from collections import defaultdict def findAnagrams(s, p): need_cnt = len(p) need = defaultdict(int) for c in p: need[c] += 1 res = [] left, right = 0, 0 while right < len(s): c = s[right] right += 1 if need[c] > 0: need_cnt -= 1 need[c] -= 1 while need_cnt == 0: if right - left == len(p): res.append(left) c = s[left] left += 1 need[c] += 1 if need[c] > 0: need_cnt += 1 return res print(findAnagrams("cbaebabacd", "abc"))
true
0c06db606ee0ab3899b3ccc506113b8b88dbc273
xsong15/codingbat
/list-1/sum3.py
223
4.15625
4
def sum3(nums): """ Given an array of ints length 3, return the sum of all the elements. """ return sum(nums) print(sum3([1, 2, 3])) #→ 6 print(sum3([5, 11, 2])) #→ 18 print(sum3([7, 0, 0])) #→ 7
true
138e492317b185f0b17e6d04635ff21b27c20e11
adamcfro/practice-python-solutions
/fibonacci.py
335
4.21875
4
def fib_nums(): new_nums = 'yes' while new_nums == 'yes': number = int(input("How many Fibonacci numbers would you like to generate?: ")) a = 0 b = 1 for num in range(1, number + 1): print(a) a, b = b, a + b new_nums = input("More nums? (yes or no) ") fib_nums()
true
3fcd80f1586f84ecb5ec40bd82f323c87c8e61de
PedroRgz/Sesiones-Python
/generadores.py
783
4.15625
4
''' Son estructuras que extraen valores de una función Se almacenan de uno en uno Cada vez que se genera, se mantiene en un estado pausado hasta que se solicita el siguiente --> Susp de estado sustituye el 'return' de una funcion por 'yield' que construye un objeto iterador def numspares(): . . . yield numeros #primera llamada [2], suspension #segunda llamada [2,4], suspension #... *Son más eficientes *Utilies con valores infinitos (generar ip's al azar) ''' def generaPares(lim): num =1 while num < lim: yield num*2 num +=1 cont_pares = generaPares(10) print(next(cont_pares)) print('relleno') print(next(cont_pares)) print('relleno') print(next(cont_pares)) print('relleno') print(next(cont_pares)) print('relleno')
false
5a0e316aa72b56a5e6f503a8b152ddb689076640
jviray/python-practice
/factorial.py
311
4.125
4
""" Write a function that takes an integer `n` as an input; it should return n*(n-1)*(n-2)*...*2*1. Assume n >= 0. As a special case, `factorial(0) == 1`. Difficulty: easy. """ def factorial(n): factorial = 1 if n >= 1: for i in range(2, n + 1): factorial *= i return factorial print(factorial(7))
true
14fd536ebf075902e093ce736c61be10642f506a
brinsga/python-bootcamp
/Day_1/HW01_ch05_ex03.py
2,593
4.625
5
#!/usr/bin/env python # HW02_ch05_ex03 # If you are given three sticks, you may or may not be able to arrange them in # a triangle. For example, if one of the sticks is 12 inches long and the other # two are one inch long, it is clear that you will not be able to get the short # sticks to meet in the middle. For any three lengths, there is a simple test # to see if it is possible to form a triangle: # If any of the three lengths is greater than the sum of the other two, then # you cannot form a triangle. Otherwise, you can. (If the sum of two lengths # equals the third, they form what is called a "degenerate" triangle.) # (1) Write a function named `is_triangle` that takes three integers as # arguments, and that prints either "Yes" or "No," depending on whether you can # or cannot form a triangle from sticks with the given lengths. # (2) Write a function that prompts the user to input three stick lengths, # converts them to integers, and uses `is_triangle` to check whether sticks # with the given lengths can form a triangle. ############################################################################### # Write your functions below: # Body def is_triangle(x,y,z): """ is_triangle function is given three lengths as arguments and is used to find if a triangle can be formed out of them """ maxi = max(x,y,z) if maxi <= (x+y+z-maxi): return 'Yes' else: return 'No' def check_stick_lengths(): """ The function predicts whether a triangle can be formed based on three inputs from the user """ x = [] i=0 while i<3: while True: try: number = int(input("Enter a side of triangle")) break except ValueError: print("Oops. Please enter a integer value") x.append(number) i = i+1 length_check = is_triangle(x[0],x[1],x[2]) return length_check # Write your functions above: ############################################################################### def main(): """Call your functions within this function. When complete have four function calls in this function for is_triangle (we want to test the edge cases!): is_triangle(1,2,3) is_triangle(1,2,4) is_triangle(1,5,3) is_triangle(6,2,3) and a function call for check_stick_lengths() """ print(is_triangle(1,2,3)) print(is_triangle(1,2,4)) print(is_triangle(1,5,3)) print(is_triangle(6,2,3)) outp = check_stick_lengths() print(outp) if __name__ == "__main__": main()
true
f7ef8a44f33ee7ebbd587d5e1f4db2b171df3ac5
MahaLakshmi0411/Circle
/area.py
316
4.15625
4
pi=3.14 r=float(input("Enter the radius of a circle:")) area=pi*r*r print("The area of the circle is =%.2f"%area) i = input("Input the Filename: ") extns =i.split(".") # repr() function is used to returns a printable representation of a object(optional) print ("The extension of the file is : " + repr(extns[-1]))
true
2230a476c21238983cd77a4760c17a532ee8b1af
hifra01/is_fibonacci
/isFibonacci.py
520
4.375
4
isFibonacci = int(input("Input number = ")) fibNum = 1 container1 = 0 container2 = 0 while fibNum < isFibonacci: container2 = container1 container1 = fibNum fibNum = container1 + container2 if isFibonacci == fibNum: print(isFibonacci,"is a fibonacci number") print("Previous fibonacci number is", container1) container2 = container1 container1 = fibNum fibNum = container1 + container2 print("Next fibonacci number is", fibNum) else: print(isFibonacci,"is not a fibonacci number")
false
7dcf4aebff94e3c2ffce8b9ca6a3c9f5e3884cfa
loghmanb/daily-coding-problem
/facebook_ways_to_detect.py
1,837
4.125
4
''' Ways to Decode Asked in: Facebook, Amazon https://www.interviewbit.com/problems/ways-to-decode/ A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. Input Format: The first and the only argument is a string A. Output Format: Return an integer, representing the number of ways to decode the string. Constraints: 1 <= length(A) <= 1e5 Example : Input 1: A = "8" Output 1: 1 Explanation 1: Given encoded message "8", it could be decoded as only "H" (8). The number of ways decoding "8" is 1. Input 2: A = "12" Output 2: 2 Explanation 2: Given encoded message "12", it could be decoded as "AB" (1, 2) or "L" (12). The number of ways decoding "12" is 2. DP version solved by interviewbit.com ''' def numDecodings_recursive(A): if not A or A[0]=='0': return 0 elif len(A)==1: return 1 elif len(A)==2: return int(A)<=26 and 2 or 1 ans = numDecodings_recursive(A[1:]) if numDecodings_recursive(A[:2]): ans += numDecodings_recursive(A[2:]) return ans # @param A : string # @return an integer def numDecodings(A): d = [0]*(len(A)+1) d[0] = d[1] = 1 for i in range(1,len(A)): no = int(A[i-1]+A[i]) if A[i]=='0' and(no!=10 and no!=20) : return 0 elif no==10 or no==20 : d[i+1] = d[i-1] elif no>10 and no<=26 : d[i+1] = d[i]+d[i-1] else: d[i+1] = d[i] return d[-1] if __name__ == "__main__": data = [ ['1213', 25] ] for d in data: print('input', d[0], 'output#1', numDecodings(d[0]), 'output#2', numDecodings_recursive(d[0]))
true
95378c4ed795ff4814cc9251f59ba6b32cdbdf25
loghmanb/daily-coding-problem
/problem050_microsoft_eval_tree.py
1,046
4.3125
4
''' This problem was asked by Microsoft. Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'. Given the root to such a tree, write a function to evaluate it. For example, given the following tree: * / \ + + / \ / \ 3 2 4 5 You should return 45, as it is (3 + 2) * (4 + 5) ''' import operator ops = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } class TreeNode: def __init__(self, val, left=None, right=None): self.left = left self.right = right self.val = val def eval(btree): if btree.val in ('+', '−', '*', '/'): return ops[btree.val](eval(btree.left), eval(btree.right)) else: return int(btree.val) if __name__ == "__main__": btree = TreeNode('*', TreeNode('+', TreeNode('3'), TreeNode('2')), TreeNode('+', TreeNode('4'), TreeNode('5'))) print('output', eval(btree))
true
06f8fef593620ee02a121393ca57c85423822d93
loghmanb/daily-coding-problem
/problem049_amazon_max_sum_contiguous_sub_arr.py
963
4.21875
4
''' This problem was asked by Amazon. Given an array of numbers, find the maximum sum of any contiguous subarray of the array. For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximum sum would be 0, since we would not take any elements. Do this in O(N) time. ''' def maxSubArr(arr): N = len(arr) max_sum = 0 group_sum = 0 for i in range(N): if group_sum+arr[i]>0: group_sum += arr[i] else: group_sum = 0 if max_sum<group_sum: max_sum = group_sum return max_sum if __name__ == "__main__": data = [ [ [34, -50, 42, 14, -5, 86], 137 ], [ [-5, -1, -8, -9], 0 ] ] for d in data: print('input', d[0], 'output', maxSubArr(d[0]))
true
8657a264fe128c104278cae2f6270143b4e0a872
loghmanb/daily-coding-problem
/facebook_max_sum_contiguous_subarray.py
1,563
4.15625
4
''' Max Sum Contiguous Subarray https://www.interviewbit.com/problems/max-sum-contiguous-subarray/ Asked in: Facebook, Paypal, Yahoo, Microsoft, LinkedIn, Amazon, Goldman Sachs Find the contiguous subarray within an array, A of length N which has the largest sum. Input Format: The first and the only argument contains an integer array, A. Output Format: Return an integer representing the maximum possible sum of the contiguous subarray. Constraints: 1 <= N <= 1e6 -1000 <= A[i] <= 1000 For example: Input 1: A = [1, 2, 3, 4, -10] Output 1: 10 Explanation 1: The subarray [1, 2, 3, 4] has the maximum possible sum of 10. Input 2: A = [-2, 1, -3, 4, -1, 2, 1, -5, 4] Output 2: 6 Explanation 2: The subarray [4,-1,2,1] has the maximum possible sum of 6. ''' import unittest def maxSubArray(A): if not A: return max_subA = A[0] subA = 0 for i,x in enumerate(A): if i==0: subA = x elif subA>0 and (x+subA)>0: subA += x else: subA = x if max_subA<subA: max_subA = subA return max_subA class MAxContSubArrTest(unittest.TestCase): def test_maxSubArray_1(self): result = maxSubArray([1, 2, 3, 4, -10]) expected = 10 self.assertEqual(result, expected) def test_maxSubArray_2(self): result = maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) expected = 6 self.assertEqual(result, expected) if __name__=='__main__': unittest.main()
true
2266a9a8f7f860f613deb4b683e36ad84082fdb0
loghmanb/daily-coding-problem
/google_pascal_triangle.py
1,127
4.25
4
''' https://www.interviewbit.com/problems/pascal-triangle/ Pascal Triangle Asked in: Google, Amazon Given numRows, generate the first numRows of Pascal’s triangle. Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1. Example: Given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] ''' # @param n : integer # @return a list of list of integers def solve(n): A = [[1] for _ in range(n)] for i in range(1, n): for j in range(i, n): val = 0 m = len(A[j-1]) if i<=m-1: val = A[j-1][i] if i<=m: val += A[j-1][i-1] if val==0: val = 1 A[j].append(val) return A if __name__=='__main__': data = [ [5, [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] ] ] for d in data: print('input', d[0], 'output', solve(d[0]))
false
f7bbb5526b0bd0c24148857ddb37b37078dd72f8
loghmanb/daily-coding-problem
/problem065_amazon_print_clockwise.py
1,822
4.3125
4
''' This problem was asked by Amazon. Given a N by M matrix of numbers, print out the matrix in a clockwise spiral. For example, given the following matrix: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] You should print out the following: 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12 ''' LEFT2RIGHT = 1 UP2DOWN = 2 RIGHT2LEFT = 3 DOWN2UP = 4 def print_clock_wise(A): ans = [] N = len(A) M = len(A[0]) start_row, end_row = 0, N-1 start_col, end_col = 0, M-1 direction = LEFT2RIGHT i, j = 0, 0 for _ in range(N*M): ans.append(A[i][j]) if direction == LEFT2RIGHT: if j<end_col: j += 1 else: direction = UP2DOWN start_row += 1 i += 1 elif direction == UP2DOWN: if i<end_row: i += 1 else: direction = RIGHT2LEFT end_col -= 1 j -= 1 elif direction == RIGHT2LEFT: if j>start_col: j -= 1 else: direction = DOWN2UP end_row -= 1 i -= 1 elif direction == DOWN2UP: if i>start_row: i -= 1 else: direction = LEFT2RIGHT start_col += 1 j += 1 return ans if __name__ == "__main__": data = [ [ [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20] ], [1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12] ] ] for d in data: print('input', d[0], print_clock_wise(d[0]))
true
85083b4f2cf7e2f2f6efb458d9e068962bf27824
loghmanb/daily-coding-problem
/problem037_google_power_set.py
763
4.59375
5
''' This problem was asked by Google. The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set. For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}. You may also use a list or array to represent a set. ''' def power_set(arr): if not len(arr): return arr elif len(arr)==1: return [[]] + [[arr[0]]] sub_power_set = power_set(arr[1:]) res = sub_power_set[:] for item in sub_power_set: res.append([arr[0]]+item) return res if __name__ == "__main__": data = [ [ [1, 2, 3] ] ] for d in data: print('input', d[0], 'output', power_set(d[0]))
true
553ee8e48c3c2a5be6ed0bcdc5d8fd05c7a417be
100121358/1CodesAndStuffs
/1CodesAndThings.py
1,132
4.375
4
# Strings # data that falls within " " marks # concatenation # put 2 or more strings together firstName = "Fred" lastName = "Flintstone" print(firstName + " " + lastName) fullName = firstName + " " + lastName print(fullName) # repitition # Repitition operator: * print("Hip"*2 + "Hooray!") def rowYourBoat(): print("Row, "*3 + 'your boat') print("Gently down the stream") print("Merrily, "*4) print("Life is but a dream") print("dream, "*5) rowYourBoat() # Indexing name = "Roy G Biv" firstChar = name[0] print(firstChar) middleIndex = len(name) // 2 print(middleIndex) print(name[middleIndex]) print(name[-1]) print(name[-2]) for i in range(len(name)): print(name[i]) # slicing and Dicing # Slicing Operator: : # slicing lets us make substrings print(name[0:5]) print(name[0:6]) print(name[:5]) print(name[6:9]) print(name[6:]) # Searching inside of Strings print("Biv" in name) print("v" not in name) if "y" in name: print("The letter y is in name") else: print("the letter y in not in name") # Character functions print(ord('5')) print(chr(97+13)) print(str(12458))
true
59fef44ab945a24868c77d7f12e0f369b1372589
ivoree/egg-order
/egg-order.py
1,884
4.25
4
#14/2/21 #Ivory Huang #Egg order program #V1a: create loop in get_orders function to get customers names and egg num #functions def get_orders(names, egg_order): #Collects order information - name, number of eggs – in a loop. Store in 2 lists. #Call read_int function to ensure you have a valid input print ("Collecting Orders") #keep getting orders until f entered while True: name = (input("What is the customer's name? ('F' to finish) ")) #if user enters f, stop getting orders if name.lower() == "f": break #else append name and egg num (order info) to lists names.append(name) egg_order.append(input("How many eggs does {} wish to order? ".format(name))) #return complete order info lists return names, egg_order def show_orders(names, egg_order): """ calculates price for each egg order, and displays order information - name, number of eggs, price """ #MRS DVA MADE CHANGES PRICE_PER_DOZEN = 6.5 print("Showing orders") def show_report(egg_order): """ displays summary - total eggs, number of dozens to be ordered, average eggs per customer. Print "No orders" if no orders received otherwise print "Summary , Total eggs and Dozens required (call get_dozens function) as well as Average" """ def get_dozens (num_eggs): """ returns whole number of dozens required to meet required number of eggs """ def read_pos_int(prompt): """ get positive int """ #main routine #lists to store order information names = [] #customer names egg_order = [] #num of eggs ordered #gets + stores order info until finish names, egg_order = get_orders(names, egg_order) #print order info lists to check correct info stored print(names) print(egg_order) #show_orders(names, egg_order) #show_report(egg_order) #MRS DVA
true
f80812eb080aa10ee3a00ade642c68d46a0d4888
mchen06/python_class_code
/python_projects/bubble_sort.py
735
4.1875
4
list = [3, 4, 1, 1, 8] def bubble_sort(list): # sorts in place length_list = len(list) - 1 comparisons = 0 x = 0 has_swaped = True while has_swaped != False: has_swaped = False y = 0 while y < length_list - x: comparisons = comparisons + 1 if list[y] > list[y + 1]: swap_position(list, y, y + 1) has_swaped = True y = y + 1 x = x + 1 print(f"bubble sort has made {comparisons} comparisons.\n") return list def swap_position(list, pos1, pos2): first_element = list[pos1] second_element = list[pos2] list[pos2] = first_element list[pos1] = second_element print(bubble_sort(list))
true
5a959eada00b487a4bc1d5037d1a2dbd90da3b43
l200170083/prak_ASD_C
/Modul_8(2)_C/modul8(2).py
1,874
4.15625
4
print ("================NOMOR1=====================") class Queue(): def __init__(self): self.qlist = [] def is_empty(self): return len(self) == 0 def __len__(self): return len(self.qlist) def enqueue(self, data): self.qlist.append(data) def dequeue(self): assert not self.is_empty(), "Antrian sedang kosong." return self.qlist.pop(0) def get_front_most(self): assert not self.is_empty(), "Antiran sedang kosong." return self.qlist[0] def get_rear_most(self): assert not self.is_empty(), "Antrian sedang kosong." return self.qlist[-1] Q = Queue() Q.enqueue(28) Q.enqueue(19) Q.enqueue(45) Q.enqueue(13) print (Q.dequeue()) print (Q.dequeue()) print (Q.get_front_most()) print (Q.get_rear_most()) print ("=========================NOMOR2===================") class PriorityQueue(): def __init__(self): self.qlist = [] def __len__(self): return len(self.qlist) def is_empty(self): return len (self) == 0 def enqueue(self, data, priority): entry = _PriorityQEntry(data, priority) self.qlist.append(entry) def dequeue(self): A = [] for i in self.qlist: A.append(i) s = 0 for i in range(1, len(self.qlist)): if A[i].priority < A[s].priority: s = i hasil = self.qlist.pop(s) return hasil.item class _PriorityQEntry(): def __init__(self, data, priority): self.item = data self.priority = priority S = PriorityQueue() S.enqueue("Jeruk", 4) S.enqueue("Tomat", 2) S.enqueue("Mangga", 0) S.enqueue("Duku", 5) S.enqueue("Pepaya", 2) print (S.dequeue()) print (S.dequeue()) print (S.dequeue()) print (S.dequeue()) print (S.dequeue())
false
f258d3be7157102100bc3d285a9465c4814bb969
erobic/neural_networks
/src/simple_network.py
2,875
4.15625
4
import numpy as np ''' A simple neural network with single hidden layer ''' # Even no. of 1s = 1 training_data = np.array([ [[0, 0, 1], 0], [[0, 1, 1], 1], [[1, 0, 1], 1], [[1, 1, 1], 0] ]) def sigmoid(z): return 1.0/(1.0+np.exp(-z)) def sigmoid_deriv(z): return z*(1-z) def feedforward(weight, input_activation): z = np.dot(weight, input_activation) output_activation = sigmoid(z) return {"z":z, "output_activation":output_activation} def output_error(expected_output, network_output): return expected_output - network_output # # def delta(activation, error): # return error * sigmoid_deriv(activation) # # # def error(delta, weight): # return np.dot(np.transpose(weight), delta) # Define weights from layer 0 to layer 1 num_input = 3 num_hidden = 5 num_output = 1 # The weights are from layer 0 to 1, but we reverse the indices i.e. use 10 instead of 01 because of convention and ease in matrix operations weights10 = np.random.randn(num_hidden, num_input) weights21 = np.random.randn(num_output, num_hidden) learning_rate = 10 for training_loop in xrange(1, 100000): td_size = len(training_data) for td_index in xrange(0, td_size): ''' PERFORM FEED FORWARD ''' # From layer 0 (input layer) to layer 1 # First column of training_data = input l0 = np.array([training_data[td_index, 0]]).T # 2X1 l1_ff = feedforward(weights10, l0) l1 = l1_ff["output_activation"] # num_hidden X 1 # From layer 1 to layer 2 (output layer) l2_ff = feedforward(weights21, l1) l2 = l2_ff["output_activation"] # num_output X 1 ''' CALCULATE OUTPUT ERROR ''' expected_output = training_data[td_index, 1] # First column of training_data = output l2_error = output_error(expected_output, l2) # num_output X 1 if training_loop % 10000 == 0: print "Error = %f" %l2_error[0] ''' PERFORM BACK PROPAGATION ''' # First, let us propagate output layer's error to adjust weights between hidden layer and output layer l2_delta = l2_error * sigmoid_deriv(l2) # 1 X 1 weights21 += learning_rate*(l1.dot(l2_delta.T)).T # num_output X num_hidden # Next propagate error from first hidden layer to adjust the weights between input layer and hidden layer l1_error = l2_delta.dot(weights21) # 1X5 l1_delta = l1_error.T*sigmoid_deriv(l1) # 5X1 weights10 += learning_rate*(l0.dot(l1_delta.T)).T # num_hidden X num_input def output(input): l1 = feedforward(weights10, input)["output_activation"] l2 = feedforward(weights21, l1)["output_activation"] return l2 print output([0, 0, 1]) # Expect 0 print output([0, 1, 1]) # Expect 1 print output([1, 0, 1]) # Expect 1 print output([1, 1, 1]) # Expect 0
true
2044dc4a1fd7d4d5481887b73813340e3913b1f8
sabinbhattaraii/python_assignment_2
/q12.py
379
4.28125
4
''' Create a function, is_palindrome, to determine if a supplied word is the same if the letters are reversed ''' def is_palindrome(string): string = string.lower() if list(string) == list(reversed(string)): return 'The word is palindrome' else: return 'The word is not palindrome' string = str(input('Enter a word :')) print(is_palindrome(string))
true
3131eb96e58ff19f85cdd910f3006dc398258192
sabinbhattaraii/python_assignment_2
/q15.py
831
4.28125
4
''' Imagine you are designing a banking application. What would a customer look like? What attributes would she have? What methods would she have? ''' class Bank(): def __init__(self): self.amount = int(input('Enter the amount of money you have')) def deposite_money(self,money): self.amount = self.amount + money return f"You have deposited {money} amount" def withdraw_money(self,withdraw): self.amount = self.amount - withdraw return f"You have withdrawn {withdraw} amount" def total_money(self): return f'Your total balance is {self.amount}' customer = Bank() print(customer.deposite_money(int(input('Enter sum of money you want to deposite:')))) print(customer.withdraw_money(int(input('Enter amount you want to withdraw:')))) print(customer.total_money())
true
e70dad15bd76770a61a3fa89ee41deb499ce3ac9
tejasgondaliya5/basic-paython
/basicpython/classandobject.py
1,168
4.1875
4
class Student: # Student is class but "S" is capital is good practice but not compulsory pass raj = Student() # harry and larry is object ravi = Student() raj.std = 12 # harry.std and harry.name is instance variable raj.name = "raj" ravi.std = 10 print(raj, ravi) print(raj.name, ravi.std) class Employe: holiday = 9 pass harry = Employe() tejas = Employe() harry.name = "harry" harry.salary = 40000 harry.role = "data science" tejas.name = "tejas" tejas.salary = 60000 tejas.role = "data analytics" print(harry.name, tejas.name, harry.salary, tejas.salary) print(Employe.holiday) print(harry.holiday) print(tejas.holiday) print() print(Employe.__dict__) print() print(tejas.__dict__) print(harry.__dict__) print() Employe.holiday = 7 # it is change all employee holiday because employee holiday is not private print(Employe.holiday) print(harry.holiday) print(tejas.holiday) print() tejas.holiday = 8 # it is change only tejas holiday because this is tejas private instance variable print(tejas.holiday) print(Employe.holiday) print(harry.holiday) print() print(Employe.__dict__) print() print(tejas.__dict__) print(harry.__dict__)
false
de09e332925a88e8a5cf342e5584d7470b91adee
guimevn/exerciciosPythonBrasil
/01_estruturaSequencial/ex017.py
1,432
4.25
4
import math """Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00 ou em galões de 3,6 litros, que custam R$ 25,00. Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações: comprar apenas latas de 18 litros; comprar apenas galões de 3,6 litros; misturar latas e galões, de forma que o preço seja o menor. Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias.""" a = int(input('Digite a área do quadrado: (m²) ')) lT = (a / 6) * 1.1 latas = lT / 18 # latas de tintas a serem compradas gal = lT / 3.6 # galões de tintas a serem comprados print('Você terá que comprar {} latas e terá que pagar R${}'.format(math.ceil(latas), math.ceil(latas) * 80)) print('Você terá que comprar {} galões e terá que pagar R${}'.format(math.ceil(gal), math.ceil(gal) * 25)) mistLatas = int(lT / 18) mistGal = int((lT - (mistLatas * 18)) / 3.6) if lT - (mistLatas * 18) % 3.6 != 0: mistGal += 1 print('Você terá que comprar {} latas, {} galões e terá que pagar R${:.2f}'.format(mistLatas, mistGal, (mistLatas * 80) + (mistGal * 25)))
false
063377c9c9f5351c6543df8c413b961462cb962d
pattypmx/def
/22.文件的相关操作.py
730
4.1875
4
# 有些时候,需要对文件进行重命名、删除等一些操作,python的os模块中都有这么功能 # 重命名 import os # os.rename("wenzi1.txt", "wenzi11.txt") # 创建文件 # p = open("haha.txt", "w") # 删除文件 # os.remove("word3.txt") # ---------------------------- #创建文件夹 # os.mkdir("helloword") # os.mkdir("helloword.txt") # 删除文件夹 # os.rmdir("helloword.txt") # ---------------------------- # 获取当前目录 获取的是绝对路径,可以看到盘符 # ret = os.getcwd() # print(ret) # 改变默认目录 # ../ 上一级目录;./或者../都是相对路径 # os.chdir("../") # ret1 = os.getcwd() # print(ret1) # 获取目录列表 ret2 = os.listdir() print(ret2)
false
9c2cda88ea275dc3a96287da6978c46346a8ec77
IvanShamrikov/COURSES---INTRO-PYTHON
/Lesson1 - INTRO/Homework_Lesson1.py
1,595
4.25
4
#1. Дано два числа (a=10, b=30). Вывести на экран результат математического взаимодействия (+, -, *, / ) этих чисел. print('Task 1') print('----------------') a = 10 b = 30 print("a + b =", a + b) print("a - b =", a - b) print("a * b =", a * b) print("a / b =", a / b) print("\n") #2. Создать переменную и записать в нее результат логического взаимодействия (<, > , ==, !=) этих чисел После этого ывести на экран значение полученой переменной. print('Task 2') print('----------------') c = a < b print("a < b =", c) c = a > b print("a > b =", c) c = a == b print("a == b =", c) c = a != b print("a != b =", c) print("\n") #3. Создать переменную - результат конкатенации (сложения) строк str1="Hello " и str2="world". Вывести на ее экран. print('Task 3') print('----------------') str1 = "Hello " str2 = "world" str_res = str1 + str2 print(str_res, '\n') #4. Используя переменные a и b сформировать строку "First variable is [тут знаение переменной a], second variable is [тут знаение переменной b]. Their sum is [тут их сумма]." print('Task 4') print('----------------') string = "First variable is " + str(a) + ", second variable is " + str(b) + ". Their sum is " + str(a + b) + "." print(string)
false
e4fded88028d58bc84e851f7f7beb73bf77a1c16
George-Went/Gwent-Library-Python
/Basic_Programs/Lists.py
360
4.40625
4
myList = [] myList.append(1) myList.append(2) myList.append(3) print(myList[0]) print(myList[1]) print(myList[2]) for x in myList: print(x) numbers = [1 ,2, 3] strings = ["Hello", "World"] names = ["John", "Eric", "Jessica"] third_name = names[2] print(numbers) print(strings[0] + " " + strings[1]) print("the third name on the list is: " + third_name)
true
66722612187059f5314c74126251ed099d795a69
vedantnanda/Python-and-ML
/18_5_18/LA12.py
264
4.15625
4
#LA12 Palindrome Check #Accept a string and check if string is palindrome or not s1 = str(input("Enter String: ")) if len(s1)==0: print("Empty String") else: s2 = s1[::-1] if s1==s2: print("Palindrome") else: print("Not Palindrome")
false
84a7cc036543f618ddead85d792824b5df491722
vedantnanda/Python-and-ML
/17_5_18/HA11.py
840
4.125
4
#Calculator using function #HA11 def addit(a,b): return(a+b) def subit(a,b): return(a-b) def mulit(a,b): return(a*b) def divit(a,b): return(a/b) print("Calculator using function") n1 = float(input("Enter first number: ")) n2 = float(input("Enter second number: ")) ch = str(input("Enter choice(A:Addition,S:Substraction,M:Multiplication,D:Division): ")) if n2 == 0: print("Division by zero not possible") else: if ch == 'A' or ch == 'a': print("The Addition of {0} and {1} is {2}".format(n1,n2,addit(n1,n2))) elif ch == 'S' or ch == 's': print("The Substraction of {0} and {1} is {2}".format(n1,n2,subit(n1,n2))) elif ch == 'M' or ch == 'm': print("The Multiplication of {0} and {1} is {2}".format(n1,n2,mulit(n1,n2))) elif ch == 'D' or ch == 'd': print("The Division of {0} and {1} is {2}".format(n1,n2,divit(n1,n2)))
false
29aa9354e288bc5a8fda963839123c01f0164083
Ge0dude/AlgorithmsCoursera
/Course1/week5/coinChanging.py
912
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 19 17:41:48 2017 @author: brendontucker using this as an example to better understand dynamic programming lets do some debugging with print statements """ coinValueList = [1, 5, 21, 25] change = 63 minCoins = [0 for x in range(change + 1)] for cents in range(change+1): print('START LOOP') print('_________') print('cents is:', cents) coinCount = cents print('so is coinCount:', coinCount) for j in [c for c in coinValueList if c <= cents]: print('j is:', j) if minCoins[cents-j] + 1 < coinCount: coinCount = minCoins[cents-j] + 1 print('coinCount is now:', coinCount) minCoins[cents] = coinCount print('the answer is:', coinCount) #need to understand this line better #[c for c in coinValueList if c <= cents] '''creates a list of every coin <= cents'''
true
4ad1559ebb5ec35f73ece414489f4154323cb2eb
LookerKy/Python-Advanced
/src/Section02-01.py
2,454
4.21875
4
# Section02-01 # Python Advanced # 데이터 모델 # 참조 : https://docs.python.org/3/reference/datamodel.html # Namedtuple 실습 # 파이썬의 중요한 핵심 프레임워크(data type) -> 시퀀스(Sequence) 반복(Iterator) 함수(Function) 클래스(Class) # 객체 -> 파이썬의 데이터를 추상화 # 모든 객체 -> id 와 type 을 가지고있음 # 일급 객체 # 일반적인 튜플 사용 from math import sqrt from collections import namedtuple pt1 = (1.0, 5.0) pt2 = (2.5, 1.5) line_len1 = sqrt((pt2[0] - pt1[0]) ** 2 + (pt2[1] - pt1[1]) ** 2) print('Ex 1-1', line_len1) # namedtuple 사용 Point = namedtuple('Point', 'x y') pt1 = Point(1.0, 5.0) pt2 = Point(2.5, 1.5) line_len2 = sqrt((pt2.x - pt1.x) ** 2 + (pt2.y - pt1.y) ** 2) print('Ex 1-2', line_len2) # 네임드 튜플 선언 방법 Point1 = namedtuple('Point', ['x', 'y']) Point2 = namedtuple('Point', 'x, y') Point3 = namedtuple('Point', 'x y') Point4 = namedtuple('Point', 'x y x class', rename=True) # 같은 변수나 예약어가 들어왔을 때 임의로 변수네이밍을 해줌 print('EX2-1', Point1, Point2, Point3, Point4) temp_dict = {'x': 75, 'y': 35} # 객체 생성 p1 = Point1(x=10, y=35) p2 = Point2(20, 40) p3 = Point3(45, y=20) p4 = Point4(10, 20, 30, 40) p5 = Point3(**temp_dict) # Dict to Unpacking print('EX2-2 -', p1, p2, p3, p4, p5) # 사용 print('EX3-1', p1[0] + p2[1]) print('EX3-1', p1.x + p2.y) # 클래스의 변수 접근 방식 # Unpacking x, y = p3 print('EX3-3', x + y) # Rename 테스트 print('Ex3-4', p4) # namedtuple method temp = [52, 38] # _make() : 새로운 객체 생성 p4 = Point1._make(temp) print('Ex4-1 -', p4) # _fields : 필드 네임 확인 print('Ex4-2 - ', p1._fields, p2._fields, p3._fields) # _asdict() : OrderedDict 반환 print('Ex4-3 -', p1._asdict(), p4._asdict()) # _replace() : 수정된 새로운 객체 반환 print('Ex4-4', p2._replace(y=100)) # 실 사용 실습 # 학생 전체 그룹생성 # 반20명 , 4개의 반 -> (A,B,C,D) 번호 Classes = namedtuple('Classes', ['rank', 'number']) # 그룹 리스트 선언 numbers = [str(n) for n in range(1, 21)] ranks = 'A B C D'.split() # List Comprehension students = [Classes(rank, number) for rank in ranks for number in numbers] print(len(students)) print(students[4].rank) students2 = [Classes(rank, number) for rank in 'A B C D'.split() for number in [str(n) for n in range(1, 21)]] # 출력 for s in students: print()
false
13350ab70b8a45e5fb64723aff3020cbc612e476
zzh730/LeetCode
/String/Multiply Strings.py
673
4.1875
4
__author__ = 'drzzh' ''' python占便宜的一种方式 ''' class Solution: # @param {string} num1 # @param {string} num2 # @return {string} def multiply(self, num1, num2): return str(int(num1) * int(num2)) ''' 面试碰到应该用如下方法:小学乘法的实现 Three Functions: 1.multiplyChar(string, char, numOfZeros):return the product of string1 and a char in string2, add zeros accord- ing to the position of the char in string2. 2.addTwoNumbers(lastResult, newResult): accumulate the products of string1 * each char in string2. 3.main function: return result. '''
false
5cea1c6236e8cb3e55abac4ad64c38e12a8ce066
zzh730/LeetCode
/Tree/preorder.py
1,358
4.125
4
__author__ = 'drzzh' """ 都是非递归写法: 1。backtracking 如果左节点存在,入栈,访问,不存在,出栈,访问右节点,注意终止条件,stack空了要停止循环 2. 根节点出栈,然后如果有右节点就入栈,如果有左节点就入栈 3. 一定注意在else后检查stack是否为空 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None tree = TreeNode(1) tree.left = TreeNode(2) tree.right = TreeNode(3) tree.left.right = TreeNode(4) tree.left.right.left = TreeNode(7) tree.left.right.right = TreeNode(8) tree.right.left = TreeNode(5) tree.right.right = TreeNode(6) tree.right.left.left = TreeNode(9) tree.right.left.right = TreeNode(10) stack = [] def preorder(root): if root == None: return 0 p = root stack = [] while (p != None or stack != None): if p: print(p.val) stack.append(p) p = p.left else: if not stack: break p = stack.pop().right def preorder1(root): if root == None: return 0 p = root stack = [root] while (stack): p = stack.pop() print(p.val) if p.right: stack.append(p.right) if p.left: stack.append(p.left)
false
b9c5a6d08e004c566ca2e69051c4a9a8b39dd6df
fionacahill/greenpepper
/PBJ.py
993
4.125
4
bread = 7 jelly = 4 pb = 4 if bread>=2 and jelly>=1 and pb>=1: print "You can have lunch today" else: print "No sandwich for you" if bread>=2 and jelly>=1 and pb>=1: sandwich=bread/2 if pb<sandwich: sandwich = pb if jelly<sandwich: sandwich = jelly print sandwich print "I can make {0} sandwiches".format(sandwich) bread2 = bread - (2*sandwich) pb2 = pb - sandwich jelly2 = jelly - sandwich print "I have {0} slices of bread, {1} servings of PB, and {2} servings of jam".format(bread2, pb2, jelly2) if bread2>=0 and pb2>=0 and jelly >=0: of=bread if pb2<of: of = pb2 if jelly2<of: of = jelly2 if of==0: print "No open-faced sandwiches for you." else: print "You can have {0} open-faced sandwiches".format(of) if jelly==0: print "You need more jam." if pb==0: print "You need more peanut butter." if bread==0: print "You need more bread." else: print "You're all set." if bread>=0 and pb>=0 and jelly==0: print "You can make a peanut butter sandwich."
true
f63945f0d5bd465b57d4c5c40329d43adcf558b5
tacolim/Python_Algorithms
/palindrome.py
1,547
4.28125
4
""" Return true if the given string is a palindrome. Otherwise, return false. A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing. Note You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes. We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others. We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2". """ def palindrome(x): low = x.lower() low_o = low.replace(" ", "") low_ol = low_o.translate(None, ",.:;?!'\"'@#$%^&*()-_=+/><\\") back_low_ol = low_ol[::-1] if low_ol == back_low_ol: return True else: return False print "racecar\n", palindrome("racecar"), "\n\n" print "RaceCar\n", palindrome("RaceCar"), "\n\n" print "race CAR\n", palindrome("race CAR"), "\n\n" print "2A3*3a2\n", palindrome("2A3*3a2"), "\n\n" print "2A3 3a2\n", palindrome("2A3 3a2"), "\n\n" print "2_A3*3#A2\n", palindrome("2_A3*3#A2"), "\n\n" print "Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked.\n", palindrome("Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked."), "\n\n" print "A man, a plan, a canal: Panama.\n", palindrome("A man, a plan, a canal: Panama."), "\n\n" print "Summit & summit & summit\n", palindrome("Summit & summit & summit"), "\n\n" print "kayak\n", palindrome("kayak"), "\n\n"
true
5c2a152bbcd04b82732e987e1dd9a57ce1115283
Dagmoores/PythonStudies
/Projeto_Integrador_Estudos/problema_pratico3-8.py
342
4.125
4
# Retirado do livro Introdução à Computação em Python - Um Foco no Desenolvimento de Aplicações - PERKOVIC, Ljubomir # Defina, diretamente no shell interativo, a função média(), que aceita dois números como entrada e retorna a média dos números. Um exemplo de uso é: >>> average(2, 3.5) 2.75 def f(x, y): return (x + y) / 2
false
583b23baececfe4afddd9f1c1706e3580772a49b
Dagmoores/PythonStudies
/Projeto_Integrador_Estudos/problema_pratico3-2.py
1,353
4.125
4
#Retirado do livro Introdução à Computação em Python - Um Foco no Desenolvimento de Aplicações - PERKOVIC, Ljubomir #Traduza estas instruções condicionais em instruções if do Python: #(a)Se idade é maior que 62, exiba 'Você pode obter benefícios de pensão'. #(b)Se o nome está na lista ['Musial', 'Aaraon', 'Williams', 'Gehrig', 'Ruth'], exiba 'Um dos 5 maiores jogadores de beisebol de todos os tempos!'. #(c)Se golpes é maior que 10 e defesas é 0, exiba 'Você está morto…'. #(d)Se pelo menos uma das variáveis booleanas norte, sul, leste e oeste for True, exiba 'Posso escapar.'. #Resolução (a): idade = eval(input('Qual é sua idade? ')) if idade > 62: print('Você pode obter benefícios de pensão') #Resolução (b) nome = input('Qual é o nome? ') lista_nomes = ['Musial', 'Aaraon', 'Williams', 'Gehrig', 'Ruth'] if nome in lista_nomes: print('Um dos 5 maiores jogadores de beisebol de todos os tempos!') #Resolução (c) golpes = eval(input('Quantos golpes? ')) defesas = eval(input('Quantas defesas? ')) if golpes > 10 and defesas == 0: print('Você está morto…') #Resolução (d) norte = eval(input('norte: ')) sul = eval(input('sul: ')) leste = eval(input('leste: ')) oeste = eval(input('oeste: ')) if norte == True or sul == True or leste == True or oeste == True: print('Posso escapar.')
false
c2a89bfcd011d2a3931e6d1522183f75ac191103
angel-robinson/validadores-en-python
/#converssores_booleano.py
864
4.125
4
#conversores tipo booleano #convertir la cadena "3" a booleano x="3" a=bool(x) print(a,type(a)) #convertir la cadena "angel" a booleano x="angel" a=bool(x) print(a,type(a)) #convertir la cadena "38" a booleano x="38" a=bool(x) print(a,type(a)) #convertir el enetero 8 a booleano x=8 a=bool(x) print(a,type(a)) #convertir real 0.0 a booleano x=0.0 a=bool(x) print(a,type(a)) #convertir el real 10.5 a booleano x=10.5 a=bool(x) print(a,type(a)) #convertir el booleano 1>=5 a booleano x=(1>=5) a=bool(x) print(a,type(a)) #convertir el booleano 10<=10 a booleano x=(10>=10) a=bool(x) print(a,type(a)) #convertir la cadena "0.5" a booleano x="0.5" a=bool(x) print(a,type(a)) #convertir 20!=20 a booleano x=(20!=20) a=bool(x) print(a,type(a)) #ejemplo de error #convertir la cadena casa a booleano x=casa a=bool(x) print(a)
false
5c915b4c2b6055fcd9c1911611a4f57f9612bb40
ramprasadgk/PhilosophyOfPython
/BubbleSort.py
577
4.25
4
print ('begin') def bubblesort(U): swapped = False for i in range(len(U)): swapped = False for j in range(len(U)-1-i): if(U[j] > U[j+1]): U[j],U[j+1]= U[j+1],U[j] print ("swapped ",U[j], 'and',U[j+1]) swapped = True print (U) else: print ("No need to swap ",U[j], 'and',U[j+1]) print(U) if not swapped: return if __name__ == '__main__': unsorted = [3,-3,-1] bubblesort(unsorted) print('done')
false
3153f620619967c90783491238477c39e681af7b
TMFrancis/Lecture4
/main.py
427
4.15625
4
# Lecture 4 # September 1, 2021 # Turtle library import turtle turtle.color("black", "red") turtle.begin_fill() #start process turtle.circle(75) # turtle.end_fill() def draw_square(t, sz): for i in range(6): t.forward(sz) t.left(60) wn = turtle.Screen() wn.bgcolor("lightgreen") wn.title("Alex meets a function") alex = turtle.Turtle() draw_square(alex, 100) wn.mainloop()
false
adafb62d7438f44a424023a65aad35dba4462934
KanchanRana/Information_Security
/IS_A_1_Additive_cipher.py
2,452
4.625
5
'''Ques 1. Write a program that can encrypt and decrypt using the Additive Cipher.''' #index of character is its value alpha_list=['A','B','C','D','E','F','G','H', 'I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z'] ''' encrypt_the_plain_text() is a function which takes two arguments - plain_text and a key, and returns the cipher_text ''' def encrypt_the_plain_text(plain_text,key): cipher_text='' #iterate the plain_text for plain_text_alphabet in plain_text: #shifting each character of plain_text cipher_alphabet=(alpha_list.index(plain_text_alphabet)+key)%26 #adding the shifted character to the output cipher_text+=alpha_list[cipher_alphabet] #returning the encrypted text return cipher_text ''' encrypt_the_cipher_text() is a function which takes two arguments - cipher_text and a key, and returns the plain_text ''' def decrypt_the_cipher_text(cipher_text,key): plain_text='' #iterate the cipher_text for cipher_text_alphabet in cipher_text: #shifting back each character of cipher_text plain_alphabet=(alpha_list.index(cipher_text_alphabet)-key)%26 plain_text+=alpha_list[plain_alphabet] #returning the decrypted text return plain_text def main(): #counter to run the input loop choice='Y' #Menu driven for input and output while(choice=='Y'): print('''Additive Cipher What do you want to do : Press 1.Encryption 2.Decryption ''' ) option=int(input("Enter your choice: ")) if option==1: #for encryption taking plain_text and key as input #and calling the encrypt function plain_text=input("Enter the plain text : ").upper() key=int(input("Enter the key : ")) print("Encrypted message : ",encrypt_the_plain_text(plain_text,key)) elif option==2: #for decryption taking cipher_text and key as input #and calling the decrypt function cipher_text=input("Enter the cipher text : ").upper() key=int(input("Enter the key : ")) print("Encrypted message : ",decrypt_the_cipher_text(cipher_text,key)) else: print("Wrong Choice : ") choice=input("Want to continue (Enter 'Y' for yes ) :") main()
true
08d70a6c3d6f164d0302e90742b33317a69110cf
attapun-an/topscore-project
/simple.py
1,026
4.40625
4
""" OpenTopScore(fileName) This function creates a new, empty, top score text file if it doesn't exist, otherwise it opens the text file filename (string) and returns a list of the contents AddScore(name, score, filename) This procedure takes 3 parameters, the name (string), score (integer) and the top score filename (string). It should append this information to the file. WriteTopScores(topScores, filename) This function writes a list to the text file filename (string) as the top score table DisplayTopScore(filename) Displays the top scores in the filename (string) """ def open_top_score(file_name): f = open(file_name, "r") return f def add_score(name, score, file_name): f = open(file_name, "a") f.write(name + "\n") f.write(score) def write_top_scores(top_scores, file_name): f = open(file_name, "w") f.write(top_scores) def display_top_scores(file_name): f = open(file_name, "r") top_scores = f.read() print(top_scores) display_top_scores("HSTF.txt")
true
635809a3d18a8b4b7e3ac6fd46880b0a5a538a3a
karafede/pyhon_stuff
/app.py
1,435
4.28125
4
print("Hello World") print("/___|") print(" /|") print(" / |") print(" / |") # create variable character_name = "George" character_age = "50" is_male = False print("There was once a guy named " + character_name + ",") print("he was" + character_age + " years old,") character_name = "Tom" print("he liked the name " + character_name + ",") print("but he didn't like being " + character_age + ".") phrase = "Giraffe\nAcademy" phrase = "Giraffe Academy" print(phrase + " is cool") # functions with strings print(phrase.lower() + "\n") print(phrase.upper() + "\n") print(phrase.isupper()) print(phrase.upper().isupper()) print(len(phrase)) print(phrase[0]) print(phrase.index("G")) # find where the word Adademy starts..position 8 print(phrase.index("Academy")) # print(phrase.index("z")) print(phrase.replace("Giraffe", "Elephant")) # functions with numbers print(-2.567) print(3 * 4 + 7) # give you what is left from the division print(10%3) my_num = -5 print(my_num) print(str(my_num) + " my favourite number") print(abs(my_num)) print(pow(3, 2)) # 3^2 print(max(4, 2)) print(round(3.2)) # import all math functions from math import * print(floor(3.6)) print(ceil(3.6)) print(sqrt(3)) ########################################## name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + "!, you are " + age)
false
bb3fb7bf84f11dcb698b7928c1cc3536c65b879a
skyswordLi/Python-Core-Program
/Chapter2/sumAndAverage.py
904
4.28125
4
print "This script computes some values' summary and average." print "------------------------------------------" print "-------------Give your choice-------------" print "---------1 means compute summary----------" print "---------2 means compute average----------" print "--------------X means quit----------------" while True: print "Enter number of values:" NUM = int(raw_input("NUM = ")) array = [] print "Enter the values:" for i in range(NUM): value = float(raw_input("value = ")) array.append(value) print "Please enter your choice:" choice = raw_input("choice = ") if choice == '1': print "You choose compute summary, and the result is %f" % sum(array) elif choice == '2': print "You choose compute average, and the result is %f" % (sum(array) / float(NUM)) else: print "You choose quit! Bye!" break;
true
95d854d4e9a5ef623d766e207875243b07bdaba3
skyswordLi/Python-Core-Program
/Chapter6/change.py
599
4.1875
4
def upper_lower_change(my_str): str_len = len(my_str) output_str = '' for i in range(str_len): if my_str[i].isupper(): output_str += my_str[i].lower() elif my_str[i].islower(): output_str += my_str[i].upper() else: output_str += my_str[i] return output_str if __name__ == "__main__": print "Please input a string to change:" inputStr = raw_input('inputStr = ') print "Before changed, the string is %s" % inputStr outStr = upper_lower_change(inputStr) print "After changed, the string is %s" % outStr
false
1288376bdc72c3d0b1e8a8556f682b3a373cabbb
skyswordLi/Python-Core-Program
/Chapter2/sumOfArrayAndPuple.py
896
4.125
4
array = [1, 2, 3, 4, 5] fibonacci = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] print "-" * 40 print "Get summaries by calling sum function:" print sum(array) print sum(fibonacci) print "-" * 40 arrayLen = len(array) fibonacciLen = len(fibonacci) print "-" * 40 print "Ger summaries by using while loop:" sumArray = 0 sumFibonacci = 0 i = 0 while i < arrayLen: sumArray += array[i] i += 1 i = 0 while i < fibonacciLen: sumFibonacci += fibonacci[i] i += 1 print "Summaries of array and puple using while loop are %d, %d" % (sumArray, sumFibonacci) print "-" * 40 print "-" * 40 print "Ger summaries by using for loop:" sumArray = 0 sumFibonacci = 0 for i in range(arrayLen): sumArray += array[i] i += 1 for i in range(fibonacciLen): sumFibonacci += fibonacci[i] i += 1 print "Summaries of array and puple using for loop are %d, %d" % (sumArray, sumFibonacci)
false
73499d8e0ded33f336ac4d610a15e367c08013ea
skyswordLi/Python-Core-Program
/Chapter5/score.py
441
4.1875
4
def grade(score): assert 0 <= score <= 100, 'Wrong input score!' if 90 <= score <= 100: return 'A' elif 80 <= score < 90: return 'B' elif 70 <= score < 80: return 'C' elif 60 <= score < 70: return 'D' elif 0 <= score < 60: return 'F' print "Please input your score to get the grade:" your_score = float(raw_input('score = ')) print 'Your grade will be %s' % grade(your_score)
true
d51a73e4e33d8fbd6e07e79fff740e03f26f2146
Automedon/Codewars
/8-kyu/Return Two Highest Values in List.py
621
4.34375
4
""" Description: In this kata, your job is to return the two highest values in a list, this doesn't include duplicates. When given an empty list, you should also return an empty list, no strings will be passed into the list. The return should also be ordered from highest to lowest. If the argument passed isn't a list, you should return false. Examples: two_highest([4, 10, 10, 9]) should return [10, 9] two_highest([]) should return [] two_highest("test") should return False """ def two_highest(arg1): if type(arg1) is list: return sorted(list(set(arg1)))[-2::][::-1] else: return False
true
9faf9f52ef81370438c9192d23813b51c709659f
Tanja75/Python-tasks-solution
/String_reverse.py
224
4.40625
4
#Function that reverses the string: def string_reverse(str1): rstr1="" index=len(str1) while index>0: rstr1 += str1[index -1] index=index-1 return rstr1 print(string_reverse("python"))
true
cd50c5bd3ec12122fceb23b80923b4c70e2ce725
zangkhun/leepy
/search/LC22.py
1,734
4.125
4
""" 22. 括号生成 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3,生成结果为: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] """ # "括号约束"组合搜索模板 # 这里每个位置都有两种选择进行组合, 但同时又有全局约束. # 注意与 lc784 的局部位置多可能性的"排列搜索"问题比较 # 剪枝条件的写法上, 第二种方法更为清晰 class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ ans = [] self.dfs(n, n, "", ans) return ans def dfs(self, left, right, path, ans): if left + right == 0: ans.append(path) return if right < left: return # 这是剩余数量, right<left说明此时path中左右括号数量相等 if left > 0: path += "(" self.dfs(left-1, right, path, ans) path = path[:-1] if right > 0: path += ")" self.dfs(left, right-1, path, ans) path = path[:-1] def generateParenthesis_2(self, n): """ :type n: int :rtype: List[str] """ res = [] self.dfs_2("", n, 0, 0, res) return res def dfs_2(self, S, n, left, right, res): if len(S) == 2 * n: res.append(S) return if left < n: self.dfs_2(S + "(", n, left + 1, right, res) if right < left: # 组成合法括号的充分条件 self.dfs_2(S + ")", n, left, right + 1, res)
false
d1b554548e9b76612436f55f7b86f41aa9af4f25
dmlogv/hr-mgfn-automation
/gppl/py/e_sorter.py
2,160
4.3125
4
#!/usr/bin/env python """Сортировка людей""" class Meat: def __init__(self, name, age): """Данные людей Args: name (str): Имя age (int): Возраст """ if not isinstance(name, str) or len == 0: raise ValueError('name must be non-empty str') if not isinstance(age, int) or age < 0: raise ValueError('age must be non-negative int') self.name = name self.age = age def __repr__(self): return f'<{self.name}, {self.age}>' class MeatSorter: def __init__(self): """Контейнер для хранения и сортировки личностей""" self.storage = [] def __iadd__(self, other): self.storage.append(other) return self def __str__(self): return '[' + '\n '.join(map(str, self.storage)) + ']' def by_name(self, desc=False): """Сортировка по имени Args: desc (bool): в убывающем порядке Returns: list """ return sorted(self.storage, key=lambda i: i.name, reverse=desc) def by_age(self, desc=True): """Сортировка по возрасту Args: desc (bool): в убывающем порядке Returns: list """ return sorted(self.storage, key=lambda i: i.age, reverse=desc) if __name__ == '__main__': import random # Случайный возраст rnd = lambda: random.randint(0, 100) storage = MeatSorter() # Наполняем псевдолюдьми storage += Meat('Jonelle Lytch', rnd()) storage += Meat('Glenda Cabana', rnd()) storage += Meat('Alene Coomer', rnd()) storage += Meat('Isidro Trexler', rnd()) storage += Meat('Palmer Saffold', rnd()) storage += Meat('Lynne Mayse', rnd()) storage += Meat('Sandee Callihan', rnd()) storage += Meat('Theron Stroup', rnd()) storage += Meat('Tracy Criger', rnd()) storage += Meat('Ardath Chacko', rnd()) print(storage) print('By name:', storage.by_name()) print('By age:', storage.by_age())
false
cbea9f3520e67d6b65d16f8b675f8e0268172b10
legacy72/geek_brains_homeworks_examples_940
/lesson_2/task_2.py
662
4.1875
4
""" Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ l = input('Введите список значений через пробел: ').split() for i in range(0, len(l) - 1, 2): l[i], l[i+1] = l[i+1], l[i] print(l)
false
a9bf59670061c279655b0346b2cbfed251ec4934
legacy72/geek_brains_homeworks_examples_940
/lesson_3/task_3.py
316
4.21875
4
""" Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов. """ def my_func(a, b, c): return a + b + c - min([a, b, c]) print(my_func(1, 2, 3))
false
7bbae2705bd5b373eebfe106989fa73114d72580
legacy72/geek_brains_homeworks_examples_940
/lesson_2/task_4.py
521
4.375
4
""" Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ words = input('Введите слова через пробел: ').split() for i, word in enumerate(words, 1): print(f'{i}: {word[:10]}')
false
3f060b1e9dbb260ac6fa4b566d256110ad8cbf08
legacy72/geek_brains_homeworks_examples_940
/lesson_1/task_2.py
503
4.4375
4
""" Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. """ time_in_seconds = int(input('Введите кол-во секунд: ')) minutes = time_in_seconds // 60 seconds = time_in_seconds % 60 hours = minutes // 60 minutes = minutes % 60 print(f'{hours:02}:{minutes:02}:{seconds:02}')
false
278d9eb16ebad5e515b87573022d396e05cce2f7
taepd/study
/Machine Learning/수업 자료/1주차_파이썬 프로그래밍/제04일차/myArrSum.py
344
4.15625
4
# 리스트의 모든 요소들의 합을 구해주는 함수 arrsum def arrsum(data): total = 0 for item in data: total += item return total mylist = [10, 20, 30] result = arrsum(mylist) print(result) mydata = (1, 2, 3) result = arrsum(mydata) print(result) myset = set((11, 22, 33)) result = arrsum(myset) print(result)
false
0519a64e3938b4f567b674acfc766372e0ef4e1f
Hank02/CodeEval
/easy/penultimate_word.py
724
4.25
4
# print next-to-last word of each input string # each string has more than one word import sys # open file with comma-separated list of integers def file_open(): # get inout file name as command line argument in_file = sys.argv[1] # open input file test_cases = open(in_file, "r") return test_cases def find_penultimate(instring): # convert string into list for easier access to individual words inlist = instring.split(" ") # access and print penultimate word print(inlist[-2]) if __name__ == "__main__": # open file file = file_open() #iterate over each line of file and run function for row in file: find_penultimate(row) # close file file.close()
true
0bd64fedc0c0b0bf4e0e9f4c85ebb9f1539a1c4a
Hank02/CodeEval
/easy/longest_word.py
698
4.375
4
# print the longest word in a sentence # if more than one, print the left-most one import sys def file_open(): # get inout file name as command line argument in_file = sys.argv[1] # open input file test_cases = open(in_file, "r") return test_cases # funtion to print in title case def longest_word(instring): # convert string into list by splitting words into elements as_list = instring.split() word = "" length = 0 for each in as_list: if len(each) > length: length = len(each) word = each print(word) if __name__ == "__main__": file = file_open() for row in file: longest_word(row) file.close()
true
911c96d588df562ed190c1cf7b786441f5a78d62
AnupreetMishra/creating-static-variable-oops-
/main.py
675
4.21875
4
class Student: dept='BCA' #define class def __init__(self,name,age): self.name=name #instance variable self.age=age #instance variable #define the object of student class stud1=Student('ANU', '22') stud2=Student('ANKIT' , '19') print(stud1.dept) print(stud2.dept) print(stud1.name) print(stud2.name) print(stud1.age) print(stud2.age) #access class variable using the class Name print(Student.dept) #change the department of particular isinstance stud1.dept='Networking' print(stud1.dept) print(stud2.dept) #change the department for all instance of class Student.dept='Database Administration' print(stud1.dept) print(stud2.dept)
true
225e5540b6996e40ab5ee461b26aa46d7635975a
AreRex14/ppdtmr-python-training
/script-10.py
1,927
4.125
4
# Classes and Objects # basic class class ClassName(object): """docstring for ClassName""" def __init__(self, arg): super(ClassName, self).__init__() self.arg = arg class MyClass(): variable = "hello" def function(self): print("This is a message inside a class.") myobjectx = MyClass() # assign above class(template) to an object myobjectx.variable # access the variable inside the newly created object print(myobjectx.variable) myobjecty = MyClass() # create another object of the same class myobjecty.variable = "assalamualaikum" # access the variable and change the value # print out both values print(myobjectx.variable) print(myobjecty.variable) # access object functions myobjectx.function() # EXERCISE > # Create two new vehicles called kereta1 and kereta2 # Set kereta1 to be a red convertible worth RM60,000.00 with a name of Fer # and kereta2 to be a blue van named Jump worth RM10,000.00 # define the Vehicle class # class Kenderaan: # nama = "" # jenis = "kereta" # warna = "" # harga = 5000.00 # def penerangan(self): # str_penerangan = "%s adalah %s %s bernilai RM%.2f." % (self.nama, self.warna, self.jenis, self.harga) # return str_penerangan # # your code goes here # # test code # print(kereta1.penerangan()) # print(kereta2.penerangan()) # SOLUTION > class Kenderaan: nama = "" jenis = "kereta" warna = "" harga = 5000.00 def penerangan(self): str_penerangan = "%s adalah %s %s bernilai RM%.2f." % (self.nama, self.jenis, self.warna, self.harga) return str_penerangan kereta1 = Kenderaan() kereta2 = Kenderaan() kereta1.warna = "Merah" kereta1.harga = 60000 kereta1.nama = "Fer" kereta2.jenis = "van" kereta2.warna = "Biru" kereta2.harga = 10000 kereta2.nama = "Jump" print(kereta1.penerangan()) print(kereta2.penerangan())
true
1de9de90abb9edd40590ce6d6e3e32d98b5871bd
AlexMan2000/ICS
/Lectures/Lecture 6/quicksort_student.py
750
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 6 20:05:43 2019 @author: xg7 """ def quicksort(seq): if len(seq) <= 1: return seq low, pivot, high = partition(seq) return quicksort(low) + [pivot] + quicksort(high) def partition(seq): """complete the function""" pivot, seq = seq[0], seq[1:] #pick the first element as pivot low = [] high = [] # iterate through each element of the list and put it in either 'low' or 'high' for i in seq: if i >= pivot: low.append(i) else: high.append(i) return low, pivot, high ##main listA = [9, 7, 6, 4, 2, 7, 8, 13, 1] print("Before sorting: ", listA) print("After sorting:", quicksort(listA))
true
ca9e6a0b79162a852a99c1b50db3e4586a1a35f1
mohnoor94/CorePythonCourse
/28 - Lecture 19/module_01/math_helpers.py
377
4.3125
4
def multiply(num1, num2, *numbers): """ Multiply all values and return the result. """ result = num1 * num2 if len(numbers): for num in numbers: result *= num return result def avg(*numbers): """ Return the average of all numbers. """ return sum(numbers) / len(numbers) if len(numbers) else 0
true
8975d1a0db28d952721747d232c7aa043106649e
orlewilson/lab-programacao-tin02s1
/aulas/exemplo5.py
1,518
4.25
4
""" Disciplina: Laboratório de Programação Professor: Orlewilson B. Maia Autor: Orlewilson B. Maia Data: 31/08/2016 Descrição: Exemplos com condições (if). """ """ Sintaxe if (condição): bloco verdadeiro else: bloco falso if (condição): bloco verdadeiro else: if (condição): bloco verdadeiro if (condição): bloco verdadeiro elif (condição): bloco verdadeiro else: bloco falso """ # Exemplos com if x = int(input("Digite um valor para x: ")) y = int(input("Digite um valor para y: ")) if (x < y): print("%d é menor que %d" %(x,y)) if (x >= y): print("%d é maior ou igual a %d" %(x,y)) if (x < y): print("%d é menor que %d" %(x,y)) else: print("%d é maior ou igual a %d" %(x,y)) # -------------------------------- categoria = int(input("Digite a categoria do produto: ")) preco = 0.0 # Solução 1 if (categoria == 1): preco = 10.0 if (categoria == 2): preco = 18.0 if (categoria == 3): preco = 23.0 if (categoria == 4): preco = 26.0 if (categoria == 5): preco = 31.0 # Solução 2 if (categoria == 1): preco = 10.0 else: if (categoria == 2): preco = 18.0 else: if (categoria == 3): preco = 23.0 else: if (categoria == 4): preco = 26.0 else: if (categoria == 5): preco = 31.0 # Solução 3 if (categoria == 1): preco = 10.0 elif (categoria == 2): preco = 18.0 elif (categoria == 3): preco = 23.0 elif (categoria == 4): preco = 26.0 elif (categoria == 5): preco = 31.0 print("O preço da categoria %d é R$ %2.2f. " %(categoria, preco))
false