blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
416478ce6ed366aae6e2a17427f50b9a86c2cd67
Peterbamidele/PythonPratice
/temp.py
524
4.125
4
from utils import * def celcius_to_fahrenheit(Celcius_value: float): return add(multiply(celcius_to_value, 1.8), 32) values_str = input("Type in your temperature separated by comma") print("val_str", values_str) values_str_list = values_str.split(",") print("val_list", values_str_list) for values_str in values_str_list: temp_celcius_value = float(values_str) fahrenheit_value = celcius_to_fahrenheit(temp_celcius_value) print(f"{temp_celcius_value} deg Celsius is {fahrenheit_value} deg Fahrenheit ")
false
cd1a9d37a86beb2db376580173b1e89984aa6f4d
noooon/100Projects
/Numbers/BinaryDecimalConverter.py
283
4.4375
4
# **Binary to Decimal and Back Converter** # # Develop a converter to convert a decimal number to binary or a binary number # to its decimal equivalent. def BinaryToDecimal(string): print("butts") input = input("Butts: ") print(input + '! = ' + str(BinaryToDecimal(int(input))))
true
b0f3774a3b99cb0f656ec295a54052ea4f48db5a
priyanshukumarcs049/Python
/Day3/practise2.py
2,538
4.15625
4
def swap(array, indexI, indexJ): temp = array[indexI] array[indexI] = array[indexJ] array[indexJ] = temp def bubbleSort(array): n = len(array) for indexI in range(n): exchanges = 0 for indexJ in range(n-1, indexI, -1): if array[indexJ] < array[indexJ-1]: swap(array, indexJ, indexJ-1) exchanges += 1 if exchanges == 0: break def intersection(array_one, array_two): array_one_index = 0 array_two_index = 0 size_of_array_one = len(array_one) size_of_array_two = len(array_two) while array_one_index < size_of_array_one and array_two_index < size_of_array_two: if array_one[array_one_index] < array_two[array_two_index]: array_one_index += 1 elif array_one[array_one_index] > array_two[array_two_index]: array_two_index += 1 else: yield array_one[array_one_index] array_one_index += 1 array_two_index += 1 def union(array_one, array_two): array_one_index = 0 array_two_index = 0 size_of_array_one = len(array_one) size_of_array_two = len(array_two) while array_one_index < size_of_array_one and array_two_index < size_of_array_two: if array_one_index > 0 and array_one[array_one_index - 1] == array_one[array_one_index]: array_one_index += 1 continue if array_two_index > 0 and array_two[array_two_index - 1] == array_two[array_two_index]: array_two_index += 1 continue if array_one[array_one_index] < array_two[array_two_index]: yield array_one[array_one_index] array_one_index += 1 elif array_one[array_one_index] > array_two[array_two_index]: yield array_two[array_two_index] array_two_index += 1 else: yield array_one[array_one_index] array_one_index += 1 array_two_index += 1 while array_two_index < size_of_array_two: if array_two_index > 0 and array_two[array_two_index - 1] == array_two[array_two_index]: array_two_index += 1 continue yield array_two[array_two_index] array_two_index += 1 while array_one_index < size_of_array_one: if array_one_index > 0 and array_one[array_one_index - 1] == array_one[array_one_index]: array_one_index += 1 continue yield array_one[array_one_index] array_one_index += 1
false
eaada4205b06d821a380cfd0e0ec214de2ebf7ad
Klaus-Analyst/Python-Programs
/all/ccs2.py
411
4.15625
4
# Syntax # if boolean: # _____________ # _____________ # elif boolean: # _____________ # _____________ # elif boolean: # ......... # ......... # else: # __________ print("Hello") a=int(input("Enter First Number:")) b=int(input("Enter Second Number:")) if a>b: print(a, "is Big no") elif b>a: print(b, "is big no") elif a==b: print("both no's are Equal") print("Thanks")
false
7630eabebd3b472982f4fca4b273f69427f652ec
shayyal-py/first-project-py
/string_repeat_1.py
379
4.40625
4
#!/usr/bin/python3.5 # Strings can be repeated using * var = 'Hi' * 3 print ("String after Hi * 3 : ", var) var1 = 3 * 'Hi' print ("String after 3 * Hi : ", var1) print ("String after repetation 3 * 'un' + 'mm' : ", 3 * 'un' + 'mm') print ("String after repetation 'un' + 3 * 'mm' : ", 'un' + 3 * 'mm') print ("String after repetation 'un' + 'mm' * 3 : ", 'un' + 'mm' * 3)
false
2c99cdd6882b6a7f3eb54c19312160a6e6236976
D9O/UNH
/homework_04/Program_1.py
447
4.21875
4
''' program 1: Write a function that converts temperature from Fahrenheit to Celsius using formula Tc=(5/9)*(Tf-32) To test your answer, 68F = 20C ''' def Far2Cel(degF): return (5.0/9)*(degF-32) if __name__ == "__main__": print(f"0 deg F is {Far2Cel(0):.2f} deg C") print(f"32 deg F is {Far2Cel(32):.2f} deg C. b/c 'mericuh") print(f"50 deg F is {Far2Cel(50):.2f} deg C") print(f"100 deg F is {Far2Cel(100):.2f} deg C")
false
11919c82dc76b133412245e20aef4654f91f027f
D9O/UNH
/homework_04/Program_2.py
827
4.3125
4
''' Write a function count_frequency that takes a list of words as an argument, counts how many times each word appears in the list, and then returns this frequency listing as a Python dictionary Sample function call and output: mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"] print(count_frequency(mylist)) {'seven': 1, 'one': 2, 'eleven': 3, 'three': 2, 'two': 2} ''' from collections import Counter def lazy_man(list_obj): return Counter(list_obj) def count_frequency(list_obj): ks = set(list_obj) ret_val = {} for k in ks: ret_val[k] = list_obj.count(k) return ret_val if __name__ == "__main__": mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"] print(count_frequency(mylist)) print(lazy_man(mylist))
true
a521606c0a970e73ff6a5344138c56fc454d842f
NitroLine/python-task-help
/21-30/28_subsets.py
555
4.15625
4
# Написать генераторную функцию, возвращающую подмножества множества. # itertools.combinations использовать нельзя: (30 баллов) def subsets(s): power_set = [[]] yield {} for x in s: for i in range(len(power_set)): tmp_list = power_set[i].copy() tmp_list.append(x) power_set.append(tmp_list) yield set(tmp_list) if __name__ == '__main__': S = [1, 2, 3] for s in subsets(S): print(s)
false
18bae6fa53b520feb6b0e1bc20f4158234468500
NitroLine/python-task-help
/31-40/40_solve.py
879
4.28125
4
# Реализовать функцию `solve`, принимающую числовую функцию `f(x)`, действительные числа `a` и `b`, точность `eps` # (по умолчанию примем равной `1e-10`). Функция должна вернуть одно из решений уравнения `f(x) = 0` на отрезке `[a; b]` # с (абсолютной) точностью `eps`; либо выбросить исключение `ValueError`, если `f(a) < 0` или `f(b) > 0`. def solve(function, a, b, eps=1e-10): if function(a) < 0 or function(b) > 0: raise ValueError while a + eps < b: mid = (a + b) / 2 if abs(function(mid)) < eps: break if function(mid) > eps: a = mid elif function(mid) < -eps: b = mid return (a + b) / 2
false
594b64c409007fec91e80027d33636e312babcc6
justinsantiago210/Raspberry-Repo
/rockpaperscissor.py
711
4.15625
4
from random import choice choice_list = ["rock", "paper", "scissors"] player_choice = input("Please Choose either Rock, Paper or Scissors!: ") computer_choice = choice(choice_list) outcome = {"scissors": {"win":"paper", "lose":"rock"}, "paper": {"win":"rock", "lose":"scissors"}, "rock": {"win":"scissors", "lose":"paper"}} if outcome[player_choice]["win"] == computer_choice: print("The computer has chosen: ", computer_choice) print("You win!") elif outcome[player_choice]["lose"] == computer_choice: print("The computer has chosen: ",computer_choice) print("You Lose!") else: print("The computer has chosen: ",computer_choice) print("It's a tie. Go again!")
true
f35645606c1ae78b380ab901dc9b3ae680494f6d
PranavSalunke/FirstPythonProjects
/working pojects/fibonacci.py
1,121
4.3125
4
''' This program makes and displays a fibonacci sequence for a inputed amount it then prompts to add them. If accepted, it adds all the numbers in the sequence and displays it. ''' ## makes the list global fib global fib_for_sum def fibonacci(): '''Creates fibonacci sequence''' global fib global fib_for_sum fib = [1] fib_for_sum = '' how_many = int(raw_input('How many times do you want to do this?\n')) print 'this is in the funtion' print how_many while how_many > 1: if len(fib) <= 1: fib += [1] else: fib += [fib[len(fib)-1]+fib[len(fib)-2]] how_many -= 1 print fib fib_for_sum = fib sum_of_fibonacci() ## adds all of the numbers def sum_of_fibonacci(): Continue = raw_input('would you like to see the sum of all the numbers in the list you created above? (Y/N)\n') global fib_for_sum sum_of_fib = 0 if Continue == 'y' or "Y" or "yes" or "Yes": for i in fib: sum_of_fib += i else: pass print '\nThe sum of your sequence is: ',sum_of_fib #runs the program fibonacci() ## to keep the program running print '\n\n' is_the_thing_running = raw_input('press enter to exit..' )
true
c4a1197ad476b3a6241e3ccab6fd3961eaf97214
AndyKovacs/python_fundamentals
/python_fundamentals-master-2/labs/03_more_datatypes/1_strings/04_05_slicing.py
474
4.40625
4
#''' #Using string slicing, take in the user's name and print out their name translated to pig latin. #For the purpose of this program, we will say that any word or name can be #translated to pig latin by moving the first letter to the end, followed by "ay". #For example: ryan -> yanray, caden -> adencay #''' s = input("enter your username: ") first_letter = s[0] rest_of_word = s[1:] ending_ay = "ay" latinform = first_letter+ending_ay print (rest_of_word,latinform)
true
a10cdc3169de9fa537bbf28067fc85afe3fa0a40
CaptainIRS/codecharacter-poc
/ai-code/ai.py
1,156
4.125
4
import random def generate_equation() -> str: """ Generates a random equation. """ num1 = random.randint(1, 9) num2 = random.randint(1, 9) num3 = random.randint(1, 9) operator1 = random.choice(["+", "-", "*"]) operator2 = random.choice(["+", "-", "*"]) return str(num1) + operator1 + str(num2) + operator2 + str(num3) def solve_equation(equation: str) -> int: """ Solves the equation. """ return str(int(eval(equation))) def read_line(): for line in open('in', 'rb', 0): yield line.decode().strip() def input(): return next(read_line()) role = input() if role == 'giver': # We provide an equation first. equation = generate_equation() print(equation) for i in range(500): equation = input() print(solve_equation(equation)) equation = generate_equation() print(equation) elif role == 'solver': # We solve first equation = input() print(solve_equation(equation)) for i in range(500): equation = generate_equation() print(equation) equation = input() print(solve_equation(equation))
true
84094d69251ab0deee0e09264a78819b5670e48d
shizakhan/lab_10
/lab 10_pg 09.py
461
4.15625
4
print('shiza khan','18B-130-CS') print('lab 10','program 09') print('\n') #removing items from the dictionary using pop() stu_info = {'name':'jibran','age':'12','class':'sixth','DOB':'16 april 2006', 'school':'the seeds school','friend1':'mohib','friend2':'akbar', 'friend3':'jaril'} for x,y in stu_info.items(): print(x,y) stu_info.popitem() print("after poping from the dictionary the remaining elements are: ",stu_info)
false
a53af8de340fcd7c3298c8f80a9f830072063d5c
shizakhan/lab_10
/lab 10_pg 02.py
491
4.25
4
print('shiza khan') print('18B-130-CS(A)','lab 10') print('program 02') print('\n') #using for loop to access the values stored inside the dictionary. student_info = {'name':'jibran','age':'12','class':'sixth','DOB':'16 april 2006'} for x in student_info: print(student_info[x])
false
fd4154a6e7a100f92cbb3040528b5bb13c27c0c2
OatsandToast/Python-Practice
/Numberguess/guesser.py
621
4.125
4
#!/usr/bin/env python """guesser.py, by ThatGuy, 2016 This program has the user guess a number between 1 and 100. """ import random attempts = 5 secret_number = random.randint(1, 100) for attempt in range (attempts): guess = int(input('Take a guess: ')) if guess < secret_number: print('Higher...') elif guess > secret_number: print ('Lower...') else: print() print('You guessed it! The number was', secret_number) print('You guessed it in', attempts, 'attempts') break if guess != secret_number: print('Sorry you reached the maximum number of tries' ) print('The secret number was', secret_number)
true
e189f638994fd606e08a1f0950c15f2f90b35c80
Auleen/Git-WorkShop
/primes.py
385
4.34375
4
# function to check if given number is prime or not def is_prime(n): cur = 2 while cur ** 2 <= n: if n % cur == 0: return false # error cur++ return true # error if __name__ == "__main__": n = int(input()) if is_prime(n): print("The number if prime!!") else: # correct the error here print(It is not prime)
true
9f96bd09e45df161abc763216be0935ba6a2dc02
maduoma/Python
/100DaysOfPythonCoding/DataTypes/DataTypes.py
880
4.15625
4
# Data Types # 1. String # prints to the console the character at index 4 print("Hello"[4]) # Concatenation using plus (+) print("123" + "456") # 2. Integer print(123 + 456) # Python ignores the underscore that serves as commas and prints the number print(123_456_789) # 3. Float print(3.12534) # 4. Boolean print(True) print(False) # Type Checking name = "Madu" num1 = 123 print(type(name)) print(type(num1)) # Type Conversion or Casting print(str(123) + str(456)) print(float(70)) # Drops the number after the decimal point print(int(7.5)) ################################################################# # Challenge 2.1: Sum of A 2-digit number ################################################################# two_digit_number = input("Type a two-digit number!\n") sum_of_two_digit_num = int(two_digit_number[0]) + int(two_digit_number[1]) print(sum_of_two_digit_num)
true
c73a17b760a5b34983bcab5dca07d094b73b6d92
ADemkin/Practice
/*args.py
1,147
4.15625
4
# print out individual elements of lists inside lists from random import randint as rnd def create_nested_list(): if rnd(0,1) == 0: x= rnd(0,10) else: x= create_nested_list() return [x for i in range(0,rnd(0,5))] def print_nested_list_recursive(lists,indentation=0): #print('new list:', lists) for number, element in enumerate(lists): if type(element) == list: print_nested_list_recursive(element, indentation+4) else: spaces = '' for i in range(0,indentation): spaces += ' ' print("%s %s: %s" % (spaces, number, element)) def print_nested_list_linear(*args): for element in args: if len(element) == 1: print(element) else: print_nested_list_linear(element) print(element) def main(): list = create_nested_list() #print(list) #print_nested_list_recursive(list) #print_nested_list_recursive([1,[1,[1,1]],[2,[2,2]],[[3,[3,[3]],3]],24]) print_nested_list_linear([1,[1,[1,1]],[2,[2,2]],[[3,[3,[3]],3]],24]) if __name__ == "__main__": main()
true
f50fba432a45a239a045eaf24e8c77d77eba2ce8
ADemkin/Practice
/recursive factorial.py
492
4.15625
4
#!/usr/bin/env python3 #coding: utf-8 # # факториал это перемножение всех чисел от 1 до данного. def factorial_recursive(number): if number == 0: return 0 elif number == 1: return 1 else: number = number * factorial_recursive(number - 1) return number for i in range(0,25): print("Factorial of %d is %d" % (i, factorial_recursive(i))) def main(): pass if __name__ == "__main__": main()
false
c82eebc007913a0d163ac84d8f18c3e1aafbbae0
xinpaladin/python_study
/iter_fan.py
913
4.28125
4
# 如何反向迭代以及如何实现反向迭代 ''' 案例 实现一个连续副段淑发生器FloatRange,根据给定的范围和步进产生一序列连续浮点数 FloatRange(3.0,4.0,0.2) example: 3.0 -> 3.2-> 3.4-> 3.6-> 3.8-> 4.0 正向 example: 4.0 -> 3.8-> 3.6-> 3.4-> 3.2-> 3.0 反向 ''' # reversed(l) 得到反向迭代器 l = [1, 2, 3, 4, 5, 6] for i in reversed(l): print(i) class FloatRange: def __init__(self, start, end, step=0.1): self.start = start self.end = end self.step = step def __iter__(self): t = self.start while t <= self.end: yield t t += self.step def __reversed__(self): t = self.end while t>=self.start: yield t t -=self.step for x in FloatRange(1.0,4.0,0.5): print('iter',x) for y in reversed(FloatRange(1.0,4.0,0.5)): print('reversed ',y)
false
d2e4343209de697890e4af489ebd9d82d330e2ff
scress78/Module7Try2
/sort_and_search_array.py
2,261
4.25
4
""" Program: sort_and_search_array.py Author: Spencer Cress Date: 06/21/2020 This program contains the functions sort_array and search_array for Search and Sort List Assignment """ import array as arr def sort_array(x): """ :parameter x: a list to be cast into an array, cast back into a list, sorted and then output :returns: A sorted list """ try: my_array = arr.array('i', x) except ValueError: raise ValueError from None my_other_list = [] for a in my_array: my_other_list.append(a) my_other_list.sort() return my_other_list pass # this array WILL include a return, that return will be the sorted list. # I'm doing it this way because it makes sense to me to have a return # since we eventually need a test to pass. It doesn't work for me without a return def search_array(x, y): """ :parameter x: a list to be searched :parameter y: the item to be searched for in the list :returns: the index of the item in the list, if it is in the list; otherwise -1 if it isn't. """ try: my_search_array = arr.array('i', x) except ValueError: raise ValueError from None my_list_search_array = [] for a in my_search_array: my_list_search_array.append(a) try: z = my_list_search_array.index(y) except ValueError: z = -1 return z pass def make_list(): """ :returns: a list of three numbers :raises ValueError: given non-numeric input or input that is less than 1 or greater than 50 """ my_list = [] for n in range(1, 4): try: x = get_input() x = int(x) if x < 1: raise ValueError from None if x > 50: raise ValueError from None my_list.insert(0, x) except ValueError: raise ValueError from None return my_list def get_input(): """ :returns: A string, that should be a number """ x = input("Please input a number: ") return x if __name__ == '__main__': # x = make_list() # sort_array(x) y = make_list() search_array(y, 15)
true
7c71e2f70997d4520662f78b8ed89edc4d0bfc42
Parth1267/PythonAssignment
/31-03-2021/factorial.py
318
4.375
4
# Python 3 program to find # factorial of given number def factorial(n): if n < 0: return 0 elif n == 0 or n == 1: return 1 else: fact = 1 while(n > 1): fact *= n n -= 1 return fact # Driver Code num = 5 print("Factorial of", num, "is", factorial(num)) # This code is contributed by Dharmik Thakkar
false
5dc8e528eb159aa9396ede580a0c5835090514b1
sypark23/pro_1Sarah
/proj04/proj04.py
442
4.15625
4
# Name: # Date: """ proj04 Asks the user for a string and prints out whether or not the string is a palindrome. """ x= raw_input("Enter a random word") while len(x) >1: if x[0]!=x[-1]: variable=False break if x[0]==x[-1]: x=x[1:-1] x[0] == x[-1] variable=True if variable == True: print"the word is a palindrome" if variable == False: print"the word is not a palindrome"
true
8143a44fe064a7eeeb283902ed1e7581dc97abbc
education-repos/python_algos_gb
/lesson2/task_3.py
1,426
4.25
4
""" 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Например, если введено число 3486, то надо вывести число 6843. Подсказка: На каждом шаге вам нужно 'доставать' из числа очередную цифру Пока все числа не извлечены рекурсивные вызовы продолжаем Условие завершения рекурсии - все числа извлечены Решите через рекурсию. Решение через цикл не принимается. Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7 Пример: Введите число, которое требуется перевернуть: 123 Перевернутое число: 321 """ def recursive_num(num, string): if num > 0: number = num % 10 string += str(number) recursive_num(num // 10, string) else: print(string) return try: number_from_input = int(input('Введите число, которое требуется перевернуть:')) recursive_num(number_from_input, '') except ValueError: print('Вы ввели не число!')
false
c95415e9f9b4f457aaf9a144f42f4448444bc0ac
Kcpf/MITx-6.00.1x
/Week 3-Structured Types/how_many.py
845
4.28125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 24 11:18:47 2020 @author: Fernando """ """ Exercise: how many Consider the following sequence of expressions: animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') We want to write some simple procedures that work on dictionaries to return information. First, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary. For example: >>> print(how_many(animals)) 6 """ def how_many(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' # Your Code Here how_many = 0 for each in aDict: how_many += len(aDict[each]) return how_many
true
90fb2f17ea146507e0cda963478570f623c8f585
Atul-Acharya-17/Deep-Q-Learning-Snake
/q_learning/graphics/window.py
1,925
4.1875
4
"""Window Class The Window Class is responsible for rendering the screen and rendering the snake and cherry on the screen. The dimensions of the screen are 400x400 pixels """ import pygame pygame.init() class Window(): # constructor def __init__(self, block_size=20, dims=400): # space that each entity occupies in the screen self.block_size = block_size # width of the screen self.width = dims # height of the screen self.height = dims # dimensions of the screen self.screen_dimensions = (self.width, self.height) # screen self.screen = pygame.display.set_mode(self.screen_dimensions) # color of the screen self.screen_color = (50, 50, 50) # renders the screen def draw_screen(self): rect = pygame.Rect(0, 0, self.width, self.height) pygame.draw.rect(self.screen, self.screen_color, rect) # renders the snake def draw_snake(self, snake): # renders head of the snake rect = pygame.Rect(snake.head[1] * self.block_size, snake.head[0] * self.block_size, self.block_size, self.block_size) pygame.draw.rect(self.screen, snake.head_color, rect) # renders the body of the snake for piece in snake.body: rect = pygame.Rect(piece[1] * self.block_size, piece[0] * self.block_size, self.block_size, self.block_size) pygame.draw.rect(self.screen, snake.body_color, rect) # renders the cherry def draw_cherry(self, cherry): rect = pygame.Rect(cherry.position[1] * self.block_size, cherry.position[0] * self.block_size, self.block_size, self.block_size) pygame.draw.rect(self.screen, cherry.color, rect) def display_score(self, score): font = pygame.font.Font("freesansbold.ttf", 16) message = font.render(str(score), True, (255, 255, 0)) self.screen.blit(message, (200, 10))
true
ef9994c26cc308e75809f2789a3d0fbea21116bd
bdbeck2/learninglab
/pat-course/py_format_0.py
1,208
4.15625
4
#!/usr/local/bin/python3 #py_format_0.py """Some formatting exotics""" #numbered fields ('all or none' here) stg = "{2} {1} {0}"\ .format("George", "Paul", "John") print(stg) print() #named fields ('all or none'; note no quotes around names) stg = "{who} is a smart {what}"\ .format(what = 'cookie', who = 'Silvia') print(stg) print() #dig out bits of a list using format string stg = "The 5th element of the 1st argument is {0[5]}"\ .format( ["Dallas", "Zorg", "Cornelius", "Ruby", "Billy", "Leelo"]) print(stg) print() #refer to dict keys using format string (note no quotes) d = {'Cher':'Sarkisian', 'Sonny':'Bono'} stg = "Sonny's surname is {0[Sonny]}".format(d) print(stg) print() #on-the fly formatting - {0:>6} means first element, 6 wide, left justified stg = "Cher's surname is {lookup[Cher]}".format(lookup = d) print(stg) print() #10 wide, accept default justification stg = "{0:10} {1:10}" for first, last in d.items(): print(stg.format(first, last)) print() #example of numeric base "casting"; stg = "{0:>6} = {0:#16b} = {0:#06x}" #note the '#..b' and '#0..x' for i in (1, 23, 456, 7890): print(stg.format(i))
true
4424feaa856e186c1c49125d84e8820e528d7c6b
asmitde/TA-PSU-CMPSC101
/Fall 2016/Recitations/RW3/problem2.py
605
4.40625
4
# Name: Asmit De # Section: 001/002 # PSU ID: aud311 # Lab Assignment: Recitation Week 3 - Problem 2 # Date: 09/08/2016 # Description: Calculate sum, product and average of any three numbers # Prompt the user to enter three numbers and save them in variables print('Please enter three numbers:') num1 = int(input()) num2 = int(input()) num3 = int(input()) # Calculate the sum, product and average sum = num1 + num2 + num3 product = num1 * num2 * num3 average = sum / 3 # Print the result print('The sum is:', sum) print('The product is:', product) print('The average is:', average)
true
80d83b799f84761a52efb3942db19eb1d4296c51
asmitde/TA-PSU-CMPSC101
/Fall 2016/Homeworks/HW4/Solution/problem7.py
353
4.1875
4
import random # Obtain the random number 0 or 1 number = random.randint(0, 1) # Prompt the user to enter a guess guess = int(input("Enter 0 for Head and 1 for Tail: ")) # Check the guess if guess == number: print("You guessed correctly!") elif number == 0: print("Sorry, it is a head.") else: print("Sorry, it is a tail.")
true
9bc3e25f2d369cca16e8c4101a660e3496c8b475
asmitde/TA-PSU-CMPSC101
/Fall 2016/Homeworks/HW2/Solutions/problem9.py
698
4.28125
4
# Name: Asmit De # ID: aud311 # Date: 09/20/2016 # Assignment: Homework 2, Problem 9 # Description: Program to convert a 6-bit binary number to decimal # Prompt the user to enter a 6-bit binary number binary = int(input('Enter a 6-bit binary number: ')) # Extract the bits and form the decimal number decimal = 0 decimal += (binary % 10) * (2 ** 0) binary //= 10 decimal += (binary % 10) * (2 ** 1) binary //= 10 decimal += (binary % 10) * (2 ** 2) binary //= 10 decimal += (binary % 10) * (2 ** 3) binary //= 10 decimal += (binary % 10) * (2 ** 4) binary //= 10 decimal += (binary % 10) * (2 ** 5) # Display the decimal number print('The decimal equivalent is', decimal)
true
48a4906117de7a1aa6bc52e586bf92b374d097c9
asmitde/TA-PSU-CMPSC101
/Spring 2017/Homework/Homework1/q6.py
326
4.53125
5
# HW1 Q6 - Calculate perimeter of circle # Author(s): Asmit De # Date: 01/27/2017 # Set value of constant PI PI = 3.14 # Input radius from user radius = float(input("Enter radius of circle: ")) # Calculate perimeter using formula perimeter = 2 * PI * radius # Output perimeter print("Perimeter =", perimeter)
true
2e57679b883a05f8d9040135e53d4f34f3640125
asmitde/TA-PSU-CMPSC101
/Spring 2017/Recitations/Lab6/Q1.py
1,124
4.46875
4
# Recitation Lab 6 Question 1 - Interleave elements from lists # Author: Asmit De # Date 03/16/2017 # Input number of elements in list n = int(input('Enter number of list elements: ')) # Initialize empty lists list1 = [] list2 = [] list3 = [] # Populate list1 with multiples of 5 i = 1 while i <= n: # Generate i-th multiple of 5 multiple = 5 * i # Add multiple to list1 list1.append(multiple) # Increment i i += 1 # Populate list2 with odd numbers oddn = 1 i = 1 while i <= n: # Add i-th odd number to list2 list2.append(oddn) # Generate next odd number oddn += 2 # Increment i i += 1 # Populate list3 with elements from list1 and list2. # Note that list index starts at 0. i = 0 while i < n: # Access i-th elements from list1 and list2 elem1 = list1[i] elem2 = list2[i] # Add the two elements to list3 list3.append(elem1) list3.append(elem2) # Increment i i += 1 # Print the lists print('List1:', list1) print('List2:', list2) print('List3:', list3)
true
ad8e901b601a8a5290fbddd45cd3dc69f7015d47
ankurf/MITx-6.00.1x-Intro-to-CS-and-Programming-Using-Python
/Problem_Set_1/Counting_Bobs.py
534
4.25
4
##https://courses.edx.org/courses/course-v1:MITx+6.00.1x_8+1T2016/courseware/Week_2/Basic_Problem_Set_1/ ## ##Counting Bobs ## ##Assume s is a string of lower case characters. ## ##Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', ##then your program should print ## ##Number of times bob occurs is: 2 count=0 x=0 y=3 for n in range(len(s)-2): s1=s[x:y] x+=1 y+=1 if s1=="bob": count+=1 print("Number of times bob occurs is: "+str(count))
true
31d8b209d24173f514cb96922fce7f5d6142fae3
jesssyb/PythonYear2
/Yr2Unit1.7.py
1,378
4.1875
4
#Jessica #Books title = ["Apprentice in Death","Razor Girl","The Underground Railroad","A Great Reckoning","The Woman in Cabin 10"] author = ["J. D. Robb","Carl Hiaasen","Colson Whitehead","Louise Penny","Ruth Ware"] cost = [17.19,17.02,21.56,17.56,15.66] revenue = [1727595.00,1706255.00,2156000.00,1751610.00,1558170.00] def main(): return calc() def enter(expense,expense2,book,book2,): bt = input("Enter the book title: ") ba = input("Enter the author of the book: ") bc = float(input("Enter the cost of the book: ")) gr = float(input("Enter the gross revenue of he book: ")) title1 = title.append(bt) author1 = author.append(ba) cost1 = cost.append(bc) revenue1 = revenue.append(gr) return calc() def calc(): expense = max(cost) expense2 = min(cost) index = cost.index(expense) index2 = cost.index(expense2) book = title[index] book2 = title[index2] return display(expense,expense2,index,index2,book,book2) def display(expense,expense2,index,index2,book,book2): print ("The most expensive book is:",expense) print ("Name of book:",book) print ("The least expensive book:",expense2) print ("Name of book:",book2) again = input("Do you have another book? Y or N: ") if again.lower() == "y": return enter(expense,expense2,book,book2) main()
true
33e4d9a07c2c9ce624232dd7ffcd1814ffb52433
AndrewGottilla/LearningPython
/Section 05 - Dictionaries/lesson35-dictionaryMethods.py
1,100
4.3125
4
### 2020-09-08 ### Author: Andrew Gottilla ### Lesson 35: Dictionary methods # Survey dictionary: participant : favorite flavor fav_chips_survey = { 'andrew': 'Dill Pickle', 'chris' : 'BBQ', 'thomas': 'Honey BBQ', 'mike' : 'Salt and Vinegar', 'bobby' : 'Original', 'hank' : 'BBQ', 'peggy' : 'Original', 'tony' : 'Salt and Vinegar', 'bill' : 'Jalapeno', 'ted' : 'BBQ' } print("- - Favorite Chips Survey - -\n") # Printing all keys of a dictionary : .keys() method print("Participants:") for participant in fav_chips_survey.keys(): print(participant.title() + ", ", end='') print("and myself! Just kidding.\n") # Printing the key-value pairs while looping : .items() method print("Survey results:") for key, val in fav_chips_survey.items(): print("Participant: " + key.title() + "\n -Favorite flavor: " + val) print() # Using set() function to print all unique values of dictionary : .values() method print("All unique chip flavors:") for flavor in set(fav_chips_survey.values()): print("-" + flavor) print()
false
8980ca86244a5bda54432ec21a656b2b0fd2be0e
AndrewGottilla/LearningPython
/Section 03 - Lists and For Loop/lesson21-numericalList.py
682
4.40625
4
### 2020-09-06 ### Author: Andrew Gottilla ### Lesson 21: Numerical lists (aka Big Data baybeeee) # Create list of numbers from 1 to 5 numbers = list(range(1,6)) print (numbers) # Create list of odd numbers from 1 to 50 # Starts at 1 and then adds 2 repeatedly odd_numbers = list(range(1,51,2)) print(odd_numbers) # Create list of squared numbers squares = [] for val in range(1,10): squares.append(val ** 2) print(squares) # using min() function to print lowest number in list print(min(numbers)) # using max() function to print highest number in list print(max(numbers)) # using sum() function to print sum of all numbers in a list print(sum(numbers))
true
621e0daca784f96b47e427062061ed2c320f17a4
AndrewGottilla/LearningPython
/Section 10 - Files and Exceptions/lesson63-handleExceptions.py
897
4.40625
4
### 2020-12-03 ### Author: Andrew Gottilla ### Lesson 63: Handling exceptions try: print(5/0) except ZeroDivisionError: print('= You\'re seeing this because you can\'t divide by zero! =\n') print('Let\'s do some math! Enter two numbers to be divided!') while True: print("[Enter 'q' at any point to quit]\n") num1 = input('First number: ') if num1 == 'q': break num2 = input('Second number: ') if num2 == 'q': break print('-------------------------------------') try: ans = int(num1) / int(num2) except ZeroDivisionError: print('= You\'re seeing this AGAIN because you STILL can\'t divide by zero!') except: print('ERROR: INVALID INPUT! TRY AGAIN.') else: print(num1 + ' divided by ' + num2 + ' is ' + str(ans) + '!') print() print('\nLet\'s do it again!')
true
cd4fbb580b47e37989065d8efd36718cbf41b447
nodebe/ItechforBootcamp
/first_program.py
254
4.15625
4
name = input('what is your name: ') #taking in the name of the user and printing it out print(name) """ This is a multiline comment I can type things anyhow and it would not compile """ #I want to make a multi line comment #THis is a multiline comment
true
3f1550d9253fb9f05ffe76ca2cef64af56fdff5b
coryseaborn/python_the_hard_way
/8ex.py
854
4.28125
4
# sets the formatter variable, to use the raw format formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter, formatter, formatter, formatter) # look at the output below, which shows the "but" string as single quotes. that's because it has the word 'didn't' which uses a single quote, which python changes when generating the representation print formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." ) # outputs with the following # 1 2 3 4 # 'one' 'two' 'three' 'four' # True False False True # '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' # 'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'
true
d7bff581368356740747c3801d473f9dc05ae7d9
coryseaborn/python_the_hard_way
/39ex.py
2,538
4.21875
4
# create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basic set of states and some cities in them cities = { 'CA': 'San Fransisco', 'MI': 'Detriot', 'FL': 'Jacksonville' } # add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print '-' * 10 print "NY state has: ", cities['NY'] print "OR state has: ", cities['OR'] # print some new states print '-' * 10 print "Michigan's abbreviation is: ", states['Michigan'] print "Florida's abbreviation is: ", states['Florida'] # do it by using the state then cities dict print '-' * 10 print "Michigan has: ", cities[states['Michigan']] print "Florida has: ", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) # print every city in state print '-' * 10 for abbrev, city in cities.items(): print "%s has the city %s" % (abbrev, state) # now do both at the same time print '-' * 10 for state, abbrev in states.items(): print "%s state is abbrevated %s and has city %s" % ( state, abbrev, cities[abbrev]) print '-' * 10 # safely get an abbreviation by state that might not be there state = states.get('Texas', None) if not state: print "Sorry, no Texas." # get a cit ywith a default value city = cities.get('TX', 'Does Not Exist') print "The city for the state 'TX' is: %s" % city # dictionaries or dicts are also called hashes with key/value pairs # outputs the following # # ---------- # NY state has: New York # OR state has: Portland # ---------- # Michigan's abbreviation is: MI # Florida's abbreviation is: FL # ---------- # Michigan has: Detriot # Florida has: Jacksonville # ---------- # California is abbreviated CA # Michigan is abbreviated MI # New York is abbreviated NY # Florida is abbreviated FL # Oregon is abbreviated OR # ---------- # FL has the city Oregon # CA has the city Oregon # MI has the city Oregon # OR has the city Oregon # NY has the city Oregon # ---------- # California state is abbrevated CA and has city San Fransisco # Michigan state is abbrevated MI and has city Detriot # New York state is abbrevated NY and has city New York # Florida state is abbrevated FL and has city Jacksonville # Oregon state is abbrevated OR and has city Portland # ---------- # Sorry, no Texas. # The city for the state 'TX' is: Does Not Exist
false
85b48e6cabba71ee68f13b41d65abc3b77dd4b83
vitoriabf/FC-Python
/Lista 1/Ex13.py
677
4.1875
4
'''Crie um algoritmo para calcular a área de um triângulo qualquer, considerando que são fornecidos os comprimentos dos seus lados. Esse programa não pode permitir a entrada de dados inválidos, ou seja, medidas menores ou iguais a 0.''' import math a = int(input('Digite o comprimento 1º: ')) b = int(input('Digite o comprimento 2º: ')) c = int(input('Digite o comprimento 3º: ')) p = (a + b + c)/2 if (a or b or c) <= 0: print('Não será possível fazer o cálculo.') else: d = (p*(p-a)*(p-b)*(p-c)) if d < 0: print('Essa raiz é menor que zero') else: d = math.sqrt(d) print(f'O valor da área do triângulo é {d}')
false
d2bb2fdba04edca2dcf786e2057bb8fb03f585a3
EduardoArgenti/Python
/CursoEmVideo/ex093.py
907
4.15625
4
# Crie um programa que gerencie o aproveitamento de um # jogador de futebol. O programa vai ler o nome do jogador # e quantas partidas ele jogou. Depois vai ler a quantidade # de gols feitos em cada partida. No final, tudo isso será # guardado em um dicionário, incluindo o total de gols feitos # durante o campeonato. # # A solução pensada foi um pouco diferente da proposta do exercício, # mas também funciona. jogador = list() partidas = dict() jogador.append(input('Nome do jogador: ')) total_partidas = int(input('Partidas jogadas: ')) jogador.append(total_partidas) total_gols = 0 for c in range(0, total_partidas): gols = int(input(f'Gols feitos na partida {c}:' )) partidas[f'partida{c}'] = gols total_gols += gols jogador.append(partidas) jogador.append(total_gols) print(f'\nNome: {jogador[0]}\nPartidas jogadas: {jogador[1]}\nGols: {jogador[2]}\nGols totais: {jogador[3]}')
false
969075d227b49a871fad8e9a9503816bf6ba00f1
EduardoArgenti/Python
/CursoEmVideo/ex086.py
654
4.40625
4
# Crie um programa que declare uma matriz de dimensão 3×3 # e preencha com valores lidos pelo teclado. No final, # mostre a matriz na tela, com a formatação correta. # Outra forma de fazer é receber valores [[0, 0, 0], [0, 0, 0], [0, 0, 0] # para não precisar utilizar o append, apenas atribuições simples direto # na coordenada. matriz = [[], [], []] for linha in range(0, 3): for coluna in range(0, 3): n = int(input(f'Posição [{linha+1}][{coluna+1}]: ')) matriz[linha].append(n) print('=+'*30) for linha in range(0, 3): for coluna in range(0, 3): print(f'[{matriz[linha][coluna]:^5}]', end=' ') print()
false
0a5e554cb31aae0f19d4138b6a982872e5088393
b-abdou-dev/Giraffe
/app10_Tuples.py
319
4.125
4
# Tuple is container similar to list but with multiple different values # and they cannot be changed once created (describes the difference between list and tuples) coordinates = (4, 5) print(coordinates[1]) # List with tuples inside that are immutable coordinates = [(4, 5), (6, 8), (13, 11)] print(coordinates[1])
true
adb832687af1921a04a0b842df3d801b13939b3a
slott56/my-euler
/euler01.py
1,570
4.3125
4
#!/usr/bin/env python3 # Multiples of 3 and 5 # ======================= # Problem 1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. # .. rubric:: Solution # # .. py:module:: euler01 # :synopsis: Multiples of 3 and 5 # # The approach is to create a set of numbers that's a union. # Let's do that literally. def answer1(): """Use set(range(0,1000,3)) | set(range(0,1000,5)). Fast. """ m3= range(0,1000,3) m5= range(0,1000,5) return sum(set(m3).union(set(m5))) # We can also do this with a loop and an if statement. def answer2(): """Use an explicit loop and if statement. This is actually 8x slower than answer1(). """ sum= 0 for i in range(1000): if i % 3 != 0 and i % 5 != 0: continue sum += i return sum # Confirm the answer. def confirm( ans ): assert ans == 233168, "{0!r} Incorrect".format(ans) # Compare performance of the :py:func:`answer1` and :py:func:`answer2` function2. def compare_timing(): import timeit print( "answer1", timeit.timeit( "answer1()", "from euler01 import answer1", number=10000) ) print( "answer2", timeit.timeit( "answer2()", "from euler01 import answer2", number=10000) ) # Create some output. if __name__ == "__main__": ans= answer1() confirm(ans) ans= answer2() confirm(ans) print( "Sum of all the multiples of 3 or 5 below 1000:", ans ) #compare_timing()
true
5bf96cc1b423550f48a4b5533149442ef9f97361
slott56/my-euler
/euler41.py
1,844
4.1875
4
#!/usr/bin/env python3 # Pandigital prime # ================ # Problem 41 # We shall say that an n-digit number is pandigital if it makes use of all the # digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is # also prime. # # What is the largest n-digit pandigital prime that exists? # .. rubric:: Solution # .. py:module:: euler41 # :synopsis: Pandigital prime # Some handy functions and classes we've already defined. # :py:class:`euler24.Permutation`, :py:func:`euler03.isprime` # and :py:func:`euler35.number`. from euler24 import Permutation from euler03 import isprime from euler35 import number # Create all permutations of a given set of digits. def pandigitalPrimes(size): """Generate all pan-digital primes of a given size. >>> from euler41 import pandigitalPrimes >>> pd4 = list( pandigitalPrimes(4) ) >>> 2143 in pd4 True >>> pd4 [1423, 2143, 2341, 4231] """ permN= Permutation( range(1,size+1) ) for p in permN.nextPerm(): ld= p[-1] if ld % 2 == 0: continue # skip even numbers if ld == 5: continue # skip 5's, also n= number( p ) if isprime(n): yield n # For sizes from 1 digit to 9 digits, generate all pan-digital primes. # The max should surface quickly if we go in descending order. def PDP_gen(): for n in range(9,0,-1): for pd in pandigitalPrimes(n): yield pd # Test the module components. def test(): import doctest doctest.testmod(verbose=0) # Compute the answer. def answer(): return max( PDP_gen() ) # Confirm the answer. def confirm(ans): assert ans == 7652413, "{0!r} Incorrect".format(ans) # Create some output. if __name__ == "__main__": test() ans= answer() confirm(ans) print( "The largest pan-digital prime:", ans )
true
8eb3655bacd7524aaaf9ad453698e8d06f2f63a6
russellsui/python3
/Introduction to Data Science in Python/Week 1/Python Dates and Times.py
870
4.46875
4
# Python Dates and Times # need to import datetime and time import datetime as dt import time as tm print(tm.time()) # this will print out how much time is there from 1970-01-01 to now dtnow = dt.datetime.fromtimestamp(tm.time()) print(dtnow) # will give the time now # if we wanna pick the specific element of the time dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # this will print out a tuple delta = dt.timedelta(days = 100) # delta actually gives us a days variable, it will be like assign a days 100 to delta # and then we could use delta to do some numerical operations # dt.date actully gives us objects of date like yyyy-mm-dd today = dt.date.today() print(today) # here we used the predefined delta to do some numerical calculations # this will be like throwback 100 days from today and print the result date print(today - delta)
true
4e674139368de1c4e163e7cc3c4b996ca1f083ca
pravencraft/engr3703_2_sums_and_products
/old/python_intro_5.py
2,921
4.1875
4
# This is a comment # The following is the import section # This brings in other python files that have pre-defined functions in them # This will be present in every single program you write from math import * import numpy as np # The following area is a sort of "global" area this code will execute first and will always execute # Below is a function definition def main(): # this is a list - it's a fundamental data structure in python (it's basically a kind of array nums = [0.0, 1.0] # This makes a list with the first item of 0.0 print(nums[0]) # Note the index for the list starts with 0 print(nums[1]) # ENGR3703 Your Turn to Code # ENGR3703 make a new list called numbers, with 4 floats in it. # ENGR3703 print the 4th item in the list # ENGR3703 print the 1st item in the list # A new list and what can be done to it strings = ["red", "green", "blue"] # Function to determine if a certain value is in the list (use the "in" keyword) if "red" in strings: print("Found it!") # ENGR3703 make a list of 4 strings # ENGR3703 Determine if one of the strings that really is there - if so print a message # ENGR3703 Determine if one of the strings that really is NOT there - if it's not there print a message # Function to get length (number of items) in a list "len" print(len(strings)) # ENGR3703 print the length of your list of strings # You can print the entire list like this print(strings) # Let's append to the list strings.append("magenta") print(strings) # ENGR3703 append a new string to your list of strings # to add an item in a particular index strings.insert(1, "burnt sienna") print(strings) # ENGR3703 insert an item into the third position of your list # remove an item by the item itself strings.remove("magenta") # ENGR 3703 remove an item from your list # To remove by index use "pop" or "del" strings.pop(1) # ENGR3703 remove the item in third position in your list strings.pop() # this removes the last item print(strings) # ENGR3703 remove the last item in your list # can also delete this way del strings[1] print(strings) # ENGR3703 delete the first item in your list del strings # totally deletes the list # print(strings) # ENGR3703 delete your list of strings # clear a list but don't delete it strings = ["red", "green"] print(strings) strings.clear() print(strings) # ENGR3703 remake your original list of strings # ENGR3703 clear your list of strings for i in range(0, 10): # print(i) nums.append((i + 1) ** i) # This is how you add items to a list # print(nums) num = 100 # while(num > 1.1): # num-=1 # print(num) # for i in nums: # print(i) if __name__ == '__main__': main()
true
8f9f9d33ed8f81ce08f8cf2b0a36e18781bed97f
megancodes/edX-Python-for-Research
/HW3_Q1.py
2,243
4.3125
4
import string # Exercise 1 # Create a string called alphabet consisting of the space character ' ' # followed by (concatenated with) the lowercase letters. Note that we're only using the lowercase letters in this exercise. alphabet = ' ' + string.ascii_lowercase # Exercise 2 # Create a dictionary with keys consisting of the characters in alphabet # and values consisting of the numbers from 0 to 26. # Store this as positions. positions = {} length = len(alphabet) for i in range(length): positions[alphabet[i]] = i # positions[i] = alphabet[i] print(positions) # Exercise 3 # Use positions to create an encoded message based on message where each # character in message has been shifted forward by 1 position, as defined by positions. # Note that you can ensure the result remains within 0-26 using result % 27 # Store this as encoded_message. CIPHER = 1 encoded = {alphabet[i]: ((i + CIPHER) % length) for i in range(length)} # encoded = {((i + key) % length): alphabet[i] for i in range(27)} print(encoded) message = "hi my name is caesar" encoded_message = " " for letter in message: encoded_message = alphabet[encoded[letter]] print(encoded_message, end = "") print() # print((positions[letter] + CIPHER) % length) # Exercise 4 # Define a function encoding that takes a message as input as well as an int # encryption key key to encode a message with the Caesar cipher by shifting # each letter in message by key positions. # Your function should return a string consisting of these encoded letters. # Use encoding to encode message using key = 3 and save the result as encoded_ # message. Print encoded_message. def encoding(message, key): encoded = {alphabet[i]: ((i + key) % length) for i in range(length)} encoded_message = "" for letter in message: encoded_message += alphabet[encoded[letter]] return encoded_message key = 3 encoded_message = encoding(message, key) print(encoded_message) # Exercise 5 # Use encoding to decode encoded_message. # Store your encoded message as decoded_message. # Print decoded_message. Does this recover your original message? new_key = -3 decoded_message = encoding(encoded_message, new_key) print(decoded_message) # Yes recovers original message
true
df52a481253b1fed164103ed78dd54d50ab40916
Auubz/Alg2
/Semester 1/Practice/Review 2/For loops.py
1,197
4.3125
4
list1 = ["champlain","dawson", "vanier"] for schools in list1: print (schools.upper()) list = [] #======================================= for x in range (1,11): power = x**2 list.append(power) print(list) #This code can also be simplified into: for x in range (1,11): list.append(x**2) print(list) var1 = [x**2 for x in range (1,11)] #This is read: x is taken to the power of two for all of the variables in the range 1 to 11 print(var1) #======================================= numbers = [1,2,3,4,5,6,7,8,9] print(min(numbers)) max(numbers) sum(numbers) #================================== for s in range (1,20,2): print (s) for s in range(3,30,3): print (s) var1 = [x**3 for x in range(1,11)] print(var1) def book(pet_name,type="dog"): print("I have a " + pet_name + " his name is " + type) book("fuck you") #=========================================== def make_shirt(text,size = "large"): print("The shirt will print " + text + " in size " + size) make_shirt(str(12),"Fuck You") make_shirt(text="haha") #================================================== def pet(pm, at=dog): pet(at=cat) #=================================================
true
0373cc75382639fa0703733c07bb524f2d9b0577
PDXCodeGuildJan/CourseAssignments
/die.py
1,568
4.40625
4
from random import randint # Create a die function that returns a random number, as if # the user rolled a die. def die(): roll = randint(1, 6) print(roll) # Make a function called custom_die that takes a range # and print a random number in that range. def custom_die(num1, num2): roll = randint(num1, num2) print("{} {}".format(roll, "Critical Miss!" if roll == min else "Critical Hit!" if roll == max else "")) if roll == num1: print("{} Critical Fail!".format(roll)) elif roll == num2: print("{r} Critical Hit!".format(r=roll)) else: print(roll) "{1} is {0} and is from {2}".format(name, age, place) # Determine if roll is the max possible result # or if roll is the min possible result # This will also need to change some ;) print(roll) def main(): print("Welcome to Die Roller. Enter q to exit.") entree = "" # Wrap the core logic of the function in a while loop, # so that it keeps asking to roll, until we exit. while entree != "q": # Ask the user how many dice to roll entree = input("How many Dice rolls do you want to roll? ") if entree.lower() == "q": # Exit the program exit() total_rolls = int(entree) #Find out how big the Dice are entree = input("How many sides on the Dice? ") if entree == "q": #Exit the program exit() max_num = int(entree) # Roll that many dice for something in range(0, total_rolls): custom_die(1, max_num) main()
true
67ca6df11d6875330cd8058a1e6f26eeea0e4b86
jessicabelfiore/python-exercises
/Chapter14/Exercise1403.py
1,681
4.46875
4
""" Exercise 14.3 If you download my solution to Exercise 12.4 from http://thinkpython.com/code/anagram_sets.py, you'll see that it creates a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters. For example, 'opst' maps to the list ['opts', 'post', 'pots', 'spot', 'stop', 'tops']. Write a module that imports anagram_sets and provides two new functions: store_anagrams should store the anagram dictionary in a "shelf;" read_anagrams should look up a word and return a list of its anagrams. """ import shelve import sys from Exercise1204 import * # Note: This was mostly taken from the solution provide by the author. # For this exercise, little preliminary explanation was given. # I felt I could learn more by studying and implementing the author's solution. def store_anagrams(filename, d): """Stores the anagrams in d on a shelf. filename: filename of shelf, formatted as a string d: dictionary that maps strings to a list of anagrams """ shelf = shelve.open(filename, "c") for word, anagrams in d.iteritems(): shelf[word] = anagrams shelf.close() def read_anagrams(filename, word): """Looks up a word in a shelf and returns a list of its anagrams. filename: string file name of shelf word: word to look up """ shelf = shelve.open(filename) base = baseline(word) try: return shelf[base] except KeyError: return [] dictionary_of_anagrams = anagram_maker("words.txt") store_anagrams("shelved_anagrams.txt", dictionary_of_anagrams) print read_anagrams("shelved_anagrams.txt", "converse")
true
fae44e37d857cd93efb5a0c87e2ff9bd7f3f41e5
jessicabelfiore/python-exercises
/Chapter11/Exercise1103.py
503
4.21875
4
""" Exercise 11.3 Dictionaries have a method called "keys" that returns the keys of the dictionary, in no particular order, as a list. Modify print_hist (below) to print the keys and their values in alphabetical order. def print_hist(h): for c in h: print c, h[c] """ def histogram(s): d = dict() for c in s: d[c] = d.get(c, 0) + 1 return d def print_hist(h): t = h.keys() t.sort() return t s = "brontosaurus" print print_hist(histogram(s))
true
3bdcfc225a2907a2fadc2db0e8d40b10e5065850
jessicabelfiore/python-exercises
/Chapter08/Exercise0805.py
822
4.125
4
""" Exercise 8.5. The following program counts the number of times the letter a appears in a string: word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print count This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result--the total number of a's. Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. """ def count(s, l): count = 0 for char in s: if char == l: count += 1 print count return count count("happy birthday to you.", "p") count("happy birthday to you.", "o") count("happy birthday to you.", "x")
true
b76971b18afa7be3ae0e1b1db655816e4630b41f
jessicabelfiore/python-exercises
/Chapter11/Exercise1110.py
802
4.15625
4
""" Exercise 11.10. Two words are "rotate pairs" if you can rotate one of them and get the other (see rotate_word in Exercise 8.12). Write a program that reads a wordlist and finds all the rotate pairs. def rotate_word(s, n): new = "" for c in s: new += chr(ord(c) + n) return new """ def rotate_pair_finder(wordlist, rotation): d = {} fin = open(wordlist) for line in fin: word = line.strip() d[word] = None newlist = [] for key in d: newword = "" for char in key: newword += chr(ord(char) + rotation) if newword in d: newlist += [(key, newword)] return newlist print rotate_pair_finder("words.txt", 13) print rotate_pair_finder("words.txt", 1)
true
c4a074329d87ecbe1e4cf0ad661071fec674a4dd
jessicabelfiore/python-exercises
/rot13_coder_decoder.py
1,574
4.5625
5
""" ROT13 is a weak form of encryption that involves "rotating" each letter in a word by 13 places. To rotate a letter means to shift it through the alphabet, wrapping around to the beginning if necessary, so 'A' shifted by 3 is 'D' and 'Z' shifted by 1 is 'A'. Write a function called rotate_word that takes a string and an integer as parameters, and that returns a new string that contains the letters from the original string "rotated" by the given amount. For example, "cheer" rotated by 7 is "jolly" and "melon" rotated by -10 is "cubed". You might want to sue the built-in functions 'ord', which convernts a character to a numeric code, and 'chr', which converts numeric codes to characters. Potentially offensive jokes on the Internet are sometimes encoded in ROT13. If you are not easily offended, find and decode some of them. """ import string def rotate_word(s, i): encrypted = [] for c in s: if c.islower(): encrypted += string.lowercase[((string.lowercase).find(c) + i) % 26] elif c.isupper(): encrypted += string.uppercase[((string.uppercase).find(c) + i) % 26] else: encrypted += c newstring = ''.join(encrypted) print newstring def rot13_encoder(s): print rotate_word(s, 13) def rot13_decoder(s): print rotate_word(s, -13) # rotate_word("CHEERCHEER#$@%%!!!", 7) # rot13_encoder("In the elevators, the extrovert looks at the OTHER guy's # shoes.") # rot13_decoder("Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf.")
true
ac27e00d70155ab42d9da1a66a0b34cd2e5605a6
EdCarlosBicudo/UH-Data_analysis_with_Python
/hy-data-analysis-with-python-summer-2021/part04-e02_powers_of_series/src/powers_of_series.py
294
4.25
4
import pandas as pd def powers_of_series(s, k): df = pd.DataFrame(s, columns=[1]) for i in range(2, k+1): df[i] = df[1] ** i return df def main(): s = pd.Series([1,2,3,4], index=list("abcd")) print(powers_of_series(s, 3)) if __name__ == "__main__": main()
false
e6a1ad3fdad8688aa4f2cc81609c9e74e65c4f44
ksimonton/Python-Chapter03
/Python Chapter 3 Exercise 1.py
397
4.1875
4
#Katelyn Simonton - Python Chapter 3 Exercise 1 - 2/23/2018 #Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours #worked above 40 hours. #Enter Hours: 45 #Enter Rate: 10 #Pay: 475.0 hours = int(input("Enter Hours: ")) rate= float(input("Enter Rate: ")) hourly = float(int(hours) *1.5) pay = float(int(hourly *rate)) print ("Pay: " + str(pay))
true
e0f7d4468e5e0a4bd3cd5370329fca075d49bf04
zuigehulu/AID1811
/pbase/day04/code/text4.py
281
4.125
4
# 输出9行内容 # 第1行输出1 # 第2行输出12 # 第3行输出123 # 以此类推,第9行输出123456789 i = 1 while i <= 9: j = 1 while j <= i: print(j,end = " ") j += 1 else: print() i += 1
false
1d8bb5199b4c1d320afc4ed3ba84114f5b9908af
zuigehulu/AID1811
/pbase/day06/jiangyi/day06/day05_exercise/tree.py
714
4.15625
4
# 3. 输入一个整数,此整数代表树干的高度,打印一棵如下形状的圣 # 诞树 # 如: # 输入: 2 # 打印: # * # *** # * # * # 如: # 输入: 3 # 打印: # * # *** # ***** # * # * # * n = int(input("请输入树干的高度: ")) # 此方法在星号的左侧填入相应空格来实现 # 1. 先打印树叶部分 for line in range(1, n + 1): blank = n - line # 计算左侧空格的个数 star = 2 * line - 1 # 计算星号的个数 print(' ' * blank + '*' * star) # 树干部分: blank = n - 1 # 计算树干左侧的空格个数 for line in range(1, n + 1): print(" " * blank + '*')
false
7ea66b62a2082bd95a92dadccbee10299cae531c
zuigehulu/AID1811
/pbase/day04/jiangyi/day04/exercise/right_align2.py
918
4.28125
4
# 练习: # 输入三行文字,让这三行文字依次以20个字符的宽度右对齐输出 # 如: # 请输入第1行: hello world # 请输入第2行: abcd # 请输入第3行: a # 输出结果为: # hello world # abcd # a # 做完上面的题后再思考: # 能否以最长的字符串长度进行右对齐显示(左侧填充空格) a = input("请输入第1行: ") b = input("请输入第2行: ") c = input("请输入第3行: ") max_length = len(a) if len(b) > max_length: max_length = len(b) if len(c) > max_length: max_length = len(c) # 方法1 # print(' ' * (max_length-len(a)) + a) # print(' ' * (max_length-len(b)) + b) # print(' ' * (max_length-len(c)) + c) # 方法2 fmt = '%' + str(max_length) + 's' # '%8s' print(fmt % a) print(fmt % b) print(fmt % c) # print("%20s" % a) # print("%20s" % b) # print("%20s" % c)
false
439fb9a27138bf7e9b88741ae6ee34fca445470f
GaryClarke/learn-python
/unpacking.py
377
4.125
4
# tuple unpacking enumerated_list = [(0, 'learn'), (1, 'Python'), (2, 'code')] # for a, b in enumerated_list: # print(b) # loop through enumerated list and unpack # without using a loop phrase = ['learn', 'Python', 'code'] # show that can also be done with lists for item in phrase: print(item) # must use the correct number of vars...therefore need to know length
true
725bef09798a4dc2443ae61acf4daad523f7f0c2
GaryClarke/learn-python
/print-formatting.py
512
4.1875
4
# show the concatenation limitation first_name = 'Gary' last_name = 'Clarke' city = 'Manchester' country = 'UK' str = 'My name is ' + first_name + ' ' + last_name + ' and I live in ' + city + ', ' + country # show the .format() method / string interpolation # indexing # repeating indexes # using named assignments # print('{fn} {ln}, {co}: {ci}, {co}' # .format(fn=first_name, ln=last_name, co=country, ci=city)) # f strings print(f'My name is {first_name} {last_name} and I live in {city}, {country}')
false
fb3a9bc78cf99b1bd27f7b6ae8b6e53743e83e4c
GaryClarke/learn-python
/for-loops-intro.py
472
4.3125
4
# iterables and loops # problem with individually accessing items - try multiplying items numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # how it can be done with a for loop # for x in numbers: # print(x * 2) # a string can be looped over because it is iterable # for letter in 'Gary Clarke Tech': # print(letter) # don't need to use the variable # the range function # for _ in range(100): # print(_ * 3) # list function new_list = list(range(100)) print(new_list[34])
true
77b2a9abae7cde99afc35a29f5c5a0dad9d24455
GaryClarke/learn-python
/dictionaries-intro.py
615
4.1875
4
# limitation of lists # user = [ # 'Gary', # 'Clarke', # '22 Acacia Avenue, London, UK', # 'GBP', # 44123456789 # ] # create a dictionary {k:v} user = { 'first_name': 'Gary', 'last_name': 'Clarke', 'address': { 'street_address': '22 Acacia Avenue', 'city': 'London', 'country': 'UK' }, 'currency': 'GBP', 'phone': 44123456789 } # print dictionary # access an item in dictionary # explain data types user['phone'] = 333 # print(user) # add a new key to existing # update a value in existing # show dictionary method(s) print(user.values())
false
1b5061dcb3cb9cdeedde0ca16db538aa8b0b44f8
GaryClarke/learn-python
/lists-program-challenge.py
609
4.28125
4
star_ratings = [4, 2, 3, 5, 4, 1, 3, 4, 5, 1, 3] # 1. Using an input function, ask the user to # enter a star rating (1 - 5) # 2. Store the user input value in a variable user_rating = int(input('Please enter a star rating (1-5): ')) # 3. Append the rating to the star_ratings list star_ratings.append(user_rating) # 4. Calculate the average of the LAST 5 ratings in star_ratings last_5 = star_ratings[-5:] # 5. Store this in a variable average_rating = sum(last_5) / len(last_5) # 6. Print the value to the console / terminal print(average_rating) # 7. Test your work # 8. Fix any errors (debug) in your code
true
59ef66a3a39ab0ec1a5be7f16b6f4950ec4d4f6f
excelincode/Excelino-2101684626
/Random/Palindrome_01.py
1,465
4.28125
4
#This is a program to check whether your word is a palindrome or not print ("Welcome to the Palindrome checker code ver0.2a!") no = ('no') ye = ('yes') def main(): while True: Pal = input("\nPlease input your word: ").lower() if str(Pal) == ''.join(reversed(Pal)): print("Yes! the word of ' " +Pal , "' is a Palindrome! :)") rep = input("Don't you still have other word to check on, do you? ( Yes / No )").lower() if rep == ye: main() if rep == no: return else: print("Please, answer the question with 'Yes' or 'No'!") else: print("Unfortunately! the word of ' " +Pal , "' is NOT a Palindrome! :(") rep = input("Don't you still have other word to check on, do you? ( Yes / No )").lower() if rep == ye: main() if rep == no: return else: print("Please, answer the question with 'Yes' or 'No'!") main() print("\n-------------------------------") print("Thank you for using this program! Have a nice day! :)") input("\nPress 'ENTER' to Exit!") #Created in 19/9/17 By Excelino.Fernando #Updated to version 0.2a in 21/9/17 By Excelino.Fernando ''' #0.1 just a code to run a Palindrome word for a time #0.2a added some User Interface to let user whether to continue with other word or not, still unstable with some issues '''
true
cdcacc9b15cc5d1db8ba7f8d750c5a47ba2aa43f
soobun/Python_Exercise
/CH_3/3_7.py
1,675
4.1875
4
# 3-7 缩减名单 :你刚得知新购买的餐桌无法及时送达,因此只能邀请两位嘉宾。 # 以完成练习3-6时编写的程序为基础,在程序末尾添加一行代码,打印一条你只能邀请两位嘉宾共进晚餐的消息。 # 使用pop() 不断地删除名单中的嘉宾,直到只有两位嘉宾为止。每次从名单中弹出一位嘉宾时,都打印一条消息,让该嘉宾知悉你很抱歉,无法邀请他来共进晚餐。 # 对于余下的两位嘉宾中的每一位,都打印一条消息,指出他依然在受邀人之列。 # 使用del 将最后两位嘉宾从名单中删除,让名单变成空的。打印该名单,核实程序结束时名单确实是空的。 names = ['Sam', 'Amy', 'Tom', 'Jerry'] print(names[0] + ', eat dinner with me.') print(names[1] + ', eat dinner with me.') print(names[2] + ', eat dinner with me.') print(names[3] + ', eat dinner with me.') print(names[3] + " can't eat dinner with me.") names[3] = 'Nephew' print(names[3] + ', eat dinner with me.') print('I found a bigger table!') names.insert(0, 'Sara') names.insert(3, 'Daming') names.append('Zac') print(names[0] + ', eat dinner with me.') print(names[1] + ', eat dinner with me.') print(names[2] + ', eat dinner with me.') print(names[3] + ', eat dinner with me.') print(names[4] + ', eat dinner with me.') print(names[5] + ', eat dinner with me.') print('Today, only two person can eat with me.') print(names.pop() + ', sorry.') print(names.pop() + ', sorry.') print(names.pop() + ', sorry.') print(names.pop() + ', sorry.') print('Welcome, ' + names[0]) print('Welcome, ' + names[1]) del names[0] del names[1] print(names)
false
b658b3c7416d0aa57877c0b8b13d7740598774d8
soobun/Python_Exercise
/CH_3/3_8.py
1,342
4.65625
5
# 3-8 放眼世界 :想出至少5个你渴望去旅游的地方。 # 将这些地方存储在一个列表中,并确保其中的元素不是按字母顺序排列的。 # 按原始排列顺序打印该列表。不要考虑输出是否整洁的问题,只管打印原始Python列表。 # 使用sorted() 按字母顺序打印这个列表,同时不要修改它。 # 再次打印该列表,核实排列顺序未变。 # 使用sorted() 按与字母顺序相反的顺序打印这个列表,同时不要修改它。 # 再次打印该列表,核实排列顺序未变。 # 使用reverse() 修改列表元素的排列顺序。打印该列表,核实排列顺序确实变了。 # 使用reverse() 再次修改列表元素的排列顺序。打印该列表,核实已恢复到原来的排列顺序。 # 使用sort() 修改该列表,使其元素按字母顺序排列。打印该列表,核实排列顺序确实变了。 # 使用sort() 修改该列表,使其元素按与字母顺序相反的顺序排列。打印该列表,核实排列顺序确实变了。 places = ['Macau', 'Hong Kong', 'Shanghai', 'New York'] print(places) print(sorted(places)) print(places) print(sorted(places,reverse=True)) print(places) places.reverse() print(places) places.reverse() print(places) places.sort() print(places) places.sort(reverse=True) print(places)
false
9fa4e294f1864a234d59706a90bf823e27e5981c
MaximusKorea/data_structure
/LinkedList/LinkedList3.py
2,131
4.21875
4
# LinkedList의 삭제원리 # 1. 삭제 대상이 되는 값이 head(맨처음 node)의 값인경우 # -> 해당 노드의 포인터값(다음 노드의 주소)을 변수 head에 저장해준다. # 2. 삭제 대상이 가운데에 있는 경우 # .... A - B - C ....... # -> A의 pointer에 C의 주소값을 저장하고 B를 삭제해준다. # 3. 삭제 대상이 마지막에 있는 경우 # ..........B - C # -> B의 pointer에 none을 저장하고 C를 삭제한다. class MakeNode: def __init__(self, data, pointer=None): self.data = data self.pointer = pointer class Node: def __init__(self,data): self.head = MakeNode(data) def add(self,data): if self.head == '': self.head = MakeNode(data) else: node = self.head while node.pointer: node = node.pointer node.pointer = MakeNode(data) def show(self): node = self.head while node: print(node.data) node = node.pointer def delete(self,data): if self.head == '': print("노드가 존재하지 않습니다.") return if self.head.data == data: temp = self.head self.head = self.head.pointer del temp else: node = self.head while node.pointer: if node.pointer.data == data: temp = node.pointer node.pointer = node.pointer.pointer del temp return else: node = node.pointer def search_node(self,data): node = self.head while node: if node.data == data: return node else: node = node.pointer LinkedList1 = Node(0) for new_data in range(1,10): LinkedList1.add(new_data) LinkedList1.show() LinkedList1.delete(3) print("------------------------------") LinkedList1.show() LinkedList1.delete(9) print("------------------------------") LinkedList1.show()
false
92329744dc7f0fe70271cf1d4f6bd8e3713706f9
rameshnataru1224/programs
/sorting_2.py
344
4.3125
4
""" list in the nested dictionary sorting """ stu_marks = [{"name": "siva", "marks": 100}, {"name": "rams", "marks": 20}, {"name": "reddy", "marks": 500}] # using sorted function it will sort the program # using lambda based on keys stu_marks = sorted(stu_marks, key=lambda l: l["marks"], reverse=False) print stu_marks
false
1db2d2806646fc7ff23203052778014bb1b85873
hsgonzaleo/ST0245-008
/Recursión/inversion.py
363
4.15625
4
# Este programa invierte una palabra o frase que asigna el usuario (Ejercicio 3). palabra = str(input("Ingrese una palabra o frase: ")) def invertir(palabra): if len(palabra) == 1: # Caso base. return palabra else: return palabra[len(palabra) - 1] + invertir(palabra[:len(palabra) - 1]) print("Inversión: ", invertir(palabra))
false
4c8807378bd48ba685dc57ce8a762611f2a74d23
AbnerAbreu/bank-666
/sistema.py
1,263
4.21875
4
print('Bem-vindo ao Banco-666') nome = input('digite seu nome: ') idade = input('digite sua idade: ') saldo = float(input('digite seu saldo: ')) print('\n digite(1) para saque \n digite(2) para depósito \n digite(3) para empréstimo \n digite(4) para visualizar informações \n digite (qualquer outro caracter) para sair') operação = int(input('digite o numero da operação: ')) if(operação == 1): saque() elif(operação == 2): deposito() elif(operação == 3): emprestimo() def saque(saque1): valorsaque = float(input('digite o valor do saque: ')) if valorsaque > 1000 and saldo < valorsaque: print('impossivel efetuar saque') else: print('transição realizada com sucesso') print(saldo - valorsaque) def deposito(deposito2): valordeposito = float(input('digite o valor do deposito: ')) if valordeposito > 5000: print('impossivel efetuar deposito') else: print(valordeposito + saldo) def emprestimo(emprestimoss): valoremprestimo = float(input('Digite o valor do Emprestimo: ')) if valoremprestimo >= 2000 or valoremprestimo <= 15 * saldo: print(valoremprestimo + saldo) else: print('Emprestimo recusado') saque() deposito() emprestimo()
false
a6a263bc03049e902b7f71390e93b88df51fba37
PythonCHB/PythonIntroClass
/week-10/code/sqlite_example.py
2,174
4.53125
5
#!/usr/bin/env python """ Example of using sqlite3 module for a relational database """ import sqlite3, os db_filename = "add_book_data.sqlite" # any extension will do -- *.db and *.sqlite are common # get the data from the py file from add_book_data_flat import AddressBook # if the db already exists -- delete it: try: os.remove(db_filename) except OSError: print "no db file there yet" # create a connection to an sqlite db file: conn = sqlite3.connect(db_filename) # NOTE: you can do an in-memory version: #conn = sqlite3.connect(":memory:") # establish the schema (single table in this case...): # Create a table conn.execute("""CREATE TABLE addresses ( first_name text, last_name text, address_line_1 text, address_line_2 text, address_city text, address_state text, address_zip text, email text, home_phone text, office_phone text, cell_phone text )""" ) conn.commit() # get the fields from the data: fields = AddressBook[0].keys() # order matters, so we sort to make sure they will always be in the same order fields.sort() # add some data: # get a cursor: c = conn.cursor() for person in AddressBook: # Insert a row of data row = [ person[field] for field in fields ] row = "','".join(row) sql = "INSERT INTO addresses VALUES ('%s')"%row #print sql c.execute(sql) # Save (commit) the changes and close the connection conn.commit() conn.close() ### see if we can re-load it conn = sqlite3.connect(db_filename) sql = "SELECT * FROM addresses" # no need for a cursor if a single sql statement needs to be run result = conn.execute(sql) ## put it all back in a list of dicts AddressBook2 = [] for row in result: d = dict(zip(fields, row)) AddressBook2.append(d) if AddressBook2 == AddressBook: print "the version pulled from sqlite is the same as the original" else: print "they don't match!" conn.close() ## now do it with the non-flat version -- with a proper schema # left as an exercise for the reader
true
5c38dc868d57c773ee0964c00f06db9f9cf30bbb
walterfan/snippets
/python/kids/name2.py
220
4.21875
4
print "please input your name" name = raw_input() if name == "fym": print "hello", name, ",you are father" elif name == "cf": print "hello", name, ",you are mother" else: print "hello", name, ",you are baby"
false
103982d4233775d3c0857170d0a004c11f66348d
akshat-max/Udacity-DSA-programs
/project2/p2_file_recursion.py
1,073
4.34375
4
import os def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ if path[-2:] == suffix: print(path) else: if os.path.isdir(path): for file in os.listdir(path): find_files(suffix, os.path.join(path, file)) # Test Cases find_files(".c", "./testdir") print("--------------------") find_files(".h", "./testdir") print("--------------------") find_files(".z", "./testdir") # expected output: # ./testdir/subdir3/subsubdir1/b.c # ./testdir/t1.c # ./testdir/subdir5/a.c # ./testdir/subdir1/a.c # -------------------- # ./testdir/subdir3/subsubdir1/b.h # ./testdir/subdir5/a.h # ./testdir/t1.h # ./testdir/subdir1/a.h # --------------------
true
8dcb2f2b1ac736a9947c630746c4e00034f5ee43
bobroxq/Simple-Python-Projects
/Calculating the Tip/main.py
1,435
4.15625
4
def calculate_tip(): bill = float(input("How much is your total bill? ")) percent = ((float(input("How much would you like to tip? (Enter 10, 15, or 18 percent): "))) / 100) tip = bill * percent print(f"You're tip is ${round(tip, 2)}") def even_bill_split(): bill = float(input("How much is your total bill? ")) percent = ((float(input("How much would you like to tip? (Enter 10, 15, or 18 percent): "))) / 100) total = bill + (bill * percent) real_total = round(total, 2) people = int(input("How many people are in your party? ")) share = real_total / people print(f"Each person should pay ${round(share, 2)}") def uneven_bill_split(): bill = float(input("How much is your total bill? ")) percent = ((float(input("How much would you like to tip? (Enter 10, 15, or 18 percent): "))) / 100) total = bill + (bill * percent) real_total = round(total, 2) people = int(input("How many people are in your party? ")) for i in range(1, people + 1): pp = (float(input(f"What percentage of the bill would person {i} like to pay? "))) / 100 share = real_total * pp print(f"Person {i} should pay ${round(share, 2)}") task_dct = {'1':calculate_tip, '2':even_bill_split, '3':uneven_bill_split} task = input("""What would you like to do? 1. Calculate the tip 2. Split the bill evenly 3. Split the bill unevenly Enter your selection: """) task_dct[task]()
false
b612ed08bedc8f657dc30404099229234392c3f6
HenaChris/python-
/模块、类和实例_test.py
2,011
4.21875
4
####模块 print('恋习Python') def main(): print('恋习Python') #在导入该模块到其他模块时,该部分不执行,可以用来测试 if __name__ == '__main__': main() print('跟着菜鸟分析,练习Python越练越恋') ####类 #括号里面填写继承了哪个类,object表示继承了object类 class Student(object): pass bart = Student() print(1,bart) '''输出:<__main__.Student object at 0x000001AF22335320>''' #自由绑定实例变量的属性 bart.name = 'Bart Simpson' print(2,bart.name) #__init__,创建实例的时候要传参 class Student(object): def __init__(self,name,score): self.name = name self.score = score bart = Student('Bart Simpson',59) print(3,bart) print(4,bart.name,bart.score) #数据的封装,用类的方法去访问数据 class Student(object): def __init__(self,name,score): self.name = name self.score = score def print_score(self): print("%s:%s"%(self.name,self.score)) def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson',59) bart.print_score() print(bart.get_grade()) ####访问限制 #将gender设置为私有这样外部就没法通过bart.gender = 'female'来修改属性了,只能通过类的方法去修改 #也无法访问到私有属性。只能通过类的方法去访问。 class Student(object): def __init__(self, name, gender): self.name = name self.__gender = gender def get_gender(self): print(self.__gender) def set_gender(self,gender): self.__gender = gender bart = Student('Bart', 'male') if bart.get_gender() != 'male': print('测试失败!') else: bart.set_gender('female') if bart.get_gender() != 'female': print('测试失败!') else: print('测试成功!')
false
5fee0ec9f84c9de60cda06c1493281dae486f3e9
pepito-alpha/Zion
/python/matriz.py
761
4.25
4
#How make matrix M = [] N = [] for i in range(5): M.append([0]*5) for i in range(5): for j in range(5): M[i][j] = j**(i+1) print "M is square matrix of size 5 x 5" for i in range(5): N=[] for j in range(5): N.append(M[i][j]) print N print "Would you like choose number of matrix?" print "1) yes\n 2) No" quest = input ("Choose number\n") if quest == 1: print "You only typing row and column" row = input ("Write row (remember 1 to 5):\n") column = input ("Write column:\n") print row print column print "The position has number:\n" print M[(row -1)][(column -1)] elif quest == 2: print "Thank you, good bye" else: print "Are you Stupid? only 1 or 2, jajajja" print M
true
d922160d1922cbb91bea9020a9f4ccd300ff5cc6
itaishopen/Intro-to-python
/ex08/game.py
2,670
4.15625
4
############################################################ # Imports ############################################################ import game_helper as gh from car import Car, Direction from board import Board import random ############################################################ # Class definition ############################################################ class Game: """ A class representing a rush hour game. A game is composed of cars that are located on a square board and a user which tries to move them in a way that will allow the red car to get out through the exit """ def __init__(self, board): """ Initialize a new Game object. :param board: An object of type board """ self._board = board print_board = self._board print('\n'.join(print_board)) red_car_board = r_car(print_board) print('\n'.join(red_car_board)) self._board = red_car_board def __single_turn(self): """ Note - this function is here to guide you and it is *not mandatory* to implement it. The logic defined by this function must be implemented but if you wish to do so in another function (or some other functions) it is ok. The function runs one round of the game : 1. Print board to the screen 2. Get user's input of: what color car to move, and what direction to move it. 2.a. Check the the input is valid. If not, print an error message and return to step 2. 2. Move car according to user's input. If movement failed (trying to move out of board etc.), return to step 2. 3. Report to the user the result of current round () """ color_input = input(gh.MESSAGE_GET_COLOR_INPUT) def play(self): """ The main driver of the Game. Manages the game until completion. :return: None """ # implement your code here (and then delete the next line - 'pass') pass ############################################################ # An example usage of the game ############################################################ def main(): size1 = 6 brd = Board.exit_board1(Board(cars = Car, exit_board = None, size = size1)) brd_list = '\n'.join(brd) print(brd_list) while not done(brd_list): if __name__=="__main__": size1 = 6 board = Board(cars = Car, exit_board = exit_board1(size1) , size = size1) game = Game(board) game.play()
true
15dd7c0443bbaf04b48c6b445ab5d7d93a88e27e
monooso/udacity-nd256-project-three
/problem_1.py
1,299
4.375
4
def sqrt(target): """ Find the square root of the given number If the square root is not an integer, the next lowest integer is returned. If the square root cannot be determined, None is returned. :param target: The square :return: int or None """ # Explicitly handle the edge-cases here if target < 0: return None if target <= 1: return target lowest, highest = 2, target // 2 while lowest <= highest: candidate = ((highest - lowest) // 2) + lowest sq_candidate = candidate * candidate if sq_candidate == target: return candidate if sq_candidate > target: highest = candidate - 1 else: # If the next largest number squared is greater than the target, return the current candidate sq_candidate_plus = (candidate + 1) * (candidate + 1) if sq_candidate_plus > target: return candidate lowest = candidate + 1 # If we got this far, all hope is lost return None assert 2 == sqrt(4) assert 3 == sqrt(9) assert 1111 == sqrt(1_234_567) # A non-integer answer should return the next lowest integer assert 5 == sqrt(27) # Edge cases assert None is sqrt(-1) assert 0 == sqrt(0) assert 1 == sqrt(1)
true
e348cb80fc87f8f33911fb8ea993aa3f1f0e5084
yaowenqiang/lpthw
/exc5_more_variables_and_printing.py
702
4.15625
4
my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 100 # lbs my_eyes = 'Blue' my_teath = 'White' my_hair = 'Brown' print(f"Let's talk about {my_name}.") # not work on python 2 f stand for format print(f"He's {my_height} inches tall.") print("He's {my_height} inches tall.") # won't print the variable print(f"He's {my_weight} pounds heavy.") print(f"Actually that's not too heavy.") print(f"He's got {my_eyes} eyes and {my_hair} hair.") print(f"His teach are usually {my_teath} depending on the coffee.") # this line is tricky,try to get it exactly right total = my_age + my_height + my_weight print(f"If I add {my_age}, {my_height}, and {my_weight} I got {total}")
true
5cc9f3072260976692ff127317093d9adfd0f96c
tylerstjacques/SchoolPrograms
/Midterm Problem 1 2nd Function.py
738
4.125
4
def read_in_answer(filename): """ Read in and return a single number from a file, the answer to the guessing game """ with open(filename) as fp: answer = int(fp.readline()) return answer def get_a_guess(): """ prompt the user for a guess and read it in and return it""" guess = int(input('Make a guess: ')) return guess def evaluate_a_guess(guess, answer): """ Return true if guess equals the answer, false otherwise. Also print out "right!" if the guess is correct, "too low!" if guess is too low, or "too high!" if guess is too high. """ if guess == answer: print('right!') elif guess < answer: print('too low!') else: print('too high!')
true
52e8ec6a258d01df92fe4c02a867361112f2387c
tylerstjacques/SchoolPrograms
/Exam Review.2.py
252
4.1875
4
def getinput(): user_input = int(input('enter an integer between 1 and 10, inclusive')) while user_input < 1 or user_input > 10: user_input = int(input('enter an integer between 1 and 10, inclusive')) print(user_input) getinput()
true
93e6008c1a4dd63457f4285a72d8337e95cf0672
NathanHess6/molecool
/molecool/measure.py
1,016
4.375
4
# have to import because you need it! import numpy as np def calculate_distance(pointA, pointB): """ This function calculates the distance between two points. Parameters ---------- pointA, pointB: np.ndarray The coordinates of each point. Returns ------- distance : float The distance between two points. Examples -------- >>> r1 = np.array([0,0,0]) >>> r2 = np.array([3,0,0]) >>> calculate_distance(r1,r2) 3.0 """ dist_vec = (pointA - pointB) distance = np.linalg.norm(dist_vec) return distance def calculate_angle(pointA, pointB, pointC, degrees = False): # Calculate the angle between three points. Answer is given in radians by default, but can be given in degrees # by setting degrees = True AB = pointB - pointA BC = pointB - pointC theta = np.arccos(np.dot(AB, BC) / (np.linalg.norm(AB) * np.linalg.norm(BC))) if degrees: return np.degrees(theta) else: return theta
true
a78c1ee5061058be2001d55290ad10e463f87f44
RoyalTbaby/Learner
/Homework 5.1.py
1,271
4.21875
4
""" Написать программу, в которой вводятся два операнда Х и Y и знак операции sign (+, –, /, *). Вычислить результат Z в зависимости от знака. Предусмотреть реакции на возможный неверный знак операции, а также на ввод Y=0 при делении. Организовать возможность многократных вычислений без перезагрузки программа (т.е. построить бесконечный цикл). В качестве символа прекращения вычислений принять ‘0’ (т.е. sign='0'). """ while True: x = int(input("Enter X: ")) y = int(input("Enter Y: ")) sign = input("Enter sign (+, -, *, /) ") if sign == "+": z = x + y elif sign == "-": z = x - y elif sign == "*": z = x * y elif sign == "/": if y == 0: print("The division by 0 is invalid") continue z = x / y elif sign == 0: print("Finish - you're done!") break else: print("Invalid action") continue print(f'The result is {z}')
false
11a63be4d7b9958913cd2f64d3cb40fab54ba0c9
wumbovii/senior_projects
/proj3-1/tests/correct3/.svn/text-base/list1.py.svn-base
2,394
4.3125
4
#does a list work? x = ["a","b","c"] print x #basic access y = x[0] print y y = x[1] print y y = x[2] print y #access to negative indicies y = x[-3] print y y = x[-2] print y y = x[-1] print y #assignment to selections x[1] = "B" x[0] = "A" x[2] = "C" print x #assignment to negatively indexed selections x[-1] = "c" x[-2] = "b" x[-3] = "a" print x #slicing print x[-100:100] print x[-3:-1] print x[0:-2] print x[3:2] print x[123:-33] #selection nesting z = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print z[0] print z[0][0] #does a list work? #j = ("a","b","c") j = ["a", "b", "c"] print j #basic access k = j[0] print k k = j[1] print k k = j[2] print k #access to negative indicies k = j[-3] print k k = j[-2] print k k = j[-1] print k #slicing print j[-100:100] print j[-3:-1] print j[0:-2] print j[3:2] print j[123:-33] #selection nesting b = ((True, False, False), (True, True, False), (False, True, True)) #do dicts work? d = {"a":True, "b": False, "c": True, "d": False} print d #access e = d["a"] print e e = d["b"] print e e = d["c"] print e e = d["d"] print e print "ALL FALSE NOW" #mutation d["a"] = False d["c"] = False print d #addition d["e"] = False print d #print access print d["e"] #dict-ception n = {1:{3:{4:5}}, 2:{5:{2:6}}, 3:{5:{6:3}}} print n print n[3][5] print n[3][5][6] #does a string work? w = "abc" print w #basic access a = w[0] print a a = w[1] print a a = w[2] print a #access to negative indicies a = w[-3] print a a = w[-2] print a a = w[-1] print a #slicing print w[-100:100] print w[-3:-1] print w[0:-2] print w[3:2] print w[123:-33] #binop on list m = [1,2,3] + [1,2,3] print m #another list test l = ["neow", "moew", "opp"] print l #lsit5 print [1,2] and [3,4] print [1,2] and [3,4] #other misc data structure tests mtv = ["Snooki", "Pauly D", "Vinny", "Mike", "JWoWW"] print "Is Jersey Shore a good show?\n" print ("Snooki" not in mtv) xc = [1,2,3,4,5,6,7,8,9,10] print xc[3:7] xf = "chickenshnificent" print xf[3:8] xa = [1,2,3,4,5,6] print xa print "meow" ewx = [[1],[2],[3]] ewx[0][0] = 9001 print ewx fewa = [["meow", "meow", "meow"], ["rawr", "rawr", "rawr"], ["1"]] fewa[0][1] = "9001" print fewa fewa[1][0] = "9001" print fewa print fewa[2][0]
false
65e48aafc050d2f08cfdb13f0743a7e7ceeef9a4
1bhavesh1/Python-practice-programs
/search.py
479
4.21875
4
# write a python program for search an element using linear search ; n=int(input('enter number of elements you want : ')) a=[n] print('enter elements : ') for i in range(0,n): n1=int(input()) a.append(n1) key=int(input('enter element to search : ')) l=len(a) loc=-1 for i in range(0,l-1): if key==a[i]: loc=i break if loc>=0: print('element is found at location : %i'%loc) else: print('element does not exist !! ')
true
7da6ced4c2c71860736b9605419e412e98af0cfe
1bhavesh1/Python-practice-programs
/search 2.py
714
4.1875
4
# write a program for binary search ; def binsearch(a,low,high,key): if high>=1: mid = (low+high)/2 mid=int(mid) if a[mid]==key: return mid elif a[mid]>key: return binsearch(a,low,mid-1,key) else: return binsearch(a,mid+1,high,key) else: return -1 n=int(input('enter how many elements you want : ')) a=[n] print('enter elements : ') for i in range(0,n): n1=int(input()) a.append(n1) key=int(input('enter element to search for : ')) l=len(a) result=binsearch(a,0,l-1,key) if result != -1: print("element is found at location %d"%result) else: print("element is not found !! ")
false
20dd6fc682c95af3d2e09d0342dd45c754f99060
1bhavesh1/Python-practice-programs
/palindrome.py
207
4.15625
4
print('enter a number : ') n=int(input()) temp=n s=0; while n>0: r=n%10; s=(s*10)+r n=n//10; if temp==s: print('number is palindrome') else: print("number is not palindrome")
false
8173fe9acbbfb4e374644e66dc6b4358f127d39b
1saac-dev/Hello
/main.py
417
4.21875
4
calc_to_unit = 24 name_of_unit = "hours" def days_to_units(num_of_days): if num_of_days > 0: return f"{num_of_days} days are {num_of_days * calc_to_unit} {name_of_unit}" else: return "Please, enter a positive number." user_input = input("Hey user, enter a number of days.\n") user_input_number = int(user_input) calculated_value = days_to_units(user_input_number) print(calculated_value)
true
a3f9346105da8dde56e0a7240ff477a72ba1f0f0
kirigaine/Notes-and-Programs
/python/fibonacci-recursion.py
1,901
4.1875
4
""" ********************************************************* * * * Project Name: Recursive Fibonacci Sequence * * Author: github.com/kirigaine * * Description: A simple program to put in how many * * numbers of the Fibonacci Sequence you would like. * * Requirements: Python Standard Library (re) * * * ********************************************************* """ import re def main(): while True: # Prompt user, exit program if "-1" x = userPrompt() if x == -1: break print("------------------------------------------------------------") print(str(fibonacci(x))) print("------------------------------------------------------------\n") def userPrompt(): # Prompt user for nth number to print up to temp_nth = "" regex_passed = None # Accept only integers and negative one while not regex_passed: temp_nth = input("How many digits of the Fibonacci Sequence would you like (-1 to quit): ") regex_passed = re.search("^(([0-9]*)|(-1))$", temp_nth) if not regex_passed: print("Invalid integer. Please try again entering a positive integer (or -1 to quit).\n") return int(temp_nth) def fibonacci(x): # fibonacci(x) == fibonacci(x-1) + fibonacci(x-2) # ... # fibonacci(4) = fibonacci(3) + fibonacci(2) # fibonacci(3) = fibonacci(2) + fibonacci(1) # fibonacci(2) = 1 # fibonacci(1) = 0 if x is not None: if x==0: # If you request none, you get none! return None elif x==1: return 0 elif x==2: return 1 else: # print(f"{x-1} {x-2}") return(fibonacci(x-1) + fibonacci(x-2)) main()
true
6cd3a3c2c98d0b7a28b78af1660d05a0ea6df4a0
anjanimsp/PythonTUT1.0
/Python TUT/Recursion.py
431
4.25
4
def fact(n): """ It prints factorial of number using recursive approach """ if n==1: return 1 else: return (n*fact(n-1)) print(fact(5)) def fabnoci(n): """ It prints the fabnoci series of the given number using recursive approach """ if n ==1: return 0 elif n==2: return 1 else: return (fabnoci(n-1)+fabnoci(n-2)) print(fabnoci(6))
false
3cbf6986609e702af82d7864a5f168c7561b3d6c
Dgustavino/Python
/Taller_02/list&dict/listas.py
1,259
4.34375
4
lista_ejemplo_numeros = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,29] # " for each " dentro de un Obj Iterable for numero in lista_ejemplo_numeros: print(numero) # podemos recorrer listas por la instruccion [start:stop:step] print(lista_ejemplo_numeros[::-3]) # los indices negativos van en reversa print(lista_ejemplo_numeros[4]) # acceder por indice lista_ejemplo_numeros.append(5689) # append me ingresa un elemento al final de la lista # pop saca el ultimo elemento de la lista y lo devuelve print(lista_ejemplo_numeros.pop()) # index me da el indice del elemento print(lista_ejemplo_numeros.index('abc')) # constructor list() lista_normal = list() contador = 0 # como llenar una lista manualmente while contador < 10: lista_normal.append(0) contador=contador+1 varr='elemento' lista_normal[1]=varr # asigar valor al indice # reversa el objeto actual lista_normal.reverse() # copy devuelve una lista exactamente igual lista_reversada = lista_normal.copy() # devolvemos el objeto a su estado original lista_normal.reverse() # imprimimos las listas print(lista_normal,lista_reversada)
false
6165444cdd37ac295faf9601f96377a4a692fbe2
sm6412/Python-Files
/MantriSamira_assign2_problem2.py
2,132
4.4375
4
#Samira Mantri 2/3/16 section:3 MantriSamira_assign2_problem2.py #Print an opening statement print("This program will project how much you can earn by investing money in a high-yield account over a 3 month period.") print() #create an input asking for the initial investment and the projected annual interest rate initial_investment=float(input("To begin, enter how much money you would like to initially invest (i.e. 500): ")) interest_rate=float(input("Next, enter your projected annual interest rate. For example, enter 0.05 for 5%: ")) print() #print "calculating" print("------- Calculating -------") print() #Calculate the starting balance, interest, and ending balance for all three months. #Make sure to designate them as variables #month 1 starting_balance1=initial_investment format_starting_balance1=format(starting_balance1,">20,.2f") interest1=starting_balance1*(interest_rate/12) format_interest1=format(interest1,">21,.2f") ending_balance1=starting_balance1+interest1 format_ending_balance1=format(ending_balance1,">22,.2f") #month 2 starting_balance2=ending_balance1 format_starting_balance2=format(starting_balance2,">20,.2f") interest2=starting_balance2*(interest_rate/12) format_interest2=format(interest2,">21,.2f") ending_balance2=starting_balance2+interest2 format_ending_balance2=format(ending_balance2,">22,.2f") #month 3 starting_balance3=ending_balance2 format_starting_balance3=format(starting_balance3,">20,.2f") interest3=starting_balance3*(interest_rate/12) format_interest3=format(interest3,">21,.2f") ending_balance3=starting_balance3+interest3 format_ending_balance3=format(ending_balance3,">22,.2f") #format headers interest_header="Interest" format_interest_header=format(interest_header,">21s") ending_balance="Ending Balance" format_ending_header=format(ending_balance,">22s") #print results print("Month Starting Balance",format_interest_header,format_ending_header) print("1",format_starting_balance1,format_interest1,format_ending_balance1) print("2",format_starting_balance2,format_interest2,format_ending_balance2) print("3",format_starting_balance3,format_interest3,format_ending_balance3)
true
08ebd10dfc1cc46c0ddd88f1e2020e358c043290
sm6412/Python-Files
/MantriSamira_assign5_part3b.py
609
4.25
4
#Samira Mantri 3/10/16 section-3 MantriSamira_assign5_part3b.py #print that 1 is not a prime number print("1 is technically not a prime number.") #establish a loop to determine prime numbers #set range from 1 to 1000 for x in range(1,1001): #check whether each individual number is prime for y in range(2,x+1): #check to see if number is prime based on whether it equals y if x==y: print(x,"is a prime number!") #if the number is not prime there will be no remainders elif x%y==0: break
true
f51bce8f458a6dbf862707e1e73df2dc6d8bd4dd
seqwith/Python
/String_Format_Practice.py
1,007
4.25
4
# # Michael Winder # SEC290 Summer 2020 # July, 18, 2020 # Homework 2 # print('Automobile Fuel Cost Calculator') print('') print('This program may help you decide which car makes sense for you based on your budget. You will be asked to enter the MPG for the car you have in mind, thte average number of miles you expect to drive each month and the cost per gallon for fuel.') print('') print('The program will then calculate the monthly fuel cost.') print('') carMpg = float(input("Please enter the car's MPG (Mile per Gallon): ")) avgMiles = int(input("Please enter your monthly miles driven: ")) fuelPrice = float(input("What is the price per gallon for fuel: $")) gallonConsumed = avgMiles/carMpg monthlyCost = gallonConsumed * fuelPrice print('') print("Given price of fuel at ${}/gallon and {} miles/month travelled:" .format(fuelPrice, avgMiles)) print('') print("Gallons used per month: {:.1f}" .format(gallonConsumed)) print("Monthly cost of fuel: {:.2f}" .format(monthlyCost))
true
16d327fe9c580c23480d803b0b6f21a0e778db06
UCSD-CSE-SPIS-2021/spis21-lab03-Jeremy-Raj
/lab03Warmup_Jeremy.py
590
4.34375
4
import turtle def draw_picture(the_turtle): ''' Draw a simple picture using a turtle ''' the_turtle.forward(20) the_turtle.left(40) the_turtle.forward(100) the_turtle.left(90) the_turtle.forward(100) the_turtle.left(90) the_turtle.forward(100) the_turtle.left(90) my_turtle = turtle.Turtle() # Create a new Turtle object draw_picture(my_turtle) # make the new Turtle draw the shape turtle1 = turtle.Turtle() turtle2 = turtle.Turtle() turtle1.setpos(-50, -50) turtle2.setpos(200, 100) turtle1.forward(100) turtle2.left(90) turtle2.forward(100)
false
98137160b7a2b4309077be534f3fa93ddfd91133
BrendanStringer/CS021
/GUI Notes/my_frame.py
1,411
4.3125
4
import tkinter class MyGUI: def __init__(self): # Create the main window widget self.main_window = tkinter.Tk() # Create two frames, one for the top of the window, and one for the bottom. self.top_frame = tkinter.Frame(self.main_window) self.bottom_frame = tkinter.Frame(self.main_window) # Create three label widgets for the Top Frame self.label1 = tkinter.Label(self.top_frame, text='Winken') self.label2 = tkinter.Label(self.top_frame, text='Blinken') self.label3 = tkinter.Label(self.top_frame, text='Nod') # Pack the labels that are in the top frame. # Use the side = 'top' argument to stack them one on top of the other self.label1.pack(side='top') self.label2.pack(side='top') self.label3.pack(side='top') # Create three label widgets for the bottom frame. self.label4 = tkinter.Label(self.bottom_frame, text='Winken') self.label5 = tkinter.Label(self.bottom_frame, text='Blinken') self.label6 = tkinter.Label(self.bottom_frame, text='Nod') # Pack the widgets for the bottom frame # Use the side left argument to arange them horizontally from left to right self.label4.pack(side='left') self.label5.pack(side='left') self.label6.pack(side='left') # Yes, we have to pack the frames too self.top_frame.pack() self.bottom_frame.pack() # Enter the main loop tkinter.mainloop() # Create an instance of the MyGUI class. my_gui = MyGUI()
true