blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
eb7bc39f59c1d5ed19f206a85ccec13c4a6a7e00
winniewjeng/StockDatabase
/Example.py
2,330
4.40625
4
#! /usr/bin/env python3 """ File: Jeng_Winnie_Lab1.py Author: Winnie Wei Jeng Assignment: Lab 2 Professor: Phil Tracton Date: 10/07/2018 The base and derived classes in this file lay out the structure of a simple stock-purchasing database """ from ExampleException import * # Base Class class ExampleBase: # constructor takes care of instantiating member variables of the class def __init__(self, my_company_name, my_stocks_dict, **kwargs): self.company_name = my_company_name self.stocks = my_stocks_dict # string method prints the company's name def __str__(self): return self.company_name # this fxn expands stock purchases by adding more entries to the dictionary def add_purchase(self, other, **kwargs): self.stocks.update(other, **kwargs) return # Derived Class class Useful(ExampleBase): # constructor calls base class' constructor def __init__(self, my_company_name, my_stocks_dict, **kwargs): ExampleBase.__init__(self, my_company_name, my_stocks_dict, **kwargs) # go through the self.stocks dictionary and calculate total value # as summation of shared purchase values multiplied by stock price def compute_value(self): value_sum = 0 for item in list(self.stocks.values()): # compute the value of the stocks product = item[0] * item[1] value_sum += product # if the number of share is negative, raise a custom exception if item[0] < 0: raise ExampleException("ERROR: Invalid number of shares!!") return value_sum # string method overriding the one from base class # outputs a table of stock dictionary and total stock value def __str__(self): print("Company's Symbol " + self.company_name) for date, item in self.stocks.items(): if item[0] == 1: print("On {} {} share is purchased at ${}".format(date, item[0], item[1])) elif item[0] > 1: print("On {} {} shares are purchased at ${}".format(date, item[0], item[1])) else: e = ExampleException("!INVALID!") print("On {} {} shares are purchased at ${}".format(date, e, item[1])) return "------------------------------------------------------"
true
c145820dfe8508a0091293b96dbf1b45d5507bd1
Stephania86/Algorithmims
/reverse_statement.py
449
4.5625
5
# Reverse a Statement # Build an algorithm that will print the given statement in reverse. # Example: Initial string = Everything is hard before it is easy # Reversed string = easy is it before hard is Everything def reverse_sentence(s): word_list = s.split() word_list.reverse() reversed_sentence = " ".join(word_list) return reversed_sentence str = "Everything is hard before it is easy" print(str) print(reverse_sentence(str))
true
c09cbd12035fbd857e646f2379691090df8e267c
Stephania86/Algorithmims
/Even_first.py
674
4.34375
4
# Even First # Your input is an array of integers, and you have to reorder its entries so that the even # entries appear first. You are required to solve it without allocating additional storage (operate with the input array). # Example: [7, 3, 5, 6, 4, 10, 3, 2] # Return [6, 4, 10, 2, 7, 3, 5, 3] def even_first(arr): next_even = 0 next_odd = len(arr) - 1 while next_even < next_odd: if arr[next_even] % 2 == 0: next_even += 1 else: arr[next_even], arr[next_odd] = arr[next_odd], arr[next_even] next_odd -= 1 test_data = [7, 3, 5, 6, 4, 10, 3, 2] print(test_data) even_first(test_data) print(test_data)
true
8fb6a2464a7c668ea237ed170a3e84a237c4a049
Lincxx/py-PythonCrashCourse
/ch3 lists/motorcycles.py
1,470
4.59375
5
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) # change an element in a list motorcycles[0] = 'ducati' print(motorcycles) # append to a list motorcycles.append('Indian') print(motorcycles) # Start with an empty list friends = [] friends.append("Jeff") friends.append("Nick") friends.append("Corey") friends.append("Erick") friends.append("Chuck") print(friends) # inserting into a list letters = ['a', 'c', 'd'] letters.insert(1, 'b') print(letters) # remove an element from a list pets = ['dog', 'cat', 'fish', 'bird'] del pets[1] print(pets) # pop an item from a. The pop() method removes the last item in a list, # but it lets you work with that item after removing it sports = ['football', 'hockey', 'fencing', 'skiing'] print(sports) # How might this pop() method be useful? Imagine that the sports # in the list are stored in chronological order according to when we played # them. popped_sport = sports.pop() print(sports) print(popped_sport) # popping items from any position in a list fav_sport = sports.pop(1) print("This has been one of my fav sports since I was a child " + fav_sport) print(sports) # Removing an Item by Value # Sometimes you won’t know the position of the value you want to remove # from a list. If you only know the value of the item you want to remove, you # can use the remove() method lab_colors = ['yellow', 'black', 'chocolate'] print(lab_colors) lab_colors.remove('yellow') print(lab_colors)
true
fddb55fdc2d951f6c8dbcf265ee894ed6b853c43
Lincxx/py-PythonCrashCourse
/ch3 lists/exercises/3-5.py
1,030
4.25
4
# 3-5. Changing Guest List: You just heard that one of your guests can’t make the # dinner, so you need to send out a new set of invitations. You’ll have to think of # someone else to invite. # • Start with your program from Exercise 3-4. Add a print statement at the # end of your program stating the name of the guest who can’t make it. # • Modify your list, replacing the name of the guest who can’t make it with # the name of the new person you are inviting. # • Print a second set of invitation messages, one for each person who is still # in your list. interesting_people = ['Einstein', 'Jack Black', 'The Queen'] cant_attend = interesting_people.pop(1) print("Mr/Mrs " + cant_attend+ ", can not attend the dinner") interesting_people.append('Elvis') print("Mr/Mrs, " + interesting_people[0] + ". I would like to invite you to dinner") print("Mr/Mrs, " + interesting_people[1] + ". I would like to invite you to dinner") print("Mr/Mrs, " + interesting_people[2] + ". I would like to invite you to dinner")
true
ec339af34ee862e4be09aa357477f6be7512c868
Lincxx/py-PythonCrashCourse
/ch3 lists/exercises/3-4.py
577
4.34375
4
# 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who # would you invite? Make a list that includes at least three people you’d like to # invite to dinner. Then use your list to print a message to each person, inviting # them to dinner. interesting_people = ['Einstein', 'Jack Black', 'The Queen'] print("Mr/Mrs, " + interesting_people[0] + ". I would like to invite you to dinner") print("Mr/Mrs, " + interesting_people[1] + ". I would like to invite you to dinner") print("Mr/Mrs, " + interesting_people[2] + ". I would like to invite you to dinner")
true
42ab61361b181d15deeb79ddcee10368643786c2
tramxme/CodeEval
/Easy/RollerCoaster.py
1,043
4.125
4
''' CHALLENGE DESCRIPTION: You are given a piece of text. Your job is to write a program that sets the case of text characters according to the following rules: The first letter of the line should be in uppercase. The next letter should be in lowercase. The next letter should be in uppercase, and so on. Any characters, except for the letters, are ignored during determination of letter case. CONSTRAINTS: The length of each piece of text does not exceed 1000 characters. ''' import sys, re def doStuff(string): string = re.sub(r'\n','', string) chars = list(string) res = "" up = True for i in range(len(chars)): if(chars[i].isalpha() == True and up == True): up = False res += chars[i].upper() else: if chars[i].isalpha(): up = True res += chars[i] print(res) def main(file_name): fileName = open(file_name, 'r') for line in fileName.readlines(): doStuff(line) if __name__ == '__main__': main(sys.argv[1])
true
569fb617c5b2721bd3df06cf09fd12cc80cd071b
tramxme/CodeEval
/Easy/ChardonayOrCabernet.py
2,096
4.1875
4
''' CHALLENGE DESCRIPTION: Your good friend Tom is admirer of tasting different types of fine wines. What he loves even more is to guess their names. One day, he was sipping very extraordinary wine. Tom was sure he had tasted it before, but what was its name? The taste of this wine was so familiar, so delicious, so pleasant… but what is it exactly? To find the answer, Tom decided to taste the wines we had. He opened wine bottles one by one, tasted different varieties of wines, but still could not find the right one. He was getting crazy, “No, it’s not that!” desperately breaking a bottle of wine and opening another one. Tom went off the deep end not knowing what this wine was. Everything he could say is just several letters of its name. You can no longer look at it and decided to help him. Your task is to write a program that will find the wine name, containing all letters that Tom remembers. CONSTRAINTS: Wine name length can be from 2 to 15 characters. Number of letters that Tom remembered does not exceed 5. Number of wine names in a test case can be from 2 to 10. If there is no wine name containing all letters, print False. The number of test cases is 40. ''' import sys, re, math def countChar(s): count = {} for c in s: if c in count: count[c] += 1 else: count.setdefault(c,1) return count def doStuff(string): values = string.split(" | ") wines = values[0].split() rememberedChars_count = countChar(values[1]) res = [] for wine in wines: temp = countChar(wine) correctWine = True for k,v in rememberedChars_count.items(): if k not in temp or temp[k] < v: correctWine = False break if correctWine == True: res.append(wine) if len(res) == 0: print("False") else: print(" ".join(res)) def main(file_name): fileName = open(file_name, 'r') for line in fileName.readlines(): doStuff(re.sub(r'\n','', line)) if __name__ == '__main__': main(sys.argv[1])
true
f78f231145b031de661340f6bb6dbedcd567b837
randalsallaq/data-structures-and-algorithms-python
/data_structures_and_algorithms_python/challenges/array_reverse/array_reverse.py
350
4.4375
4
def reverse_array(arr): """Reverses a list Args: arr (list): python list Returns: [list]: list in reversed form """ # put your function implementation here update_list = [] list_length = len(arr) while list_length: update_list.append(arr[list_length-1]) list_length-=1 return arr
true
8ff7e7b25fa251914cefc9ac48073768cc06c745
nuass/lzh
/The_diffcult_point/iter_iterable.py
1,104
4.21875
4
#coding:utf-8 #迭代器一定是迭代对象,反过来则不是, #迭代对象是定义__iter__()方法,返回迭代器 #迭代器是定义了__iter__()和__next__() #生成器是特殊的迭代器,yeild的作用和__iter__()和__next__()的作用相同 from collections import Iterable,Iterator class Myrange(object): def __init__(self,start,end,step=1): self.start=start self.end=end self.step=step def __iter__(self): print("=") # return genetor() return IteratorRange(self.start,self.end,self.step) class IteratorRange(object): def __init__(self,start,end,step=1): self.start=start self.end=end self.step=step def __iter__(self): print("=") return self def __next__(self): if self.start<self.end: self.start+=self.step else: raise StopIteration return self.start if __name__=="__main__": for i in Myrange(0,10): print(i) print(isinstance(Myrange(0,1),Iterable)) print(isinstance(IteratorRange(0,1), Iterator))
false
70291137c6c759f268f7ab8b45591a3d1ec95cd9
dnwigley/Python-Crash-Course
/make_album.py
492
4.21875
4
#make album def make_album(artist_name , album_title): """"Returns a dictionary based on artist name and album title""" album = { 'Artist' : artist_name.title(), 'Title' : album_title.title(), } return album print("Enter q to quit") while True: title = input("Enter album title: ") if title == "q": break artist = input("Enter artist: ") if artist =="q": break album = make_album(artist , title) print(album) print("Good-bye!")
true
53fb20fc1ba77ca145dea0b93a89cc020f887619
naveensambandan11/PythonTutorials
/tutorial 39_Factorial.py
224
4.34375
4
# Funtion to calculate factorial def Fact(n): fact = 1 for i in range(1, n+1): fact = fact * i return fact n = int(input('enter the number to get factorial:')) result = Fact(n) print(result)
true
da85714a0fea257a811e53d95d5b0bf3d99717a5
TwitchT/Learn-Pythonn-The-Hard-Way
/ex4.py
1,687
4.4375
4
# This is telling me how many cars there is cars = 100 # This is going to tell me how much space there is in a car space_in_a_car = 40 # This is telling me how many drivers there is for the 100 cars drivers = 30 # This is telling how many passengers there is passengers = 90 # This tells me how many empty cars there is going to be so you have to substract how many cars there is by how many drivers there is available cars_not_driven = cars - drivers # How many cars are going to be driven base on how many drivers there is cars_driven = drivers # To find the carpool capacity, I am going to multiply how many cars are going to be driven by the space in the car carpool_capacity = cars_driven * space_in_a_car # This is telling me how many average passengers is going to be in 1 car average_passengers_per_car = passengers / cars_driven # The print is going to tell me how many cars are available print("There are", cars, "cars available.") # The print is going to tell me how many drivers is available to drive the cars print("There are", drivers, "drivers available.") # This print is going to tell me how many cars are empty print("There will be", cars_not_driven, "empty cars today.") # This print is going to tell me how many people will be able to fit in one car print("We can transport", carpool_capacity, "people today.") # The print is telling me how many passengers I have today print("We have", passengers, "to carpool today.") # This print is going to average the passengers per car print("We need to put about", average_passengers_per_car, "in each car.") # _ is called an underscore character and it is used a lot to put an imaginary space between words in variable names
true
1dfed477aa45a48f640d4d869f5ae051c99b363a
TwitchT/Learn-Pythonn-The-Hard-Way
/ex13.py
984
4.125
4
from sys import argv # Read the WYSS section for how to run this # These will store the variables script, first, second, third = argv # Script will put the first thing that comes to the line, 13.py is the first thing # So script will put it 13.py and it will be the variable print("The script is called:", script) # If you put Kiwi after the 13.py then kiwi will be the varaible and it will replace first print("Your first variable is called:", first) # What ever you put after kiwi then it would turn it into a variable so if you put mango then # Mango would be the second variable print("Your second variable is called:", second) # Your last and third variable is whatever you out after Mango so if you put Watermelon # Then third would be replace with watermelon print("Your third variable is called:", third) # It tells me that there is too many values to unpack #print("Your fourth variable is called:", fourth) # One study drill # The errors says "not enough values to unpack "
true
33115232faf0951e37f4b48521e3e22f6bbc2a00
TwitchT/Learn-Pythonn-The-Hard-Way
/ex23.py
916
4.125
4
import sys # Will make the code run on bash script, input_encoding, error = sys.argv # Defines the function to make it work later on def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding, errors) return main(language_file, encoding, errors) # Defines this function to make it work when I use it again in the code def print_line(line, encoding, errors): next_lang = line.strip() raw_bytes = next_lang.encode(encoding, errors=errors) cooked_string = raw_bytes.decode(encoding, errors=errors) # This will print out '<===>' for every raw bytes that the txt have print(raw_bytes, "<===>", cooked_string) # This will open the language.txt and it will encode something called a utf-8 languages = open("languages.txt", encoding="utf-8") # Function that we define before main(languages, input_encoding, error)
true
03cd39bc59234bd30b84a89ae3157a44363f8a93
Ishan-Bhusari-306/applications-of-discrete-mathematics
/dicestrategy.py
988
4.28125
4
def find_the_best_dice(dices): # you need to use range (height-1) height=len(dices) dice=[0]*height #print(dice) for i in range(height-1): #print("this is dice number ",i+1) # use height for j in range(i+1,height): #print("comparing dice number ",i+1," with dice number ",j+1) check1=0 check2=0 for element1 in dices[i]: for element2 in dices[j]: if element1>element2: check1=check1+1 elif element2>element1: check2=check2+1 else: continue if check1>check2: print("the dice number ",i+1,"is better than dice number ",j+1) dice[i]=dice[i]+1 else: print("the dice number ",j+1,"is better than dice number ",i+1) dice[j]=dice[j]+1 print(dice) maxelement=max(dice) maxindex=dice.index(max(dice)) for i in range(len(dice)): if i != maxindex: if dice[i]==maxelement: return -1 return maxindex dices=[[1, 2, 3, 4, 5, 6], [1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7]] print(find_the_best_dice(dices))
true
892ba5dc80b77da4916db1e1afb0f0b4a06c75ba
ibndiaye/odd-or-even
/main.py
321
4.25
4
print("welcome to this simple calculator") number = int(input("Which number do you want to check? ")) divider = int(input("what do you want to divide it by? ")) operation=number%divider result=round(number/divider, 2) if operation == 0: print(f"{result} is an even number") else: print(f"{result} is an odd number")
true
d475df99c67157cfad58ce2514cae3e378ed785c
adwardlee/leetcode_solutions
/0114_Flatten_Binary_Tree_to_Linked_List.py
1,520
4.34375
4
''' Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked list" should be in the same order as a pre-order traversal of the binary tree. Example 1: Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6] Example 2: Input: root = [] Output: [] Example 3: Input: root = [0] Output: [0] Constraints: The number of nodes in the tree is in the range [0, 2000]. -100 <= Node.val <= 100 Follow up: Can you flatten the tree in-place (with O(1) extra space)? ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if root == None: return None _ = self.flattenSubtree(root) return root def flattenSubtree(self, root): a = None tmpright = root.right if root.left: a = self.flattenSubtree(root.left) tmp = a root.right = root.left tmp.right = tmpright root.left = None if tmpright: a = self.flattenSubtree(tmpright) return a if a else root
true
6bf88ae9e8933f099ed1d579af505fc8ef0d04b4
Abicreepzz/Python-programs
/Decimal_to_binary.py
462
4.25
4
def binary(n): result='' while n>0: result=str(n%2)+str(result) n//=2 return int(result) binary(5) ##output= 101 # Another simple one line code for converting the decimal number to binary is followed: def f(n): print('{:04b}'.format(n)) binary(5) ##output =101 # If we want to print in the 8 bit digit of the binary numbers then we can just specify the 8 bit in function. def f(n): print('{:08b}'.format(n)) binary(5) ##output = 00000101
true
9e188e9dcd5fd64231f883943ab83e307158a5f7
Jewel-Hong/SC-projects
/SC101Lecture_code/SC101_week6/priority_queue_list.py
1,402
4.46875
4
""" File: priority_queue_list.py Name: ---------------------------------- This program shows how to build a priority queue by using Python list. We will be discussing 3 different conditions while appending: 1) Prepend 2) Append 3) Append in between """ # This constant controls when to stop the user input EXIT = '' def main(): priority_queue = [] print('--------------------------------') # TODO: while True: name = input('Patient: ') if name == EXIT: break priority = int(input('Priority: ')) data = (name, priority) if len(priority_queue) == 0: priority_queue.append(data) else: # Prepend if priority < priority_queue[0][1]: priority_queue.insert(0, data) # Append elif priority >= priority_queue[len(priority_queue)-1][1]: priority_queue.append(data) # In between else: for i in range(len(priority_queue) - 1): # 在python之中for loop不會動態更新,其他語言會 if priority_queue[i][1] <= priority < priority_queue[i+1][1]: priority_queue.insert(i+1, data) break #不然會產生無限迴圈 print('--------------------------------') print(priority_queue) if __name__ == '__main__': main()
true
7ce2f22d370784db0284cac76eba4becb42f7556
Jewel-Hong/SC-projects
/SC101Lecture_code/SC101_week3/word_occurrence.py
1,397
4.21875
4
""" File: student_info_dict.py ------------------------------ This program puts data in a text file into a nested data structure where key is the name of each student, and the value is the dict that stores the student info """ # The file name of our target text file FILE = 'romeojuliet.txt' # Contains the chars we would like to ignore while processing the words PUNCTUATION = '.,;!?#&-\'_+=/\\"@$^%()[]{}~' def main(): d = {} with open(FILE, 'r') as f: for line in f: token_list = line.split() for token in token_list: token = string_manipulation(token) # 不知道存不存在怎麼加啦! key error~ # d[token] += 1 # key為該文字,value為該文字出現之次數 if token in d: d[token] += 1 else: # 注意初始值為1,非0,因為當你看到它時是它出現的第一次!! d[token] = 1 print_out_d(d) def print_out_d(d): """ : param d: (dict) key of type str is a word value of type int is the word occurrence --------------------------------------------------------------- This method prints out all the info in d """ for key, value in sorted(d.items(), key=lambda t: t[1]): print(key, '->', value) def string_manipulation(word): word = word.lower() ans = '' for ch in word: if ch.isalpha() or ch.isdigit(): # if ch not in PUNTUATION: ans += ch return ans if __name__ == '__main__': main()
true
b7c2bfb8e2014f910c9303da904d3303eae9e5bf
KREAL22/tms
/lesson8/lesson8.py
2,464
4.34375
4
''' Создайте класс Figure. У каждой фигуры есть имя, также можно найти площадь и периметр фигуры. Создайте классы Triangle, Circle, Rectangle производные от Figure. У класса Triangle есть 3 стороны: a, b, c; у Circle - радиус r; у Rectangle - стороны a и b. Переопределите методы нахождения площади и периметра для каждой фигуры (Triangle, Circle, Rectangle). Также для объектов классов должны работать операторы сравнения: ==, >, < <=, >=. Будем считать, что фигуры равны, если они имеют одинаковую площадь. Строковое представление объекта должно возвращать тип фигуры и её имя. Дополнительная функциональность приветствуется. ''' class Figure: def info(self): print("класс Фигура") class Triangle(Figure): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def tr_sq(self): s = 0.5 * (self.a + self.b + self.c) return s def tr_pr(self): p = self.a + self.b + self.c return p def tr_info(self): print('Фигура: Треугольник') print('Периметр равен:', self.tr_pr()) print('Площадь равна:', self.tr_sq()) class Circle(Figure): def __init__(self, r): self.r = r def cr_sq(self): s = 3.14 * self.r ** 2 return s def cr_pr(self): p = 2 * 3.14 * self.r return p def cr_info(self): print('Фигура: Круг') print('Периметр равен:', self.cr_pr()) print('Площадь равна:', self.cr_sq()) class Rectangle(Figure): def __init__(self, a, b): self.a = a self.b = b def rt_sq(self): s = self.a * self.b return s def rt_pr(self): p = 2 * (self.a + self.b) return p def rt_info(self): print('Фигура: Прямоуголник') print('Периметр равен:', self.rt_pr()) print('Площадь равна:', self.rt_sq())
false
122d28e0debb5673766de18fcdd5f27c44cdb407
Nicolas-Wursthorn/Exercicios-Python-Brasil
/EstruturaDeRepeticao/exercicio13.py
461
4.15625
4
# Faça um programa que peça dois números, base e expoente, calcule e mostre o primeiro número elevado ao segundo número. Não utilize a função de potência da linguagem. base = int(input("Digite o primeiro número: ")) expoente = int(input("Digite o segundo número: ")) count = 1 potencia = 1 while count <= expoente: potencia = potencia * base count += 1 print("O primeiro número elevado ao segundo número é igual a: {}".format(potencia))
false
9f97af2a66220b24f7fc849b477d455027f80960
Nicolas-Wursthorn/Exercicios-Python-Brasil
/EstruturaDeDecisao/exercicio23.py
276
4.15625
4
# Faça um Programa que peça um número e informe se o número é inteiro ou decimal. Dica: utilize uma função de arredondamento. num = float(input("Digite um número: ")) if num // 1 == num: print("Esse número é inteiro") else: print("Esse número é decimal")
false
a01d070dcdbc806fe0b93a311ea5660bc9b6d16a
Nicolas-Wursthorn/Exercicios-Python-Brasil
/EstruturaDeRepeticao/exercicio31.py
411
4.28125
4
# Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário. Ex.: 5!=5.4.3.2.1=120. A saída deve ser conforme o exemplo abaixo: # Fatorial de: 5 # 5! = 5 . 4 . 3 . 2 . 1 = 120 import math numero = int(input("Fatorial de: ")) count = numero fatorial = math.factorial(numero) for i in range(numero - 1): print(count, end=" * ") count -= 1 print("1 = {}".format(fatorial))
false
78f798166b198026dbd97dbb63d23802865baaee
Nicolas-Wursthorn/Exercicios-Python-Brasil
/EstruturaSequencial/exercicio17.py
1,275
4.15625
4
# Faça um Programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 6 metros quadrados e que a tinta é vendida em latas de 18 litros , que custam R$80,00 ou galões de 3,6 litros, que custam R$25,00. # Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações: # 1. comprar apenas latas de 18 litros; # 2. comprar apenas galões de 3,6 litros; # 3. misturar latas e galões, de forma que o preço seja o menor. Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias. tamanhoM2 = float(input("Qual o tamanho em metros quadrados da área a ser pintada?: ")) if tamanhoM2 % 108 == 0: latas = tamanhoM2 / 108 else: latas = int(tamanhoM2 / 108) + 1 if tamanhoM2 % 21.6 == 0: galoes = tamanhoM2 / 21.6 else: galoes = int(tamanhoM2 / 21.6) + 1 precoLata = latas * 80 precoGalao = galoes * 25 print("Comprando apenas latas de 18 litros o valor gasto será: R${}".format(precoLata)) print("Comprando apenas galões de 3,6 litros o valor gasto será: R${}".format(precoGalao)) # print("Misturando latas e galões o valor gasto ficaria menor, sendo: R${}".format())
false
80f2cfaaa82a18157ebc3b8d6015ac36b3412bc4
uppala-praveen-au7/blacknimbus
/AttainU/Robin/Code_Challenges/Day2/Day2/D7CC3.py
1,984
4.21875
4
# 3) write a program that takes input from the user as marks in 5 subjects and assigns a grade according to the following rules: # Perc = (s1+s2+s3+s4+s5)/5. # A, if Perc is 90 or more # B, if Perc is between 70 and 90(not equal to 90) # C, if Perc is between 50 and 70(not equal to 90) # D, if Perc is between 30 and 50(not equal to 90) # E, if Perc is less than 30 # Defining a function to check a number contains no characters # and the marks less than 100 def my_func(a): # Defining a list for reference to compare the characters of the input list=['0','1','2','3','4','5','6','7','8','9','.'] for i in range(0,len(a)): if a[i] in list: continue else: a=input('Enter valid marks: ') continue # after confirming the entered input contains only numbers # checking whether the given number is greater than 100 # and if it is greater than 100 asking the student to enter # the marks scaled to 100 if float(a)>100: a=input('please enter your marks scaled to 100: ') my_func(a) else: pass return float(a) # getting the individual subject marks from a student subject1=(input('enter the subject1 marks out of 100 here: ')) sub1=my_func(subject1) subject2=(input('enter the subject2 marks out of 100 here: ')) sub2=my_func(subject2) subject3=(input('enter the subject3 marks out of 100 here: ')) sub3=my_func(subject3) subject4=(input('enter the subject4 marks out of 100 here: ')) sub4=my_func(subject4) subject5=(input('enter the subject5 marks out of 100 here: ')) sub5=my_func(subject5) total= sub1+sub2+sub3+sub4+sub5 print('Total: ',total) perc =(sub1+sub2+sub3+sub4+sub5)/5 print('Average: ',perc) if perc>=90: print('Your grade is \'A\'') elif perc>=70 and perc<90: print('your grade is \'B\'') elif perc>=50 and perc<70: print('Your grade is \'C\'') elif perc>=30 and perc<50: print('Your grade is \'D\'') else: print('Your grade is \'E\'')
true
2c49ef300a9d5a6b783f103e064132f222fe4977
ruchirbhai/Trees
/PathSum_112.py
2,125
4.15625
4
# https://leetcode.com/problems/path-sum/ # Given a binary tree and a sum, determine if the tree has a root-to-leaf path such # that adding up all the values along the path equals the given sum. # Note: A leaf is a node with no children. # Example: # Given the below binary tree and sum = 22, # 5 # / \ # 4 8 # / / \ # 11 13 4 # / \ \ # 7 2 1 # return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. from collections import deque answer = False # Definition for a binary tree node. class TreeNode: def __init__(self, key): self.data = key self.left = None self.right = None class Solution: def path_sum(self, root): # Edge case when the root is empty if root is None: # if the target is Zero and the tree is null its not clear if we return true of false. # another corner case to consider return False global answer self.path_sum_helper(root, 0, 22) return answer def path_sum_helper(self, node, slate_sum, target): #base case: leaf node if node.left is None and node.right is None: if slate_sum + node.data == target: global answer answer = True return answer # recursive case if node.left is not None: self.path_sum_helper(node.left, slate_sum + node.data, target) #right side if node.right is not None: self.path_sum_helper(node.right, slate_sum + node.data, target) #driver program for the above function # #left side of the tree # root = TreeNode(1) root = TreeNode(5) root.left = TreeNode(4) root.left.left = TreeNode(11) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(2) #right side of the tree root.right = TreeNode(8) root.right.left = TreeNode(13) root.right.right = TreeNode(4) root.right.right.right = TreeNode(1) # Create a object for the class obj = Solution() #now call the class methos with the needed arguments print(obj.path_sum(root))
true
58118aa6dac147138a91cdfb393ddf328be961b0
44858/variables
/multiplication and division.py
484
4.34375
4
#Lewis Travers #12/09/2014 #Multiplying and dividing integers first_integer = int(input("Please enter your first integer: ") second_integer = int(input("Please enter an integer that you would like the first to be multiplied by: ")) third_integer = int(input("Please enter an integer that you would like the total of the previous to be divided by: ")) end_total = (first_integer * second_integer) / third_integer print("The total is {0}").format(end_total)
true
9995de8314efb0c98d03f0c893bb7b7ddbbfd239
jjsherma/Digital-Forensics
/hw1.py
2,967
4.3125
4
#!/usr/bin/env python import sys def usage(): """Prints the correct usage of the module. Prints an example of the correct usage for this module and then exits, in the event of improper user input. >>>Usage: hw1.py <file1> """ print("Usage: "+sys.argv[0]+" <file1>") sys.exit(2) def getFile(): """Creates a file descriptor for a user-specified file. Retreives the filename from the second command line argument and then creates a file descriptor for it. Returns: int: A file descriptor for the newly opened file specified by the user. Raises: An error occured while attempting to open the file """ if len(sys.argv) > 1: filename = sys.argv[1] else: usage() try: fd = open(filename, "rb") return fd except: print("error opening program ") sys.exit() def partialLine(bytes): """Adds additional spacing so the ASCII on a shortened line lines up with preceeding lines. Takes the number of bytes on a short line and finds the difference between a full line. This difference is then used to calculate the number of spaces necessary to properly align the ASCII with the rows above. >>>00000000 32 b4 51 7a 3b 3c 64 dd c3 61 da 8a ff 60 5c 9b |2.Qz;<d..a...`\.| >>>00000120 91 93 f7 |...| Args: bytes: The number of bytes currently being processed """ if sys.getsizeof(bytes) < 33: difference = 33 - sys.getsizeof(bytes) while difference != 0: print(" ", end = "") difference = difference - 1 def process(): """Forms a table with byte hex values, memory positions in hex, and associated ASCII Uses the file descriptor from getFile() to continually read 16 bytes formatting each line so that the memory position, in hex, of the first byte of a line, followed by all of the hex values for those bytes, and then the associated ASCII values for the hex values. >>>00000000 32 b4 51 7a 3b 3c 64 dd c3 61 da 8a ff 60 5c 9b |2.Qz;<d..a...`\.| Raises: An error occured while attempting to close the file """ fd = getFile() count = 0 bytes = fd.read(16) while bytes: print("%08x" % count + " ", end = "") for b in bytes: print("%02x" % b + " ", end = "") count = count + 1 if sys.getsizeof(bytes) < 33 and sys.getsizeof(bytes) > 17: partialLine(bytes) print("|", end = "") for b in bytes: if b > 31 and b < 127: print(chr(b), end = "") else: print(".", end = "") print("|") bytes = fd.read(16) print("%08x" % count + " ") try: fd.close() except: print("error closing program ") sys.exit() def main(): process() if __name__=="__main__": main()
true
2f9c1a23384af6b52ab218621aa937a294a6b793
bainjen/python_madlibs
/lists.py
895
4.125
4
empty_list = [] numbers = [2, 3, 5, 2, 6] large_animals = ["african elephant", "asian elephant", "white rhino", "hippo", "guar", "giraffe", "walrus", "black rhino", "crocodile", "water buffalo"] a = large_animals[0] b = large_animals[5] # get the last animal in list c = large_animals[-1] # return index number d = large_animals.index('crocodile') # accessing slices (chunks) of list - (first element, last element) e = large_animals[0:3] # returns indices 0, 1, 2 f = large_animals[3] = 'penguin' # change value # delete del large_animals[3] # find length g = len(a) # can have nested lists animal_kingdom = [ ['cat', 'dog'], ['turtle', 'lizard'], ['eagle', 'robin', 'crow'] ] biggest_bird = animal_kingdom[-1][0] # strings are also lists of symbols and can be treated as such h = 'this is a list of symbols' i = h[5:7] j = h.split(' ') k = h.split('symbols') print(j) print(k)
true
423fce215596d87146dd016ad3cd9b7a51cf9895
dasha108219/PROGR
/hw6/try-random.py
2,872
4.21875
4
print('ВАРИАНТ 2') print('Текст должен представлять собой стихотворение на русском языке из четырёх строк без рифмы, но написанное с соблюдением одной метрической схемы, кроме трёхстопного анапеста- трехстопный дактиль') print() import random with open('noun_sg.txt') as file: file = file.read().split(' ') noun_sg = file with open('noun_pl.txt') as file: file = file.read().split(' ') noun_pl = file def noun(number): if number == 's': return random.choice(noun_sg) else: return random.choice(noun_pl) with open('verb_ntrans_sg.txt') as file: file = file.read().split(' ') verb_ntrans_sg = file with open('verb_trans_sg.txt') as file: file = file.read().split(' ') verb_trans_sg = file with open('verb_ntrans_pl.txt') as file: file = file.read().split(' ') verb_ntrans_pl = file with open('verb_trans_pl.txt') as file: file = file.read().split(' ') verb_trans_pl = file def verb(trans, number): if trans == 'y': if number == 's': return random.choice(verb_trans_sg) else: return random.choice(verb_trans_pl) else: if number == 's': return random.choice(verb_ntrans_sg) else: return random.choice(verb_ntrans_pl) with open('marks.txt') as file: file = file.read().split(' ') marks = file def punctuation(): return random.choice(marks) with open('addition.txt') as file: file = file.read().split(' ') addition = file with open('adverbs.txt') as file: file = file.read().split(' ') adverbs = file def add(trans): if trans == 'y': return random.choice(addition) else: return random.choice(adverbs) with open('imperative.txt') as file: file = file.read().split(' ') imperativ = file def imperative(): return random.choice(imperativ) def verse1(): return noun('s')+' '+verb('y','s')+' ' + add('y') + punctuation() def verse2(): return noun('p')+' '+verb('y','p')+' ' + add('y') + punctuation() def verse3(): return noun('s')+' '+verb('n','s')+' ' + add('n') + punctuation() def verse4(): return noun('p')+' '+verb('n','p')+' ' + add('n') + punctuation() def verse5(): return imperative()+' '+add('y')+' ' + add('n') + punctuation() def make_verse(): verse = random.choice([1,2,3,4,5]) if verse == 1: return verse1() elif verse == 2: return verse2() elif verse == 3: return verse3() elif verse == 4: return verse4() else: return verse5() for n in range(4): print(make_verse())
false
36e830aa4a52c6f8faa1347722d1dab6333088c8
tom1mol/core-python
/test-driven-dev-with-python/refactoring.py
1,197
4.3125
4
#follow on from test-driven-development def is_even(number): return number % 2 == 0 #returns true/false whether number even/not def even_number_of_evens(numbers): evens = sum([1 for n in numbers if is_even(n)]) return False if evens == 0 else is_even(evens) """ this reduces to line 7/8 above evens = 0 #initialise a variable to say currently zero evens #loop to check each number and see if it's even for n in numbers: if is_even(n): #remainder when divided by 2 is zero(modulo)..then is even number evens += 1 #if even...increment by 1 if evens == 0: # if number of evens = 0 return False else: return is_even(evens) #returns true if number of evens is even """ assert even_number_of_evens([]) == False, "No numbers" assert even_number_of_evens([2, 4]) == True, "2 even numbers" assert even_number_of_evens([2]) == False, "1 even number" assert even_number_of_evens([1,3,9]) == False, "3 odd numbers" print("All tests passed!")
true
bc547b6f91f5f3133e608c4aa479eb811ddf7c58
sgspectra/phi-scanner
/oldScripts/wholeFile.py
835
4.40625
4
# @reFileName is the name of the file containing regular expressions to be searched for. # expressions are separated by newline # @fileToScanName is the name of the file that you would like to run the regex against. # It is read all at once and the results returned in @match import re #reFileName = input("Please enter the name of the file containing regular expressions:") #reFile = open(reFileName, 'r') reFile = open('lib/phi_regex.txt', 'r') #fileToScanName = input("Please enter the name of the file you wish to scan:") fileToScanName = 'test_text.txt' for line in reFile: fileToScan = open(fileToScanName, 'r') # strip the newline from the regex line = line.rstrip('\n') print(line) exp = re.compile(line) print(exp) match = exp.findall(fileToScan.read()) print(match) fileToScan.close()
true
b28a938c098b5526fb6541b41f593d30a665b185
elguneminov/Python-Programming-Complete-Beginner-Course-Bootcamp-2021
/Codes/StringVariables.py
1,209
4.46875
4
# A simple string example short_string_variable = "Have a great week, Ninjas !" print(short_string_variable) # Print the first letter of a string variable, index 0 first_letter_variable = "New York City"[0] print(first_letter_variable) # Mixed upper and lower case letter variable mixed_letter_variable = "ThIs Is A MiXeD VaRiAbLe" print(mixed_letter_variable.lower()) # Length of the variable print(len(mixed_letter_variable)) # Use '+' sign inside a print command first_name = "David" print("First name is : " +first_name) # Replace a part of a string first_serial_number = "ABC123" print("Changed serial number #1 : " +first_serial_number.replace('123' , '456')) # Replace a part of a string -> Twice ! second_serial_number = "ABC123ABC" print("Changed serial number #2 : " +second_serial_number.replace('ABC' , 'ZZZ' , 2)) # Take a part of a variable, according to specific index range range_of_indexes = second_serial_number[0:3] print(range_of_indexes) # One last thing - adding spaces between multiple variables in print first_word = "Thank" second_word = "you" third_word = "NINJAS !" print(first_word +" " +second_word +" " +third_word) "automationninja.qa@gmail.com"
true
201a2b05930cd4064623156c2b9248665d378647
Dumacrevano/Dumac-chen_ITP2017_Exercise2
/3.1 names.py
234
4.375
4
#Store the names of a few of your friends in a list called names . # Print each person’s name by accessing each element in the list, one at a time . names=["Suri", "andy", "fadil", "hendy"] print(names[0],names[1],names[2],names[3])
true
42627250cb4d940216afbfd63631af391c8df4f9
Dumacrevano/Dumac-chen_ITP2017_Exercise2
/3.10 every function.py
328
4.15625
4
list=["Indonesia","singapore","Thailand","Kamboja"] print(list[1]) print(list[-2]) list[1]="Vietnam" list.append("Laos") list.insert(0,"Malaysia") del list[3] winner=list.pop() print("the winner is "+winner) list.remove("Malaysia") print(list) print(sorted(list,reverse=True)) list.sort() print(list) list.reverse() print(list)
false
70bff1130064e823077c47b62fe29a207661fa73
PauloGunther/Python_Studies
/Teorias/2.1_Exemplos.py
1,362
4.125
4
# POR TUDO MAIUSCULO E MINUSCULO, CONTA NUMERO DE LETRAS nome = input('Digite seu nome completo: ') print(nome.upper()) print(nome.lower()) rep = nome.replace(' ', '') print('O número de letra é: {}' .format(len(rep))) n1 = nome.split() print('Seu primeiro nome tem {} letras' .format(len(n1[0]))) # MOSTRAR DEZENAS CENTENAS MILHARES n = int(input('Digite um número entre 0 a 9999: ')) u = n // 1 % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}' .format(u, d, c, m)) # ANALIsAR SE O NOME DA CIDADE COMEÇA COM SANTO city = str(input('Digite o nome de sua cidade: ')).split()[0].capitalize() print(city == 'Santo') # ANALIsAR SE HÁ SILVA NO SEU NOME n = str(input('Digite seu nome: ')).title().split() print('Silva' in n) # ANALIsAR POSIÇÕES DE UMA LETRA NUMA FRASE a1 = str(input('Digite uma frase: ')).lower().lstrip() x = a1[0] print('A letra {} aparece {} vezes na frase.' .format(x.upper(), a1.count(x))) print('A primeira letra {} aparece na posição {}.' .format(x.upper(), a1.find(x))) print('A última letra {} aparece na posição {}.' .format(x.upper(), a1.rfind(x))) # IDENTIFICAR POSIÇÕES DE PALAVRAS NUMA FRASE n = str(input('Digite seu nome completo: ')) .title().split() print('Seu primeiro nome é: {}' .format(n[0])) print('Se último nome é: {}' .format(n[-1]))
false
752626c1314c482e195bec357be5f28142a69c51
bquillas/Learning-Python
/codigo_python/listas.py
742
4.125
4
# LISTAS # Las listas son mutables # Puedo quitar y añadi9r alementos a la lista objetos = ["Hola", 2, 4.5, True] objetos[0] #'Hola' objetos[3] # True objetos.append(False) # ["Hola", 2, 4.5, True, False] objetos.pop(1) #Pasa como parámetro el índice de la lista # 2 # Elimina el valor de la pos 2 # ["Hola", 4.5, True, False] for elemento in objetos: print(elemento) #Hola #4.5 #True #False objetos[::-1] #[False, True, 4.5, "Hola" ] objetos[1:3] # [4.5, True] #------------------------------- numero = [1,2,3,4] numero2 = [5,6,7,8] lista_numeros = numero + numero2 #lista_ numeros [1,2,3,4,5,6,7,8] numero * 3 # [1,2,3,4,1,2,3,4,1,2,3,4] #uso de 'del' para eliminar por indices li = ['b','a','c'] del li[0] li ['a', 'c']
false
5a98de9302cd36107a5bd2c3e7bba4218f817ba6
lodi-jesse/aula_python
/desafio042.py
744
4.125
4
# Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado: # Equilátero: todos os lados iguais # Isósceles: dois lados iguais # Escaleno: Todos os lados diferentes r1 = int(input('Digite a primeira reta: ')) r2 = int(input('Digite a segunda reta: ')) r3 = int(input('Digite a terceira reta: ')) if (r1 + r2) > r3 and (r2 + r3) > r1 and (r1 + r3) > r2: input('Sim estas retas formam um triângulo') if r1 == r2 == r3: print('Ete triângulo é um Equilátero.') elif r1 != r2 != r3 != r1: print('Este triângulo é um isósceles.') else: print('Este triângulo é escaleno') else: print('Essas retas não formam um triângulo.')
false
f5b05ac0de2aa72baae02f6cf9c077b6e774bf93
lodi-jesse/aula_python
/desafio028.py
744
4.125
4
#Escreva um programa que faça o computador sortear um número de 0 ate 5 e pesa para o usuário tentar descobrir qual foi o número escolhido pelo computador. # O programa deverá escrever na tela se o usuário venceu ou perdeu. from random import randint from time import sleep sorteado = randint (0, 5) #faz o computador a sortear um número print('-=-' * 20) num = int(input('Digite um número de "0 até 5" e tente a sorte: ')) print('-=-' * 20) print('PROCESSANDO ...') sleep(3) if sorteado == num: print('O computador escolheu {} e você digitou {}. PARABÉNS VOCÊ VENCEU!'.format(sorteado,num)) else: print('O computador escolheu {} e você digitou {}. MAIS SORTE DA PROXIMA VOCÊ PERDEU!'.format(sorteado,num))
false
9454b32184aa1c29ad0db72ec564036666dff0f9
EnriqueStrange/portscannpy
/nmap port-scanner.py
1,508
4.1875
4
#python nmap port-scanner.py #Author: P(codename- STRANGE) #date: 10/09/2020 import argparse import nmap def argument_parser(): """Allow target to specify target host and port""" parser = argparse.ArgumentParser(description = "TCP port scanner. accept a hostname/IP address and list of ports to" "scan. Attenpts to identify the service running on a port.") parser.add_argument("-o", "--host", nargs = "?", help = "Host IP address") parser.add_argument("-p", "--ports", nargs="?", help = "comma-separation port list, such as '25,80,8080'") var_args = vars(parser.parse_args()) # Convert argument name space to dictionary return var_args def nmap_scan(host_id, port_num): """Use nmap utility to check host ports for status.""" nm_scan = nmap.PortScanner() nm_scan.scan(host_id, port_num) state = nm_scan[host_id]['tcp'][int(port_num)]['state'] # Indicate the type of scan and port number result = ("[*] {host} tcp/{port} {state}".format(host=host_id, port=port_num, state=state)) return result if __name__ == '__main__': # Runs the actual program try: user_args = argument_parser() host = user_args["host"] ports = user_args["ports"].split(",") # Make a list from port numbers for port in ports: print(nmap_scan(host, port)) except AttributeError: print("Error, please provide the command_line argument before running.")
true
0dd3441b24d9c65bc2c0bdfe20612dfcfcf55482
nadiyasalma/Nadiya-Salma_I0320071_M.Wildan-Rusydani_Tugas3
/I0320071__Exercise 3.1-3.10.py
2,150
4.375
4
#exercise 3.1 #cara mengakses nilai di dalam list python list1 = ['fisika', 'kimia', 1993, 2017] list2 = [1, 2, 3, 4, 5, 6, 7] print("list1[0]: ", list1[0]) print("list2[1;5]: ", list2[1:5]) #exercise 3.2 list = ['fisika', 'kimia', 1993, 2017] print("Nilai ada pada index 2: ", list[2]) list[2] = 2001 print("Nilai baru ada pada index 2: ", list[2]) #exercise 3.3 #contoh cara menghapus nilai pada list python list = ['fisika', 'kimia', 1993, 2017] print(list) del list[2] print("setelah dihapus nilai pada index 2: ", list) #exercise 3.4 #contoh cara membuat dictionary pada python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print("dict['Name']: ", dict['Name']) print("dict['Age']: ", dict['Age']) #exercise 3.5 #contoh cara membuat dictionary pada python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print("dict['Name']: ", dict['Name']) print("dict['Age']: ", dict['Age']) #exercise 3.6 #update dictionary python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8; #mengubah entru yang sudah ada dict['School'] = "DPS School" #Menambah entri baru print("dict['Age']; ", dict['Age']) print("dict['School']: ", dict['School']) #exercise 3.7 #cara menghapus pada dictionary python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name'] #hapus entri dengan key 'Name' dict.clear() #hapus semua entri dict del dict #hapus dictionary yang sudah ada print("dict['Age']: ", dict['Age']) print("dict['School']: ", dict['School']) #exercise 3.8 #cara mengakses nilai tuple tup1 = ('fisika', 'kimia', 1993, 2017) tup2 = (1, 2, 3, 4, 5, 6, 7) print("tup1[0]: ", tup1[0]) print("tup2[1:5]: ", tup2[1:5]) #xercise 3.9 tup1 = (12, 34.56) tup2 = ('abc', 'xyz') #aksi seperti dibawahini tidak bisa dilakukan pada tuple python #karena memang nilai pada tuple python tidakbisa diiubah #tup1[0] - 100 #jadi, buatlah tuple baru sebagai berikut tup3 = tup1 + tup2 print(tup3) #exercise 3.10 tup = ('fisia', 'kimia', 1993, 2017) #hapus tupe statement del del tup #lalu buat kembali tuple yang baru dnegan elemen yang di inginkan tup = ('Bahasa', 'Literasi', 2020) print("Setelah menghapus ti[e:", tup)
false
f484aab33a5142f6fbe20f6072e035339f561d0b
programmer290399/Udacity-CS101-My-Solutions-to-Exercises-
/CS101_Shift_a_Letter.py
387
4.125
4
# Write a procedure, shift, which takes as its input a lowercase letter, # a-z and returns the next letter in the alphabet after it, with 'a' # following 'z'. def shift(letter): ASCII = ord(letter) if ASCII == 122 : return chr(97) else : return chr(ASCII + 1) print shift('a') #>>> b print shift('n') #>>> o print shift('z') #>>> a
true
62c129920b2c9d82d35eaba02a73924596696280
Maxrovr/concepts
/python/sorting/merge_sort.py
1,982
4.21875
4
class MergeSort: def _merge(self, a, start, mid, end): """Merges 2 arrays (one starting at start, another at mid+1) into a new array and then copies it into the original array""" # Start of first array s1 = start # Start of second array s2 = mid + 1 # The partially sorted array s = [] # for - till we iterate over all elements of partial array being sorted for i in range(end - start + 1): # If second array has been completely been traversed - first one still has some elements left - copy them all if s1 > mid: s.append(a[s2]) s2 += 1 # Vice-Versa elif s2 > end: s.append(a[s1]) s1 += 1 # Actual sorting - change symbols (either hardcode or dynamically with a bool descending) elif a[s1] <= a[s2]: s.append(a[s1]) s1 += 1 # Vice-Versa else: s.append(a[s2]) s2 += 1 # Copy partially sorted array into original array a[start:end+1] = s def _merge_sort(self, a, start, end): """Divides array into halves and calls merge on them""" if start < end: mid = start + (end - start) // 2 self._merge_sort(a, start, mid) self._merge_sort(a, mid + 1, end) self._merge(a, start, mid, end) def merge_sort(self, a): self._merge_sort(a, 0, len(a) - 1) a = [i for i in range(8,0,-1)] print(f'Before: {a}') obj = MergeSort() obj.merge_sort(a) print(f'After: {a}') a = [i for i in range(7,0,-1)] print(f'Before: {a}') obj = MergeSort() obj.merge_sort(a) print(f'After: {a}') a = [i for i in range(1,9)] print(f'Before: {a}') obj = MergeSort() obj.merge_sort(a) print(f'After: {a}') a = [i for i in range(1,8)] print(f'Before: {a}') obj = MergeSort() obj.merge_sort(a) print(f'After: {a}')
true
a5333dc221c0adcb79f583faceb53c7078333601
tocheng/Book-Exercises-Intro-to-Computing-using-Python
/Book-Chapter5_2-Range.py
1,922
4.21875
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 09:48 2020 Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed Book Chapter 5 Structured types, mutability and higher-order functions Ranges @author: Atanas Kozarev - github.com/ultraasi-atanas RANGE the Theory The range function takes three parameters - start, stop, step Returns the progression of integers - start, start + step, start + step*2 etc If step is positive, the last integer is the largest start + step*i smaller than stop If step is negative, the last integer is the smallest integer start + step*i greater then stop If two arguments are supplied, step is 1 If one argument is supplied, step is 1, stop is taken from arg, start is 0 All of the operations on tuples apply on ranges, except concatenation and repetition The numbers of the progression are generated on an "as needed" basis, so even expressions such as range(10000) consume little memory (Python3.x) The arguments of the range function are evaluated just before the first iteration of the loop and not reevaluated for subsequent iteration """ # RANGE SLICE rangeSlice = range(10)[2:6][2] # returns 4 print('RangeSlice of range(10)[2:6][2] is ', rangeSlice, '\n') # RANGE COMPARISON range2 = range(0,7,2) range3 = range(0,8,2) print('Range 2 is equal to Range 3?', range2 == range3) print('Range 2 is', range2) print('Range 3 is', range3) print("Range2: ") for e in range2: print(e) print("Range3:") for e in range3: print(e) # NEGATIVE STEP range4 = range(40,-10,-10) print('\n', 'Range4 is', range4) for i in range4: print('\n', i) # EXECUTING RANGE INSIDE A FOR LOOP x = 5 for i in range(0,x): print(i) x = 8 # it doesnt change the range set in the loop condition x = 5 y = range(0,x) for i in y: print('\n', y) print(i) x = 8 # it doesnt change the range set in the loop condition
true
0240f939041db7bfe697fecd110ca33dd83f84b8
tocheng/Book-Exercises-Intro-to-Computing-using-Python
/Book-Chapter2_2-FE-odd-number.py
1,173
4.46875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 11 09:54:53 2020 Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed Book Chapter 2 Finger Exercises - Find the largest odd number @author: Atanas Kozarev - github.com/ultraasi-atanas """ # edge cases 100, 2, 3 and 100,2,-3 and 2,2,2 x = 301 y = 2 z = 1 # what if the largest number is not odd? We need to discard any non-odd numbers # if none of them are odd - go straight to else if (x % 2 != 0) or (y % 2 != 0) or (z % 2 != 0): #codeblock if we have some odd numbers print("ok") # initialising the variable with one odd number, so we check each in turn if (x % 2 != 0): largest = x elif (y % 2 != 0): largest = y elif (z % 2 != 0): largest = z # here we check each against the largest # no need to check for x as we did already if (y % 2 != 0): if y > largest: largest = y if (z % 2 != 0): if z > largest: largest = z print("The largest odd number is:", largest) print("The numbers were", x, y, z) else: print("No odd number found")
true
32edc5c1c32209e99e6b51d2bf0cb14ba3f1a07c
tocheng/Book-Exercises-Intro-to-Computing-using-Python
/Book-Chapter2_3-Exercises-LargestOddNumberOf10.py
1,186
4.28125
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 13 14:15:03 2020 Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed Book Chapter 2 Finger Exercises Largest Odd number of 10, using user input Prints the largest odd number that was entered If no odd number was entered, it should print a message to that effect @author: Atanas Kozarev - github.com/ultraasi-atanas """ # big goal is to handle and compare negative numbers entered # we will build in a logic that start with an initial value of 0 # and then the first odd value entered by the user is largest = 0 userPromptsRemaining = 10 print("You will be asked to enter a number 10 times") while userPromptsRemaining > 0: # get a number in newNumber = int(input("Please enter a number: ")) # check if it's odd if (newNumber % 2) != 0: # check if that's the first registered number if largest == 0: largest = newNumber elif newNumber > largest: # do we have found a new largest largest = newNumber userPromptsRemaining -= 1 if largest == 0: print("No odd numbers entered") else: print("Largest odd number entered ", largest)
true
8e04e0bc3911f87b01ccab4a8d70101f53bff593
stulew93/die-simulator
/dicesimulator.py
1,773
4.4375
4
import random def die_face_generator(digit: int) -> str: """ Function to create a basic render of a die face, of value equal to digit. If digit is not an integer between 1 and 6, function will return a warning. :param digit: Any integer. :return: str """ full_line = "-----------" middle_line = "| |" one_dot = "| o |" two_dot = "| o o |" if digit == 1: face_string = full_line + '\n' + middle_line + '\n' + one_dot + '\n' + middle_line + '\n' + full_line elif digit == 2: face_string = full_line + '\n' + middle_line + '\n' + two_dot + '\n' + middle_line + '\n' + full_line elif digit == 3: face_string = full_line + '\n' + one_dot + '\n' + one_dot + '\n' + one_dot + '\n' + full_line elif digit == 4: face_string = full_line + '\n' + two_dot + '\n' + middle_line + '\n' + two_dot + '\n' + full_line elif digit == 5: face_string = full_line + '\n' + two_dot + '\n' + one_dot + '\n' + two_dot + '\n' + full_line elif digit == 6: face_string = full_line + '\n' + two_dot + '\n' + two_dot + '\n' + two_dot + '\n' + full_line else: face_string = "This number doesn't exist on a regular die..?" return face_string if __name__ == '__main__': print("This is a die-rolling simulator. First roll:") while True: x = random.randint(1, 6) face = die_face_generator(x) print(face) print() command = input("r: roll again; q: quit\n") if command == 'q': print("Quitting...") break elif command == 'r': print("Rolling...") continue else: print("Entry not recognised. Quitting...") break
false
1b049dc1145f1269bcbf38c96965fa0b13d585ca
guyjacks/codementor-learn-python
/string_manipulation.py
872
4.1875
4
print "split your and last name" name = "guy jacks" # split returns a list of strings print name.split() print "/n" print "split a comma separated list of colors" colors = "yellow, black, blue" print colors.split(',') print "\n" print "get the 3rd character of the word banana" print "banana"[2] print "\n" blue_moon = "Blue Moon" print "get the first character of Blue Moon. get the last." print blue_moon[0] print blue_moon[-1] print "\n" print "get the last four characters of Blue Moon" print blue_moon[4:] print "\n" print "get the first four characters of Blue Moon" print blue_moon[:4] print "\n" print "get \"Moo\" from Blue Moon" print blue_moon[5:8] print "\n" print "replace Blue with Full in Blue Moon" print blue_moon.replace("Blue", "Full") print "\n" print "covert Blue Moon to lowercase. uppercase" print blue_moon.lower() print blue_moon.upper()
true
b67babb057054f9c58063cee41fdbc8244d23071
Chris-gde/exercicios
/algoritmo-Fabiano/22-3-exe1.py
249
4.21875
4
''' 1) Escreva um algoritmo para ler um valor e escrever o seu antecessor. usuario informa um valor valor=valor - 1 ''' num=int(input("Digite um numero qualquer: ")) valor=num - 1 print("O antecessor do numero digitado é: ", valor)
false
af1368faa37377ce0f6df653891f9104d5cd23b6
Chris-gde/exercicios
/algoritmo-Fabiano/03-05-exe4.py
699
4.15625
4
''' (4) - Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total. Obs. : somente são vendidos um número inteiro de latas. ''' tamanho =int(input("Informe quantos metros quadrados a serem pintados")) litros = tamanho / 3 if tamanho % 54 == 0: latas = tamanho / 54 else: latas = int(tamanho / 54) + 1 preco = latas * 80 print ('%d latas' %latas) print ('R$ %.2f' %preco)
false
3d0785a60c2af05e31ac80f61d05accc32a7b5e0
Chris-gde/exercicios
/algoritmo-Fabiano/31-05-desafio2.py
585
4.15625
4
''' Faça um programa onde o usuário informe a km inicial no momento que o tanque é cheio, no próximo abastecimento o usuário deve informar os km percorridos e a quantidade de combustível necessária para completar o tanque (l). O sistema deve informar a o consumo médio (km/l). ''' n=int(input("Informe a kilometragem inicial: ")) percorrido=int(input("Informe os kilometros percorridos: ")) litros=int(input("Informe a quantidade de combustivel necessária para completar o tanque: ")) km=percorrido-n consumo=km/litros print("Seu consumo médio foi: ",consumo)
false
427e6f0978cd52b339ef4f89256ace7ff9298c4d
learnthecraft617/dev-sprint1
/RAMP_UP_SPRINT1/exercise54.py
291
4.21875
4
def is_triangle (a, b, c): if a > b + c print "YES!" else print "NO!" is_triangle (4, 2, 5) #5.4 question = raw_input('Please enter 3 lengths to build this triangle in this order (a, b, c)/n') length = raw_input (a, b, c) is triangle (raw_input)
true
afed5225df3b7a8cc6b42ba7691710a8a019459d
colten-cross/CodeWarsChallenges---Python
/BouncingBalls.py
784
4.375
4
# A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known. # He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). # His mother looks out of a window 1.5 meters from the ground. # How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?# # Note: # The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter. # Example: # h = 3, bounce = 0.66, window = 1.5, result is 3 def bouncing_ball(h, bounce, window): Sightcount = 1 current = h * bounce while current > window: current *= bounce Sightcount += 2 return Sightcount
true
58f99618238ebedc92e013c8b47b259e1fb2b197
ryadav4/Python-codes-
/EX_05/Finding_largestno.py
263
4.28125
4
#find the largest number : largest = -1 print('Before',largest) for i in [1,45,67,12,100] : if i>largest : largest = i print(largest , i) else : print(i , 'is less than',largest) print('largest number is :', largest)
true
6faa436ab98bac3d2f6c556f8cb239c48ba72b0f
BusgeethPravesh/Python-Files
/Question6.py
1,549
4.15625
4
"""Write a Python program that will accept two lists of integer. Your program should create a third list such that it contain only odd numbers from the first list and even numbers from the second list.""" print("This Program will allow you to enter two list of 5 integers " "\nand will then print the odd numbers from list 1 and even numbers from list 2. ") tryagain="yes" while tryagain=="yes": count=0 list1=[] print("\nLIST 1:") while count<=4: addintegers=input("Enter integer:") list1.append(addintegers) count+=1 print("\nList 1:",list1) count=0 list2=[] print("\nLIST 2:") while count<=4: addintegers=input("Enter integer:") list2.append(addintegers) count+=1 print("\nList 1:",list1) print("List 2:",list2) even_numbers=[] odd_numbers=[] for addintegers in (list1): if int(addintegers)% 2 != 0: odd_numbers.append(addintegers) #else: # print("No Odd Number in LIST 1") for addintegers in (list2): if int(addintegers) % 2 == 0: even_numbers.append(addintegers) # else: # print("No Even Number in LIST 2") # print("\nOdd Numbers in List 1:", odd_numbers) # print("Even Numbers in List 2", even_numbers) print("\nOdd Numbers from List 1 and Even Numbers from List 2:",odd_numbers,even_numbers) tryagain = input("\nContinue? Yes/No?") if tryagain == " no ": break
true
f7789e9d8ba69c7974aa42131a6bf08c8cb8a293
vithalsamp/AlgosWithPython
/merge_insertion_sort.py
1,470
4.21875
4
# This program shows how to speed up merge sort using insertion sort def merge_insertion_sort(arr): if len(arr) > 1: mid = len(arr)//2 L = arr[mid:] R = arr[:mid] # Set threshold length of sub-arrays to use insertion sort # divide array if it is greater then 10 if len(L) > 10: merge_insertion_sort(L) if len(R) > 10: merge_insertion_sort(R) # use insertion sort to sort sub arrays insertion_sort(L) insertion_sort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] # Merging already sorted arrays while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Merge sort def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j+1] = arr[j] j = j - 1 arr[j+1] = key # main program arr = [10, 30, 1, 34, 54, 63, 5, 6, 7, 3, 1, 2, 2, 43, 765, 8, 56, 9, 45, 5, 2, 7, 0, 4, 2, 8, 3, 7, 9, 5] merge_insertion_sort(arr) print(arr)
false
04890c636e097a33fdad2ff75e9c00be0da9ee06
Oluyosola/micropilot-entry-challenge
/oluyosola/count_zeros.py
544
4.15625
4
# Write a function CountZeros(A) that takes in an array of integers A, and returns the number of 0's in that array. # For example, given [1, 0, 5, 6, 0, 2], the function/method should return 2. def countZeros(array): # count declared to be zero count=0 # loop through array length and count the number of zeros for m in range(0,len(array)): if array[m] == 0: count=count+1 return count # testing the function A = [1, 0, 5, 6, 0, 2] zeros_count=countZeros(A) print("Number of zeros is", zeros_count)
true
d9504458070080dca24cf9736564196369483c82
salmonofdoubt/TECH
/PROG/PY/py_wiki/wiki_code/w8e.py
1,551
4.125
4
#!/usr/bin/env python #8_Lists - test of knowledge def get_questions(): #Note that these are 3 lists return [["What color is the daytime sky on a clear day? ", "blue"], ["What is the answer to life, the universe and everything? ", "42"], ["What is a three letter word for mouse trap? ", "cat"]] def check_question(question_and_answer): #what element is the q, which one the a question = question_and_answer[0] answer = question_and_answer[1] given_answer = input(question) #give the question to the user if answer == given_answer: #compare the user's answer to the testers answer print("Correct") return True else: print("Incorrect, correct was:", answer) return False def run_test(questions): #runs through all the questions if len(questions) == 0: print("No questions were given.") return #the return exits the function index = 0 right = 0 while index < len(questions): if check_question(questions[index]): # Check the question, it extracts a q and a list from the lists of lists. right = right + 1 index = index + 1 # go to the next question print("You got", right * 100 / len(questions), # order of the computation, first multiply, then divide "% right out of", len(questions)) run_test(get_questions()) #let's run the questions
true
df7cfa7f74c9ac6d00ee5f0cb1c059aeac69febb
salmonofdoubt/TECH
/PROG/PY/dicts/ex40.py
800
4.1875
4
#!/usr/bin/env python # encoding: utf-8 """ Discription: dicts Created by André Baumann 2012 Copyright (c) Google Inc. 2012. All rights reserved. """ import sys from sys import exit import os def find_city(which_state, cities): if which_state in cities: return cities[which_state] else: return "Not found." def main(): cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Oregon' for key in cities: print key cities[key]() while True: print "State?: / ENTER to quit", which_state = raw_input("> ") if not which_state: break print find_city(which_state, cities) # simply calls find_city() with cities (the dict) # and the state (entered), prints the return value if __name__ == '__main__': main()
true
3de44b016d5b45e0670397bfe59d69aedb9bef33
salmonofdoubt/TECH
/PROG/PY/classes/dog.py
1,881
4.53125
5
#!/usr/bin/env python # encoding: utf-8 ''' How to use classes and subclasses - classes are templates Created by André Baumann on 2011-12-11. Copyright (c)2011 Google. All rights reserved. ''' import sys import os class Dog(object): # means Dog inherits from 'object' def __init__(self, name, breed): # __init__ is class constructor method self.name = name # initilizing the instance vars self.breed = breed #print self.name + ' created this Dog instance' def Bark(self): # classes also provide certain methods return 'barking!' def Greet(self): return 'Woof, I am ' + self.name def Rename(self, new_name): self.name = new_name return self.name def Owner(self, owner_id): self.owner = owner_id return 'Who owns '+ self.name +'? '+ self.owner +' does.' class Puppy(Dog): # creates a subclass of (now) superclass Dog def Bark(self): return 'Puppy wiff' # --- lets play with this ---------------------------------------------------: my_dog = Dog('Lou', 'Malti') # - instantiate Dog object, calling the # contructor method. Ignore 1st var 'self'. # - my_dog = Dog(breed='Malti', name='Lou') print my_dog.name # let'see this Dog's properties print my_dog.breed print my_dog.Bark() # let's use this Dog's methods print my_dog.Greet() my_dog.Rename('Lou2') print my_dog.Greet() print my_dog.Owner(u'André') # this method adds an instance variable that # was not previously defined in the class. # --- lets play with subclass -----------------------------------------------: my_puppy = Puppy('Louchen', 'Malti') print my_puppy.name print my_puppy.breed print my_puppy.Bark() # uses the new bark method from subclass # so subclasses EXTEND the superclass
true
2f3e14bec17b97afd523081d2e116dea6ddcd6d8
salmonofdoubt/TECH
/PROG/PY/py_wiki/wiki_code/w12a.py
434
4.125
4
#!/usr/bin/env python # 12_Modules import calendar year = int(input('Type in the bloody year: ')) calendar.setfirstweekday(calendar.SUNDAY) calendar.prcal(year) # Prints the calendar for an entire year as returned by calendar(). from time import time, ctime prev_time = "" while True: the_time = ctime(time()) if prev_time != the_time: print("The time is:", ctime(time())) prev_time = the_time
true
cb7e18fd05f7cb9b2bedb14e80ceef0c9d5591ea
molusca/Python
/learning_python/speed_radar.py
955
4.15625
4
''' A radar checks whether vehicles pass on the road within the 80km/h speed limit. If it is above the limit, the driver must pay a fine of 7 times the difference between the speed that he was trafficking and the speed limit. ''' def calculate_speed_difference(vehicle_speed, speed_limit): return (vehicle_speed - speed_limit) def calculate_fine_value(speed_difference, base_multiplier): return (speed_difference * base_multiplier) print('\nSPEED RADAR') vehicle_speed = int(input('\nVehicle speed (Km/h): ')) speed_limit = 80 base_multiplier = 7 speed_difference = calculate_speed_difference(vehicle_speed, speed_limit) fine_value = calculate_fine_value(speed_difference, base_multiplier) if vehicle_speed > speed_limit: print(f'\nThe vehicle was {speed_difference}Km/h above the speed limit and got fined!') print(f'The fine value is ${fine_value} !\n') else: print('\nThe vehicle was trafficking within the speed limit!\n')
true
18fa6287bdfec727517bb2073845c911f1494b2f
swatha96/python
/preDefinedDatatypes/tuple.py
928
4.25
4
## tuple is immutable(cant change) ## its have index starts from 0 ## enclosed with parenthesis () - defaultly it will take as tuple ## it can have duplicate value tup=(56,'swe',89,5,0,-6,'A','b',89) t=56,5,'swe' print(type(t)) ## it will return as tuple print(tup) print(type(tup)) ## it will return datatype as tuple print(tup[3]) ## print3rd index - 4th value tup[6]=45 ## cant assign (error : does not support item assignment) del tup[2] ## cant del (error : 'tuple' object does not support item deletion) s="asd",'swe','swe is a good girl',5,5 d=5,5,6,9,10 print(d) ## will print enclosed with parenthesis- it will considered as type tuple print(d[4]) print(type(d)) ## return type as tuple print(s) ## will print enclosed with parenthesis- it will considered as type tuple print(s[2]) print(type(s)) ## return - tuple del s[1] ## error :'tuple' object doesn't support item deletion
true
4205c5ca3e4edd81809135f9aa3f79323a0db129
swatha96/python
/numberDatatype.py
327
4.3125
4
#int #float #complex - real and imaginary number: eg:5 : it will return 5+0j #type() - to get the datatype - predefined function #input()- predefined function - to get the inputs from the user a=int(input("enter the number:")) b=float(input("enter the number:")) c=complex(input("enter the number:")) print(a,b,c)
true
317b17c8ac8c70a11950599c1c150feadf2cf034
swatha96/python
/large_number_list.py
478
4.1875
4
""" number=[23,98,56,26,96,63] number.sort() maxi=len(number) minus=maxi-1 for i in range(maxi): if(i==minus): print("the largest number is :",number[i]) """ number=[] n=int(input("how many numbers you wants to add:")) for i in range(n): num=int(input("enter the number:")) number.append(num) number.sort() maxi=len(number) minus=maxi-1 for i in range(maxi): if(i==minus): print("the largest number is :",number[i])
true
f341beabb8073553316b8c64b1b0c040a5c82b75
wf-Krystal/TestDemo
/PTestDemo/funcTest/funcTest4.py
1,128
4.40625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #案例5:计算传入的列表的最大值、最小值和平均值,并以元组的方式返回; import math def numdel(li): list = [] list.append(float(max(li))) list.append(float(min(li))) sum = 0 for i in li: sum += float(i) aver = sum/len(li) list.append(aver) return tuple(list) print("-------list-------", list) if __name__ == '__main__': list = input("please input a list,just contain number:",) #input()函数输入的是字符串str,若要用算术时,需要类型转换 li = list.split(',') print("tuple contain max_number,min_number and average_number:", numdel(li)) """ python2.x与python3.x中关于input()函数的区别: python2.x中有两种input 1.input() input("1")输入的类型是number;input("hello word")输入的类型是字符串str 即用户输入的是什么类型就是什么类型 2.raw_input() 不论输入什么,都是字符串类型,比如raw_input("123") = ‘123’ 字符串类型 python3.x只有一个input,功能等同于raw_input() 都是字符串类型 """
false
5fc71703fba3d7be429fa128215cb01ffa0f32c2
AliPollock/Morar-group-repository
/calculator.py
302
4.1875
4
x=int(input("enter value for x: ")) y=int(input("enter value for y: ")) symbol = input("enter operator ('*', '+', '-', '/'): ") if symbol == '*': print(x*y) elif symbol == '/': print(x/y) elif symbol == '+': print(x+y) elif symbol == '': print(x-y) else: print("invalid operator")
false
fc551bda83861e5a5f921668fc08d3e98b76307e
c344081/learning_algorithm
/01/48_Rotate_Image.py
1,544
4.3125
4
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Example 1: Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ] Example 2: Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ] ''' ''' 1, 2, 3, 4 5, 6, 7, 8 9, 10, 11, 12 13, 14, 15, 16 -> 1, 5, 9, 13 2, 6, 10, 14 3, 7, 11, 15 4, 8, 12, 16 -> 13, 9, 5, 1 14, 10, 6, 2 15, 11, 7, 3 16, 12, 8, 4 ''' class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if not matrix: return if len(matrix) == 0: return n = len(matrix[0]) for i in range(n): for j in range(i, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in range(n): for j in range(int(n * 0.5)): matrix[i][j] , matrix[i][n - j - 1] = matrix[i][n - j - 1], matrix[i][j] matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ] s = Solution() s.rotate(matrix) print(matrix)
true
f1251d29d364dd65a74150dcdd1c7b4e5a906bbc
009shanshukla/tkinter_tut_prog
/tkinter3.py
433
4.125
4
from tkinter import* root = Tk() ######making lable ####### one = Label(root, text="one", bg="red", fg="white") #bg stands for background color one.pack() #static label two = Label(root, text="two", bg="green", fg="black") two.pack(fill=X) #label that streches in x-dir three = Label(root, text="one", bg="red", fg="white") three.pack(side=LEFT, fill=Y) #label that streches in y-dir root.mainloop()
true
545bebe07bcdb15db70b76a9b011e85f1c5bc8b6
Guillermomartinez03/Tic_20_21
/python/ejercico_10.py
344
4.34375
4
'''10.Realizar un programa que al recibir un numero entero muestre por pantalla los 3 numeros anteriores y los 3 numeros siguientes al numero recibido''' def ejercicio_10 (): numero=input ("Escribe un numero entero:") print (numero-1), (numero-2), (numero-3) print (numero+1), (numero+2), (numero+3) ejercicio_10 ()
false
190ed822b9a78a3415282df127c15aec1a50333f
einian78/The-Complete-Python-3-Course-Beginner-to-Advanced-Udemy-Course
/Section 3 (Programming Basics)/4. Self-Defined Functions.py
1,129
4.375
4
# Without Arguments: def my_function(): # recommended style: snake case print("This is my function!") my_function() # This is my function # With Arguments: def my_function2(str1, str2): print(str1, str2) my_function2("Argument 1", "Argument 2") # Argument 1 Argument 2 my_function2("Hello", "World!") # Hello World! # Default Arguments def print_something(name="Unknown", age="Unknown"): print("My name is ", name, " and my age is ", age) print_something("Muiz", 23) # My name is Muiz and my age is 23 print_something() # My name is Unknown and my age is Unknown print_something("Muiz") # My Unknown is Unknown and my age is Unknown # Keyword Arguments print_something(age = 23) # My name is Unknown and my age is 23 print_something(name="Muiz", age=23) # My name is Muiz and my age is 23 # Infinite Arguments: def print_people(*people): for person in people: print("This is " + person) print_people("Muiz", "Sakib", "Fahad") # This is Muiz # This is Sakib # This is Fahad # Functions with return values: def do_math(n1, n2): return n1 + n2 print(do_math(1,2)) # 3
false
6f8af959758fad53d3a36b7da1fb1ea9aeca3777
einian78/The-Complete-Python-3-Course-Beginner-to-Advanced-Udemy-Course
/Section 3 (Programming Basics)/3. Built-in Functions.py
706
4.21875
4
# print(): prints whatever inside print("hi!") # hi! # str(): Converts any type into a string str(5) # 5 str(True) # True # int(): Converts any type into a integer int("5") # float(): Converts any type into a float float("5.6") print(float(1)) # 1.0 # bool(): Converts any type into a boolean bool("True") # len(): returns the length len("Hello There!") len([1,2,3,4,5,6,7]) len(["Hello", "Muiz"]) print(len(["Hello", "Muiz"])) # 2 # sorted(): sort an array/list in accending order arr = [16, 3,8,6,9,133,435,21,823,45] arr = sorted(arr) print(arr) # [3, 6, 8, 9, 16, 21, 45, 133, 435, 823] Str = ["A", "Z", "d", "c", "5.5", "1"] Str = sorted(Str) print(Str) # ['1', '5.5', 'A', 'Z', 'c', 'd']
true
91945d3b7d3fd6939c0d44e0a08fb8a5e6627af5
msheikomar/pythonsandbox
/Python/B05_T1_Dictionaries.py
420
4.21875
4
# Dict: # Name is String, Age is Integer and courses is List student = {'name':'John', 'age':25, 'courses':['Math', 'CompSys']} # To get value by using key print(student['name']) # To get value by using key print(student['courses']) # If you look at the keys are currently being string. But actually it can be any immutable data type #student = {1:'John', 'age':25, 'courses':['Math', 'CompSys']} #print(student[1])
true
8b393455be6e85cc3825b98fe857d7147c7c1806
msheikomar/pythonsandbox
/Python/B04_T1_Lists_Tuples_Sets.py
974
4.5
4
# Lists and Tuples allows us to work with sequential data # Sets are unordered collections of values with no duplicate # List Example courses = ['History', 'Math', 'Physics', 'ComSys'] # Create List with elements print(courses) # To print lists print(len(courses)) # To print length of list print(courses[0]) # To access first value from the list print(courses[3]) # To access last value from the list # We can use -ve index too to access last value of the list print("-ve index example") print(courses[-1]) # So zero is the first item of the list -1 is the last item of the list # List index error # print(courses[4]) # **List index out of range # Get first two values/items from the list print("Get first two values/items from the list") print(courses[0:2]) print(courses[:2]) # Alternative approach. You can leave off the start index as empty # Get values/items from the mid of the list and all the way end print(courses[2:]) # Leave the end index empty
true
d5c7efe1c7f1345be4b3fa2bdc3c1cb218c532e7
riya1794/python-practice
/py/list functions.py
815
4.25
4
list1 = [1,2,3] list2 = [4,5,6] print list1+list2 #[1,2,3,4,5,6] print list1*3 #[1,2,3,1,2,3,1,2,3] print 3 in list1 #True print 3 in list2 #False print "length of the list : " print len(list1) list3 = [1,2,3] print "comparsion of the 2 list : " print cmp(list1,list2) # -1 as list1 is smaller print cmp(list2,list1) # 1 as list2 is bigger print cmp(list1,list3) # 0 as same print max(list1) print min(list1) new_list = [] for i in range(6): new_list.append(i) print new_list new_list.append(3) print "list after appending 3", new_list print new_list.count(3) #count number of 3 in the list print new_list.index(2) print new_list.pop(0) print new_list.pop(-1) new_list.remove(2) print new_list new_list.reverse() print new_list list4 = [2,3,2,31,1,0] list4.sort() print list4
true
c6e4fa1d487e0c922865c44fa8042aad78cf6a96
crazymalady/Python-Exercises
/ielect_Meeting10/w10_e1fBC_ListOperations_Delete Elements.py
508
4.40625
4
def display(): try: # We can change the values of elements in a List. Lets take an example to understand this. # list of nos. list = [1,2,3,4,5,6] # Deleting 2nd element #del list[1] # Deleting elements from 3rd to 4th #del list[2:4] #print(list) # Deleting the whole list del list print(list) #if(list == -1): # print("EMPTY!") except: print("Something went wrong") display()
true
d63aa167926b91a246b0219af06e6ffec803a944
SahityaRoy/get-your-PR-accepted
/Sorting/Python/Insertion_Sort.py
532
4.21875
4
# Python program to implement Insertion Sort def insertion_sort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key # Driver function if __name__ == '__main__': nums=list(map(int,input().split())) insertion_sort(nums) # Calling the insertion_sort function by passing the 'nums' list # Printing the sorted list print(nums)
true
db188733063d2315b9ba8b8906b24576fc5883cc
SourabhSaraswat-191939/ADA-BT-CSE-501A
/Assignment-2/Insertion_Sort.py
1,740
4.5
4
#Insertion sort is used when number of elements is small. It can also be useful when input array # is almost sorted, only few elements are misplaced in complete big array. import time, random, sys sys.setrecursionlimit(3010) def insertionSortRecur(arr,n): if n<=1: return insertionSortRecur(arr,n-1) val = arr[n-1] j = n-2 while j>=0 and val<arr[j]: #compare value with its predecissors till we get the right position. arr[j+1] = arr[j] # performing swap here. j-=1 arr[j+1] = val # placing the value at right position. return arr def insertionSort(arr): # we are starting from 1 because there is no sense to compare value at 0 index with none. for i in range(1,len(arr)): val = arr[i] j = i-1 while j>=0 and val<arr[j]: #compare value with its predecissors till we get the right position. arr[j+1] = arr[j] # performing swap here. j-=1 arr[j+1] = val # placing the value at right position. return arr N = int(input("Enter the number of values you want to sort --> ")) numbers = [] for i in range(N): numbers.append(random.randint(0,N)) print(numbers) start = time.time() numbers = insertionSortRecur(numbers,N) end = time.time() print(numbers) print(f"Runtime of the program is {end - start}") # Time Complexity (Worst Case): O(n^2) # Time Complexity (Best Case): O(n) # Number of comparisons in Normal Insertion sort can be decreased by using Binary Search. # Insertion sort takes "n" comaprisons for "n-th interation" in worst case. # With the use of Binary Search with Insertion Sort, we can decrease comparison for "n-th interation" to "log(n)" in worst case.
true
279eaa1adb84a6362e50c16cbcf77fdb96b8c710
parinita08/Hacktoberfest2020_
/Python/wordGuess.py
1,664
4.3125
4
import random # This lib is used to choose a random word from the list of word # The user can feed his name name = input("What's your Name? ") print("Good Luck ! ", name) words = ['education', 'rainbow', 'computer', 'science', 'programming', 'python', 'mathematics', 'player', 'condition', 'reverse', 'water', 'board', 'hacktoberfest'] # Our function will choose a random from the give list word = random.choice(words) print("Guess the characters") guesses = '' # You can reduce/increase the number of turns turns = 10 while turns > 0: # This holds the number of times a user fails failed = 0 # The letter you feed is taken as input one at a time for char in word: # Comparing that character with our set if char in guesses: print(char) else: print("_") # For every failure 1 will be added in failed count failed += 1 if failed == 0: # The User will win the game if failure is 0 print("You Win") # This prints the correct word print("The word is: ", word) break # If user has input the wrong alphabet then the user is given a next chance guess = input("guess a character:") # Every input character will be stored in guesses guesses += guess # Check input with the character in word if guess not in word: turns -= 1 # if the character doesn’t match the word then “Wrong” will be given as output print("Wrong") # this will print the number of turns left print("You have", + turns, 'more guesses') if turns == 0: print("You Loose")
true
e9958c2817a63419482cd59df408a156cd3264ae
SwiftBean/Test1
/Name or Circle Area.py
656
4.40625
4
#Zach Page #9/13 #get a users name ##def get_name(): ### step one: ask user for name ## name = input("what's your name") ###step two: display the name back for user ## print("the name you entered was", name) ###step three: verify the name ## input("is this correct? yes or no") ## ##print("this is our function") ##get_name() #calculate the area of a circle #radius*radius*pi def areaofCircle(): pi=3.141592653 #1: Get a radius radius = input("what is the radius") #2: Calculate the area radius = float(radius) area = radius*radius*pi #3: Display the area print("the area of the circle is: ", area) areaofCircle()
true
297443115f368f6f74954748aea31cf38fdb3aad
abhikrish06/PythonPractice
/CCI/CCI_1_09_isSubstring.py
732
4.15625
4
# Given two strings, sl and s2, write code to check if s2 is a rotation of sl using only one # call to isSubstring (e.g., "waterbottle" is a rotation of"erbottlewat"). def isRotation(str1, str2): if len(str1) != len(str2): return False return isSubstring(str1 + str1, str2) def isSubstring(str1, str2): if len(str2) > len(str1): return False for i in range(len(str1) - len(str2) + 1): isSubstringexists = True for j in range(len(str2)): if str1[i + j] != str2[j]: isSubstringexists = False break if isSubstringexists: return True return False print(isRotation("abhikrish", "ishabhikr"))
true
ac98777c509e0e92d030fd29f9fc9e33e175d948
morvanTseng/paper
/TestDataGeneration/data_generation.py
2,653
4.125
4
import numpy as np class DataGenerator: """this class is for two dimensional data generation I create this class to generate 2-D data for testing algorithm Attributes: data: A 2-d numpy array inflated with 2-D data points has both minority and majority class labels: A 1-D numpy array inflated with 0 or 1 0 represent majority class, whereas 1 represent minority class """ def __init__(self, total_number, ratio): """init this class instance :param total_number: a int, indicating how many number of points you want to generate :param ratio: a float number, between 0 and 1, the ratio of majority against minority """ self.total_number = total_number self.ratio = ratio self.data = [] self.labels = [] def _generate_majority(self)->np.array: """this is for majority creation :return: a 2-D numpy array """ num_of_majority = self.total_number * self.ratio return np.random.random((int(num_of_majority), 2)) * 100 def _generate_minority(self)->np.array: """this is for minority creation :return: a 2-D numpy array """ num_of_minority = self.total_number - self.ratio * self.total_number center = num_of_minority * 0.2 left_bottom = num_of_minority * 0.25 right_bottom = num_of_minority * 0.05 left_top = num_of_minority * 0.2 right_top = num_of_minority * 0.3 center_area = 50 + (np.random.random((int(center), 2)) - 0.5) * 10 left_bottom_area = np.array([20, 15]) - (np.random.random((int(left_bottom), 2)) - np.array([0.5, 0.5])) * 10 right_bottom_area = np.array([90, 0]) + np.random.random((int(right_bottom), 2)) * 10 left_top_area = (np.random.random((int(left_top), 2)) * [2, 1]) * 10 + np.array([10, 70]) right_top_area = np.array([100, 100]) - np.random.random((int(right_top), 2)) * 15 return np.concatenate((right_top_area, center_area, left_bottom_area, right_bottom_area, left_top_area), axis=0) def generate(self)->np.array: """generate both majority class instances and minority class instances :return: a 2-d numpy array """ majority = self._generate_majority() for i in range(len(majority)): self.labels.append(0.) minority = self._generate_minority() for i in range(len(minority)): self.labels.append(1.) self.data, self.labels = np.concatenate((majority, minority), axis=0), np.array(self.labels) return self.data, self.labels
true
193ba136e0c667b84dcff683355aee443607c556
olessiap/glowing-journey-udacity
/6_drawingturtles.py
1,179
4.15625
4
# import turtle # # def draw_square(): # window = turtle.Screen() # window.bgcolor("white") # # brad = turtle.Turtle() # brad.shape("turtle") # brad.color("green") # brad.speed(2) # count = 0 # while count <= 3: # brad.forward(100) # brad.right(90) # count = count + 1 # angie = turtle.Turtle() # angie.shape("arrow") # angie.color("red") # angie.circle(100) # # tom = turtle.Turtle() # tom.color("blue") # tom.shape("circle") # count = 0 # while count <= 2: # tom.forward(320) # tom.left(120) # count = count + 1 # # window.exitonclick() # # draw_square() ###draw a circle from a bunch of squares (with better code)### import turtle def draw_shapes(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window = turtle.Screen() window.bgcolor("white") #create square brad brad = turtle.Turtle() brad.shape("turtle") brad.color("red") brad.speed(10) for i in range(1,37): draw_shapes(brad) brad.right(10) window.exitonclick() draw_art()
true
820b6dc8f092a7128bfd1b55d0db7f3b239d3f9a
olessiap/glowing-journey-udacity
/2_daysold.py
2,007
4.375
4
# Given your birthday and the current date, calculate your age # in days. Compensate for leap days. Assume that the birthday # and current date are correct dates (and no time travel). # Simply put, if you were born 1 Jan 2012 and todays date is # 2 Jan 2012 you are 1 day old. ##breaking down the problem ## #PSEUDOCODE for daysBetweenDates (3)# # # days = 0 # while date1 is before date2: #<--dateIsBefore (2) # date1 = day after date1 #<-- nextDay (1) # days = days + 1 # return days ## 1. nextDay - find next day assuming month has 30 days## def nextDay(year, month, day): if day < 30: return year, month, day + 1 else: if month < 12: return year, month + 1, 1 else: return year + 1, 1, 1 # print nextDay(2016, 10, 30) # print nextDay(2016, 12, 06) # print nextDay(2015, 12, 30) ## 2. helper procedure## def dateIsBefore(year1, month1, day1, year2, month2, day2): """returns True if year1-month1-day1 is before year2-month2-day2. otherwise, returns False""" if year1 < year2: return True if year1 == year2: if month1 < month2: return True if month1 == month2: return day1 < day2 return False print dateIsBefore(2016, 10, 06, 2016, 10, 07) # True print dateIsBefore(2016, 10, 06, 2016, 11, 06) # True print dateIsBefore(2018, 10, 06, 2017, 10, 06) # False ## 3. daysBetweenDates - approximate answers using the above nextDay procedure ### def daysBetweenDates(year1, month1, day1, year2, month2, day2): days = 0 while dateIsBefore(year1, month1, day1, year2, month2, day2): year1, month1, day1 = nextDay(year1, month1, day1) days += 1 return days print daysBetweenDates(2016, 10, 06, 2016, 10, 07) #>>1 print daysBetweenDates(2016, 10, 06, 2016, 11, 06) #>>30 print daysBetweenDates(2016, 10, 06, 2017, 10, 06) #>>360 print daysBetweenDates(2013, 1, 24, 2013, 6, 29) #>>155 print daysBetweenDates(2015, 1, 24, 2013, 6, 29) #>> 0
true
de922ab0471fc5b6976933148f4fcf09ff205cf2
tianyi33/Python
/river_cases.py
419
4.15625
4
river={'chang jiang':'china', 'huang he':'china', 'qian tang jiang':'china', 'nile':'egypt'} for name,location in river.items(): if location!="china": print(name.title()+" is not in my country.") else: print(name.title()+' is from my country!') for name,location in river.items(): print('\nthis river called '+ name.title()+' is located at '+location.title()) for name in river.keys(): print(name.title())
false
a9ab2e591e65123d33deb79ffc5467f5199a2f39
TeeGeeDee/adventOfCode2020
/Day4/day4.py
2,221
4.125
4
from typing import List def parse_records(records_raw:List[str]): """Turn list of raw string records (each record across multiple list entries) to list of dict structured output (one list entry per record) Parameters ---------- records_raw : List[str] List of records. Records are seperated by '' entries. strings of the form: 'key1:value1 key2:value2' for any number of key-value pairs Returns ------- records : List[dict] List of dicts, structuring the key-value pairs in the records """ records,my_record = [],'' for r in records_raw: if len(r)>0: my_record += ' '+r else: records += [dict([p.split(':') for p in my_record.split()])] my_record = '' return records def validate1(record: dict): return all([(fld in set(record.keys())) for fld in ['byr','iyr','eyr','hgt','hcl','ecl','pid']]) def validate2(record: dict): is_valid = validate1(record) if not is_valid: return False is_valid &= record['byr'].isnumeric() and 1920<=int(record['byr'])<=2002 is_valid &= record['iyr'].isnumeric() and 2010<=int(record['iyr'])<=2020 is_valid &= record['eyr'].isnumeric() and 2020<=int(record['eyr'])<=2030 is_valid &= ((record['hgt'][-2:]=='cm' and 150<=int(record['hgt'][:-2])<=193) or (record['hgt'][-2:]=='in' and 59<=int(record['hgt'][:-2])<=76) ) is_valid &= (record['hcl'][0]=='#' and len(record['hcl'][1:])==6 and all([c in 'abcdef0123456789' for c in record['hcl'][1:]]) ) is_valid &= record['ecl'] in ('amb','blu','brn','gry','grn','hzl','oth') is_valid &= record['pid'].isnumeric() and len(record['pid'])==9 return is_valid if __name__ == "__main__": with open("data.txt", "r") as f: records = [r.rstrip('\n') for r in f.readlines()] print('Number of valid records is {0}'.format(sum([validate1(r) for r in parse_records(records)]))) print('Number of valid records using second rule is {0}'.format(sum([validate2(r) for r in parse_records(records)])))
true
ad3564d330aba2b298de30d2f8b41ab2ca6891da
TeeGeeDee/adventOfCode2020
/Day3/day3.py
1,066
4.125
4
from typing import List from math import prod def traverse(down: int,right: int,terrain: List[str]): """ Counts number of trees passed when traversing terrane with given step sizes Parameters ---------- down: int number of steps to take down each iteration right: int number of steps to take right each iteration terrain: list of str representing terrain. '#' represents tree Returns ------- number of trees the traveral goes through """ y_pos,x_pos,num_trees = down,right,0 while y_pos<=len(terrain)-1: num_trees += terrain[y_pos][x_pos % len(terrain[y_pos])]=='#' y_pos += down x_pos += right return num_trees if __name__ == "__main__": with open("data.txt", "r") as f: slope = [x.rstrip('\n') for x in f.readlines()] params = [(1,1),(1,3),(1,5),(1,7),(2,1)] print('Number of trees his is {0}'.format(traverse(1,3,slope))) print('Product of trees seen is {0}'.format(prod([traverse(*p,slope) for p in params])))
true
9e72a3b63a392aff565a4cd4bbad93a433a4a29f
matthijskrul/ThinkPython
/src/Fourth Chapter/Exercise7.py
375
4.1875
4
# Write a fruitful function sum_to(n) that returns the sum of all integer numbers up to and including n. # So sum_to(10) would be 1+2+3...+10 which would return the value 55. def sum_to(n): s = 0 for i in range(1, n+1): s += i return s def sum_to_constant_complexity(n): return ((n*n)+n)/2 total = sum_to_constant_complexity(3242374) print(total)
true
90e3aa20ceca89debc99ef5b009ad413dd57c625
matthijskrul/ThinkPython
/src/Seventh Chapter/Exercise15.py
2,718
4.5
4
# You and your friend are in a team to write a two-player game, human against computer, such as Tic-Tac-Toe # / Noughts and Crosses. # Your friend will write the logic to play one round of the game, # while you will write the logic to allow many rounds of play, keep score, decide who plays, first, etc. # The two of you negotiate on how the two parts of the program will fit together, # and you come up with this simple scaffolding (which your friend will improve later) - see below. # 1) Write the main program which repeatedly calls this function to play the game, # and after each round it announces the outcome as “I win!”, “You win!”, or “Game drawn!”. # It then asks the player “Do you want to play again?” and either plays again, or says “Goodbye”, and terminates. # 2) Keep score of how many wins each player has had, and how many draws there have been. # After each round of play, also announce the scores. # 3) Add logic so that the players take turns to play first. # 4) Compute the percentage of wins for the human, out of all games played. Also announce this at the end of each round. def play_once(human_plays_first): """ Must play one round of the game. If the parameter is True, the human gets to play first, else the computer gets to play first. When the round ends, the return value of the function is one of -1 (human wins), 0 (game drawn), 1 (computer wins). """ # This is all dummy scaffolding code right at the moment... import random # See Modules chapter ... rng = random.Random() # Pick a random result between -1 and 1. result = rng.randrange(-1,2) print("Human plays first={0}, winner={1} " .format(human_plays_first, result)) return result def play_game(): wincount_player = 0 wincount_comp = 0 drawcount = 0 player_turn = True while True: result = play_once(player_turn) if result == -1: wincount_player += 1 print("You win!") elif result == 0: drawcount += 1 print("Game drawn!") else: wincount_comp += 1 print("I win!") player_turn = not player_turn print(f"Player wins: {wincount_player}, Computer Wins: {wincount_comp}, Draws: {drawcount}") print(f"Player wins percentage: {100*(wincount_player/(wincount_player + drawcount + wincount_comp))}%") while True: response = input("Do you want to play again? Type y or n") if response == "n": print("Goodbye!") return if response == "y": break play_game()
true
95bf5a53f5b665dec11f4171b5b4877d2f241f08
mohapsat/python-abspy
/tuples.py
592
4.15625
4
#!/usr/bin/python # tuple are immutable lists, whose values cannot be changed tup1 = (1,2,3) try: tup1.pop() except AttributeError: print "'tuple' object has no attribute 'pop':" + "Please pop from a list" print tup1 tup2 = tup1 * 3 print "lenght: %d Values: %s" %(len(tup2),tup2) tup3 = list(tup2) print tup3 tup4 = tuple('Hello') print tup4 x = 'o' not in tup4 print x tup3.sort(reverse=True) print tup3 #tup3.sort(reverse=True) #print "tup3 reverse sorted" tup3 for i in tup1: print "Value at %d is %s" %(tup1.index(i),i) for i in tup4: print "******* " + i +" ********"
false
4da17d0305a8c7473bd24624d04fb148a271bc7e
AbelCodes247/Google-Projects
/Calculator.py
1,240
4.375
4
#num1 = input("Enter a number: ") #num2 = input("Enter another number: ") #result = int(num1) + int(num2) #print(result) #Here, the calculator works the same way but the #Arithmetic operations need to be changed manually print("Select an operation to perform:") print("1. ADD") print("2. SUBTRACT") print("3. MULTIPLY") print("4. DIVIDE") operation = input() if operation == "1": num1 = input("Enter first number: ") num2 = input("Enter second number: ") print("The sum is " + str(int(num1) + int(num2))) elif operation == "2": num1 = input("Enter first number: ") num2 = input("Enter second number: ") print("The sum is " + str(int(num1) - int(num2))) elif operation == "3": num1 = input("Enter first number: ") num2 = input("Enter second number: ") print("The sum is " + str(int(num1) * int(num2))) elif operation == "4": num1 = input("Enter first number: ") num2 = input("Enter second number: ") print("The sum is " + str(int(num1) / int(num2))) else: print("Invalid Entry") #Here is a more complex calulator where it can accept #User input and can choose between the addition, #Subtraction, multiplication and division #If no input is entered, then it returns ("Invalid Entry")
true
49d4ae16fba58eaa1ebfeb45553eb575b6962b0a
EJohnston1986/100DaysOfPython
/DAY9 - Secret auction/practice/main.py
1,283
4.65625
5
# creating a dictionary student = {} # populating the dictionary with key value pairs student = {"Name": "John", "Age": 25, "Courses": ["Maths", "Physics"] } # printing data from dictionary print(student) # prints all key, value pairs print(student["name"]) # prints only value of named key # accessing key value pair using get method print(student.get("name")) # adding new key value pair to a dictionary student["phone"] = "01738 447385" # searching a dictionary for a key named "phone", returns not found if no result print(student.get("phone", "not found")) # changing information in a dictionary student["Name"] = "Jane" # using update function to update more than one piece of information, dictionary as argument student.update({"Name": "Steve", "Age": 27, "Courses": "Geology", "Phone": "2342145435"}) # deleting a dictionary key value pair del student["age"] # looping through keys and values of dictionary print(len(student)) # displays number of keys print(student.keys()) # displays all the keys print(student.values()) # displays all the values print(student.items()) # displays all key and value pairs for key, value in student.items(): # prints all key value pairs from loop print(key, value)
true
ed583b5475071835db5ac8067ccae943e10c432a
LavanyaJayaprakash7232/Python-code---oops
/line_oop.py
844
4.40625
4
''' To calculate the slope of a line and distance between two coordinates on the line ''' #defining class line class Line(): def __init__(self, co1, co2): self.co1 = co1 self.co2 = co2 #slope def slope(self): x1, y1 = self.co1 x2, y2 = self.co2 return (y2 - y1)/(x2 - x1) #distance def distance(self): x1, y1 = self.co1 x2, y2 = self.co2 return ((x2 - x1)**2 + (y2 -y1)**2)**(1/2) #User input of coordinates in the form of tuples co1 = tuple(int(a) for a in input("Enter the coordinate point 1\n").split()) co2 = tuple(int(b) for b in input("Enter the coordinate point 2\n").split()) myline = Line(co1, co2) slope = myline.slope() distance = myline.distance() print(f"The slope is {slope} and the distance is {distance}")
true
40fa436b40b1158b0057e8f5b13208acc748dd5d
a2606844292/vs-code
/慕课网/面向对象/c4.py
2,149
4.15625
4
class Student(): # 类方法 name = '' # 类变量 age = 0 sum = 0 def __init__(self, name, age): # self代表的是实例 self.name = name # 对实例变量进行赋值 self.age = age self.__score = 0 # 加__变成私有变量 # print('student') # print(self.name) self.__class__.sum += 1 print('当前班级学生总数为:'+str(self.__class__.sum)) def marking(self, score): self.__score = score if score < 0: return '分数不能为负数' print(self.name+'本次考试分数为:'+str(self.__score)) # 行为与特征 # 类方法 def do_homework(self): self.do_engilsig_homework() # 内部调用方法 print('do homework now') # self.__class__.sum += 1 # print('当前班级学生总数为:'+str(self.__class__.sum)) def do_engilsig_homework(self): print() # 类方法 #装饰器 @classmethod def plus_sum(cls): cls.sum += 1 print(cls.sum) # 静态方法 @staticmethod def add(x, y): print(Student.sum) print('This is a static method') Student1 = Student('xiaobai', 18) Student2 = Student('xiaohei', 18) resule = Student1.marking(-1) # 调用marking的方法 print(resule) # Student1.do_homework() # 不建议使用这种方法修改值 Student1.__score = -1 # python通过.为新增变量,所以不会报错 print(Student1.__score) # print(Student1.__dict__) # 与students进行对比检测 print(Student2._Student__score) # 访问私有变量 # r = Student1.score # 公开的public私有的private # print(Student1.score) # 静态方法调用 # Student1.add(1, 2) # Student.add(1, 2) # 类方法的调用 # Student1.plus_sum() # Student1.do_homework() #调用其它实例方法 # 实例方法调用 # Student2 = Student('xiaohei', 18) # Student1.plus_sum() # Student3 = Student('xiaoming', 18) # Student1.plus_sum() # print(Student1.name) # print(Student.sum) # print(Student1.__dict__) # print(Student.__dict__)
false
4d386f77d415e5e9335763ebb49bc683af7c0fbf
pbeata/DSc-Training
/Python/oop_classes.py
2,087
4.40625
4
import turtle class Polygon: def __init__(self, num_sides, name, size=100, color="black", lw=2): self.num_sides = num_sides self.name = name self.size = size # default size is 100 self.color = color self.lw = lw self.interior_angles_sum = (self.num_sides - 2) * 180 self.single_angle = self.interior_angles_sum / self.num_sides # print details about the attributes def print(self): print("\npolygon name:", self.name) print("number of sides:", self.num_sides) print("sum of interior angles:", self.interior_angles_sum) print("value for single angle:", self.single_angle) # draw the polygon shape def draw(self): turtle.color(self.color) turtle.pensize(self.lw) for i in range(self.num_sides): turtle.forward(self.size) turtle.right(180 - self.single_angle) turtle.done() # PART 1: The Basics # plaza = Polygon(4, "Square", 200, color="blue", lw=5) # plaza.print() # plaza.draw() # building = Polygon(5, "Pentagon") # building.print() # # building.draw() # stop_sign = Polygon(6, "Hexagon", 150, color="red", lw=5) # stop_sign.print() # stop_sign.draw() # PART 2: Inheritance and Subclassing class Square(Polygon): def __init__(self, size=100, color="black", lw=2): # Polygon is the "super" class super().__init__(4, "Square", size, color, lw) # overriding the member function from Polygon def draw(self): turtle.begin_fill() super().draw() turtle.end_fill() # square = Square(color="blue", size=200) # print(square.num_sides) # print(square.single_angle) # square.draw() # turtle.done() # PART 3: Operator Overloading import matplotlib.pyplot as plt class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): if isinstance(other, Point): x = self.x + other.x y = self.y + other.y else: x = self.x + other y = self.y + other return Point(x,y) def pplot(self): plt.plot(self.x, self.y, 'kx') plt.show() point1 = Point(4, 5) print(point1.x, point1.y) # point1.pplot() a = Point(1, 1) b = Point(2, 2) c = a + b print(c.x, c.y) d = a + 5 print(d.x, d.y)
true
2d840cb24543cc55b9cf78d8b5569286db52c510
pbeata/DSc-Training
/02-Udemy-DS-Bootcamp/exercise_84.py
1,097
4.15625
4
# Paul A. Beata # January 29, 2021 import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import skew def compute_skewness(x): n = len(x) x_mean = x.mean() a = x - x_mean b = a ** 3 numer = (1 / n) * b.sum() c = a ** 2 d = (1 / n) * c.sum() denom = (math.sqrt(d)) ** 3 x_skew = numer / denom return x_skew # Task 0 # load in our data set which has two columns labeled 'A' and 'B' data = pd.read_csv('./data/data_L84.csv') print(data.describe()) # Task 1 # compute skewness for data set A print("\nCompute SKEWNESS using custom code for data column A: ") a_skew = compute_skewness(data['A']) print(a_skew) print("\nCheck skewness result using scipy function skew() on data column A: ") print(skew(data['A'])) # Task 2 # compute skewness for data set B print("\nCompute SKEWNESS using custom code for data column B: ") b_skew = compute_skewness(data['B']) print(b_skew) print("\nCheck skewness result using scipy function skew() on data column B: ") print(skew(data['B']))
false
0e087f65ba7b781cda0568712dee4975a49a1bd1
OkelleyDevelopment/Caesar-Cipher
/caesar_cipher.py
1,258
4.21875
4
from string import ascii_letters def encrypt(message, key): lexicon = ascii_letters result = "" for char in message: if char not in lexicon: result += char else: new_key = (lexicon.index(char) + key) % len(lexicon) result += lexicon[new_key] return result def decrypt(message, key): return encrypt(message, (key * -1)) def main(): while True: print("\n============ Menu ============") print(*["1.Encrpyt", "2.Decrypt", "3.Quit"], sep="\n") user_choice = input("Choose an option: ").strip() or "3" if user_choice not in ("1", "2", "3"): print("ERROR: Please enter a valid choice!") elif user_choice == "1": message = input("Please enter the string to be encrypted: ") key = int(input("Please enter off-set: ").strip()) print(encrypt(message, key)) elif user_choice == "2": message = input("Please enter the string to be decrypted: ") key = int(input("Please enter off-set: ").strip()) print(decrypt(message, key)) elif user_choice == "3": print("Farewell.") break if __name__ == "__main__": main()
true
f194918b18cd8728d7f5ec5854152b8d5bc4cc2e
rarezhang/ucberkeley_cs61a
/lecture/l15_inheritance.py
987
4.46875
4
""" lecture 15 inheritance """ # inheritance # relating classes together # similar classes differ in their degree of specialization ## class <name>(<base class>) # example: checking account is a specialized type of account class Account: interest = 0.04 def __init__(self, account_holder): self.balance = 0 self.holder = account_holder def deposit(self, amount): self.balance = self.balance + amount return self.balance def withdraw(self, amount): if amount > self.balance: return 'insufficient funds' self.balance = self.balance - amount return self.balance class CheckingAccount(Account): withdraw_fee = 1 interest = 0.01 def withdraw(self, amount): return Account.withdraw(self, amount + self.withdraw_fee) ch = CheckingAccount('Tom') # calls Account.__init__ print(ch.interest) # can be found in CheckingAccount class print(ch.deposit(20)) # can be found in Account class print(ch.withdraw(5)) # can be found in CheckingAccount class
true