blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5a1da23b4558b4da778ae275f4fb8247735ff4f6
Grey-EightyPercent/Python-Learning
/ex18.py
778
4.40625
4
# Names, Variables, Code, Funcstions!!! 函数!! # this one is like your scripts with argv def print_two(*args): # use def to give the function name arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") # ok, that *args is actually pointless, we can just do This def print_two_again(arg1, arg2): pr...
true
904a6832d6427b1c93eed2231c7eb335d40b750c
apulijala/python-crash-course
/ch3-4/locations.py
1,007
4.28125
4
def places_to_visit(): locations = ["Varanasi", "Kedarnath", "Badrinath", "Dwaraka", "Ukraine"] print(f"Places to visit") print(locations) def places_to_visit_using_sorted(): locations = ["Varanasi", "Kedarnath", "Badrinath", "Dwaraka", "Ukraine"] print("\nSorted Locations") print(sorted(loca...
false
f40a4c7f84d966786da49f21e22eb1dcc349327b
apulijala/python-crash-course
/ch3-4/pizza.py
1,790
4.28125
4
def pizzas(): pizzas = ("Pepperoni", "Cheese", "Tomato") print("\n") for pizza in pizzas: print(f"I like {pizza}") print("I really love Pizza!") def pets(): pets = ("Dog", "Horse", "Cat") print("\n") for pet in pets: print(f"A {pet} would make a great Pet") print("Any o...
true
a7eb80d09873836fa28a834b76ede6d4696b8a81
apulijala/python-crash-course
/ch3-4/guest_list.py
2,058
4.15625
4
def guest_list(): guests = ["Krishna", "Rama", "Govinda", "Datta"] print("\n") for guest in guests: print(f"Jaya Guru Datta {guest}, Please come to my Dinner") """ Create a guest list minus one. Removing Govinda. """ def guest_list_minus_one(): guests = ["Krishna", "Rama", "Govinda...
false
a25342fe26e0766e5003e6839b661789fa916a53
SaentRayn/Data-Structures-By-Python
/Python Files/Set-Prob.py
835
4.375
4
def intersection(set1, set2): differentValues = set() # Add Code to only add values that are not in both sets to the differentValues # Hint: One need only cycle a value and check if it is in the other set return(differentValues) def union(set1, set2): unionOfSets = set() # Add code to add both the val...
true
50871b83a9b35cd72104f1684a6e6c30b9bd0aa5
jb240707/Google_IT_Automation_Python
/Interacting with OS/test_script.py
2,719
4.5
4
""" The create_python_script function creates a new python script in the current working directory, adds the line of comments to it declared by the 'comments' variable, and returns the size of the new file. Fill in the gaps to create a script called "program.py". """ import datetime import os def create_python_scri...
true
fa3f9e982b12fc3726adeebf47e40a9d4a475c18
Sannj/learn-python-in-a-day
/bmiCalc.py
796
4.21875
4
def calBMI(h, w): bmi = int(w)/(int(h)/100)**2 print('Your BMI is: {}'.format(round(bmi, 2))) bmi = round(bmi, 2) if bmi > 25: print('You have this sweetheart! You can get rid of those extra pounds!') elif bmi < 18.5: print('Omg. You need Nutella like right now! You need more pounds.') else: print('Keep mai...
true
68b6d97adc41e0aa374fc1235e342605aa8c9ae6
llakhi/python_program
/Practise_1.py
1,408
4.15625
4
# split a string and display separately filename = input("Type file name") print ("Filename : ",filename) print ("Split the file name and show ") data = filename.split('.') print("file name - " ,data[0]) print("file name - " ,data[1]) # Write a program and display all the duplicates of list alist = [10,20,30,10,...
true
bf5d24a9e92a2afe969b118890bce75e2f57d9cc
clive-bunting/computer-science
/Problem Set 2/probset2_1.py
745
4.25
4
balance = 4842 # the outstanding balance on the credit card annualInterestRate = 0.2 # annual interest rate as a decimal monthlyPaymentRate = 0.04 # minimum monthly payment rate as a decimal monthlyInterestRate = annualInterestRate / 12.0 totalPaid = 0.0 for month in range(1,13): minimumMonthlyPayment = monthlyPa...
true
0311b7f276f93289f83999eb43227c13283433f7
VovaRen/Tasks
/Tasks_2/Except.py
1,222
4.15625
4
# Функция принимает числа введённые пользователем # через пробел. # Необходимо вернуть их сумму, если # все элементы являются чилами и их # кол-во меньше 11. # Если какое-то из условий не соблюдается # вызвать исключение. def sum_nums(): """Функция складывает не более 10 целых чисел (чисел с плавающей ...
false
d46d1b419391f408934e1f1a94092d18f9c50d61
Irbah28/Python-Examples
/recursion_examples.py
1,365
4.3125
4
'''A few simple examples of recursion.''' def sum1(xs): '''We can recursively sum a list of numbers.''' if len(xs) == 0: return 0 else: return xs[0] + sum1(xs[1:]) def sum2(xs): '''Or do the same thing iteratively.''' y = 0 for x in xs: y += x return y def product1...
true
37a83e497842185ec4fa9c8126d959f1d38164b6
msmiel/mnemosyne
/books/Machine Learning/Machine Learning supp/code/chapter2/Divisors3.py
240
4.125
4
def divisors(num): count = 1 div = 2 while(div < num): if(num % div == 0): count = count + 1 div = div + 1 return count result = divisors(12) if(result == 1): print('12 is prime') else: print('12 is not prime')
true
22c635a85256152016cf90c55d2a68fb33335f24
s-andromeda/Two-Pointers-2
/Problem2.py
1,120
4.15625
4
from typing import List """ Student : Shahreen Shahjahan Psyche Time Complexity : O(N) Space Complexity : O(1) """ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. ...
true
0a7879e26edb46c5b55cdb9322997c8ffea49274
rohitharyani/LearningPython
/functionAndMethodsHw.py
1,927
4.28125
4
import math def volume(radius): ''' Calculate volume of a sphere based on the formula ''' return (4.0*math.pi*(radius**3))/3 print("Volume of sphere is: ",volume(3)) #----------------------------------- def valueInRange(num,low,high): ''' Check for a given value in a defined range ''' return "Value in ran...
true
9d21e3afdbd6b659169c55463e7415572fd96cfe
rohitharyani/LearningPython
/InheritanceAndPolymorphism.py
1,326
4.28125
4
#Inheritance class Animal(): def __init__(self): print("Animal Created") def who_am_i(self): print("I am an Animal") def eat(self): print("I am eating") class Dog(Animal): def __init__(self): Animal.__init__(self) print("Dog Created") def who_am_i(self): print("I am a dog") de...
false
63bc550f76e9a09cfdc638aa4969469f8068fe32
cornel-kim/MIT_Class_October
/lesson3a.py
820
4.1875
4
#we have covered, variables, data types and operators. #implement python logics. if else statements. conditinal statements #mpesa buy airtime- account you are buying for, account balance, # pin, okoa jahazi arrears. # Account = input("Please input the account number:") # Amount = input("Please input the amount or airti...
true
11d674f105b3d7851c61a501c946be7202432ed4
gabrielbolivar86/simple_python_scripts
/tire_volume.py
1,815
4.5625
5
#calculate the volume of a tire and storage it on TXT document #Libraries import math from datetime import date #1st get the data necesary to calculate the tire volume # tire_width = float(input("Enter the width of the tire in mm (ex 205): ")) # tire_aspect = float(input("Enter the aspect ratio of the tire (ex 60): "))...
true
894ea0771249c060f9bbd1f623d2a07b5a8c2bf2
hubbm-bbm101/lab5-exercise-solution-b2210356108
/Exercises/Exercise1.py
428
4.15625
4
number = int(input("Enter the number:")) if number % 2 == 0: oddnumber = number - 1 formulanumber = (oddnumber+1)/2 else: formulanumber = (number+1)/2 sumodd = formulanumber**2 print("Sum of odd numbers:", str(sumodd)) evennumbers = range(2,number,2) sumeven = 0 a = 0 for i in evennumbers: ...
true
08956994c6649c0e52b64fc54fd751d59ae8ce52
zephyr-c/oo-tic-tac-toe
/components.py
2,326
4.125
4
class Player(): """A player of the tic-tac-toe game""" def __init__(self, name, game_piece): self.name = name self.game_piece = game_piece class Move(): """A single move in the tic-tac-toe game""" def __init__(self, author, position): self.author = author self.position...
true
aeef567aa047d2190d91cb6dbb32b505fb7c6b04
michellejanosi/100-days-of-code
/projects/rock_paper_scissors.py
1,785
4.21875
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ...
false
d0e98e7202d56fbefd7264203a5d5851a425fbaa
michellejanosi/100-days-of-code
/projects/area_calc.py
621
4.3125
4
# You are painting a wall. The instructions on the paint can says that 1 can of paint can cover 6 square meters of wall. Given a random height and width of wall, calculate how many cans of paint you'll need to buy. # number of cans = (wall height ✖️ wall width) ÷ coverage per can. import math height = int(input("Hei...
true
5a54831a9faa524123b5c4cc35c95b022ad8ab4b
michellejanosi/100-days-of-code
/algorithms/leap_year.py
961
4.3125
4
# A program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February. # A leap year is on every year that is evenly divisible by 4 **except** every year that is evenly divisible by 100 **unless** the year is also evenly divisible by 400 def ...
true
50b6ab8a005c611d38156b585713391f42faa973
Eylon-42/classic-sudoku-py
/backtrack.py
2,746
4.125
4
import random def validate_sudoku(board, c=0): m = 3 c = 0 validate = False # check all 81 numbers while c < 81: i, j = divmod(c, 9) # the current cell coordinate i0, j0 = i - i % m, j - j % m # the start position of the 3 x 3 block current_number = board[i][j...
true
3789a408088b094e66aa0c7591ff3c93cd1515ca
trini7y/conjecture-proofs
/collatz_conjecture/collatz_sequence.py
480
4.3125
4
print( '''A program to see if the collatz conjecture is true \n''') print ("======****=================*****======= \n") number = int(input('Input any number: ')) def collazt(number): while number > 0: if number % 2 == 0: number = number // 2 elif number % 2 == 1: number = (3 * number) + ...
true
9329edbb60144923e0ec8aad296650d2edacee38
ThomasMcDaniel91/cs-sprint-challenge-hash-tables
/hashtables/ex3/ex3.py
1,242
4.1875
4
def intersection(arrays): """ YOUR CODE HERE """ # Your code here # create empty dict nums_dict = {} # create empty list result = [] # going through the first list in our list of lists for num in arrays[0]: # appending the values from the first list into our # di...
true
97ba0c6f0767147bca3924d5c37ac2516ea4150f
chinnagit/python
/sample.py
610
4.125
4
# name = raw_input('what is your name? ') # color = raw_input('what is your favorite color ') # # print('Hi '+name + ' likes ' + color) # weight = raw_input('what is your weight in pound? ') # weight_in_kgs = float(weight)/2.25 # print('{name} weight is ' + str(weight_in_kgs)) # # name = 'jayanth' # # print(name[-3:])...
true
64257fa443d9b6aa8c7cb8553087adc29454e048
julianruben/mycode
/dict01/dictChallenge.py
1,199
4.28125
4
#!/usr/bin/env python3 heroes= { "wolverine": {"real name": "James Howlett", "powers": "regeneration", "archenemy": "Sabertooth",}, "harry potter": {"real name": "Harry Potter", "powers": "magic", "...
true
b378875888e67a74f00b0e375b97d43e4e684b45
Montenierij/Algorithms
/Bipartite.py
1,731
4.15625
4
###################################################### # Jacob Montenieri # Introduction To Algorithms # Lab 9 # This lab goes over if a graph is bipartite or not. # This is determined by seeing if vertices can be # colored blue and red without having adjacent # matching colors. ################################...
true
eabb5ea3d79d26d0275b2a95e7136d842152c88b
elainew96/coding_exercises
/project_python/ch_01/hello.py
840
4.53125
5
''' Exercise: hello, hello! Objective: Write and call your own functions to learn how the program counter steps through code. You will write a program that introduces you and prints your favorite number. Write the body of the function print_favorite_number Write a function call at the end of the program that c...
true
40d31dc0ae389a1ee4b2a90df9d7d7ba766ec62d
MadhuriSarode/Python
/ICP1/Source Code/stringReverse.py
712
4.15625
4
# Get the input from user as a list of characters with spaces as separators input_List_of_characters = input("Enter a list elements separated by space ") print("\n") # Split the user list userList = input_List_of_characters.split() print("user list is ", userList) # Character list to string conversion inputString = ...
true
7164e6216b0549046af29246d672d5e5a8df21f4
UMDHackers/projects_langs
/factorial.py
242
4.125
4
#factorial def factorial(number): if number == 0: return 0 if number == 1: return 1 return number * factorial(number-1) #main number = input("Enter a number: ") print("number: "+ str(number) + " factorial "+ str(factorial(number)))
true
09ecb6d8c3b8b9ea03c27b38b5b5abf42483d45c
marceloamaro/Python-Mombaca
/Lista Aula06 - Listas e Tuplas/06.py
1,283
4.28125
4
"""Encapsule o código da questão anterior em uma função, que recebe a lista criada e a letra de uma operação. A função deve retornar o resultado da operação representada por esta letra de acordo com o enunciado da questão anterior.""" def operacao(lista,letra): if letra == "a" or letra == "A": print(f"Os d...
false
c455dd1391008f7185f4a6af94a6baf655ef0d88
marceloamaro/Python-Mombaca
/Lista Aula03 Decisões e Repetições/08.py
365
4.1875
4
""" Faça uma função que receba uma lista de números inteiros e retorne o maior elemento desta lista. Utilize o for """ lista = [] def criar(lista): for i in range(0, 10): lista.append(int(input(f"digite um valor para prosição {i}:"))) print(f"Voce digitou os valores da {lista}") print ("O maior ele...
false
2e1e3159f0361b5cfacd0c4917a4978a8228b0aa
marceloamaro/Python-Mombaca
/Lista Aula03 Decisões e Repetições/01.py
794
4.25
4
""" Escreva uma função que simule o funcionamento de um radar eletrônico. Essa função deve receber a velocidade do carro de um usuário. Caso ultrapasse 80 Km/h, exiba uma mensagem dizendo que o usuário foi multado. Nesse caso, exiba o valor da multa, cobrando R$ 90 reais pela infração + R$ 5 reais por km acima de 80 km...
false
105fe95176771abda3276207c93a49981716d7f0
marceloamaro/Python-Mombaca
/Lista Aula07 - Dicionários e Sets/05.py
668
4.25
4
"""Utilizando o dicionário criado na questão anterior faça: Uma função que retorne apenas os valores pares do dicionario da questão anterior Uma função que retorne apenasas chaves vogais do dicionário da questão anterior """ nome="marcelo" def estrutura(nome): dic = {x : [x for x in range(7) ] for x in nome} ...
false
dedd5f66fc529649a7120dfa62f024225b44eaf1
marceloamaro/Python-Mombaca
/Lista Aula06 - Listas e Tuplas/02.py
339
4.21875
4
"""Faça o mesmo que que se pede na questão anterior, mas a terceira lista não pode ter itens repetidos. """ lista1 = [1, 2, 3, 4, 5] lista2 = [5, 6, 7, 8, 9] def lista_final(lista1,lista2): lista3 = [] lista3.extend(lista1) lista3.extend(lista2) lista3 = set(lista3) print(f"{lista3}") lista_fina...
false
519288225b0eb3990bbfbe5a4c2968d9eb6c5a99
oldmonkandlinux/python-basics
/for.py
254
4.15625
4
''' for loop ''' for item in 'Ashish': print(item) for item1 in ['apples', 'mangoes', 'pears']: print(item1) for item2 in range(10): print(item2) for item3 in range(1, 10): print(item3) for item4 in range(1, 10, 2): print(item4)
false
d6f22db680a74d0f8623a7b0f41895a206582a23
vs666/Pirates-of-the-Pacific
/Coins.py
1,535
4.125
4
from data import * import random # coin class is used to check all the functionalities of coins in the game class Coin: # this is the compulsary constructor method def __init__(self): self.bitcoin = [] self.bcX = [] self.bcY = [] self.coin_amount = 12 self.initialize()...
false
325b1be9213bccac043365fdea0e961fef784612
tanvipenumudy/Competitive-Programming-Solutions
/HackerRank/Problem-Solving/equalize_the_array.py
2,087
4.34375
4
# Karl has an array of integers. He wants to reduce the array until all remaining elements are equal. # Determine the minimum number of elements to delete to reach his goal. # For example, if his array is arr = [1,2,2,3], we see that he can delete the 2 elements 1 and 3 leaving arr = [2,2]. # He could also delete bo...
true
d8bee4e1fa1b74568c8f4f30dbb9841b699edbf4
tanvipenumudy/Competitive-Programming-Solutions
/HackerRank/Python/python-evaluation.py
512
4.4375
4
# It helps in evaluating an expression. # The expression can be a Python statement, or a code object. ---> # >>> eval("9 + 5") # 14 # >>> x = 2 # >>> eval("x + 3") # 5 # eval() can also be used to work with Python keywords or defined # functions and variables. These would normally be stored as strings. --> # >>> ...
true
4d5d9e634d8c48382f373555a27501f490a5d941
irisnunezlpsr/class-samples
/assignmentTester.py
277
4.3125
4
# creates a variable called word and sets it equal to "bird" word = "bird" # sets word equal to itself concatenated with itself word = word + word # word is now equal it itself concatenated with itself times 2 word = word + word # should print birdbirdbirdbird print(word)
true
fa981020f339414abf2c9bc1347be190638b1488
pradeep14316/Python_Repo
/Python_exercise/ex13.py
393
4.28125
4
#Ask the user for a number and determine whether the number is prime or not. def get_number(): num = int(input("Enter a number:\n")) return num def prime_check(): 'check whether number is a prime or not' num = get_number() if (num % 2 != 0) and (num / num == 1): print(num,"is a prime numbe...
true
f93238b907911d6b990c1f03cc0050bf54c65d24
trevllew751/python3course
/bouncer.py
301
4.125
4
age = input("How old are you?\n") if age: age = int(age) if age >= 21: print("You can enter and you can drink") elif age >= 18: print("You can enter but you need a wristband") else: print("You cannot come in little one") else: print("Please enter an age")
true
bc40b023ec89a51b34fcb77aa27f7d80ea8c57cf
iscoct-universidad/dai
/practica1/simples/exercise2/bubble.py
486
4.46875
4
import numpy as np def bubbleSorting(array): length = len(array) for i in range(0, length - 1): for j in range(i, length): if array[i] > array[j]: temp = array[i] array[i] = array[j] array[j] = temp desiredLength = int(input("Int...
true
5d33c4b42e2198cac51d4f22db6776218aa1a68e
CatarinaBrendel/Lernen
/curso_em_video/Module 2/exer053.py
332
4.125
4
print "Enter a Phrase and I'll tell you if it is a Palindrome or not" sentence = str(raw_input("Your phrase here: > ")).strip().lower().replace(' ', '') pal = "" for i in sentence: pal = i + pal if pal == sentence: print "'{}' is a palindrome!".format(sentence) else: print "'{}' is NOT a palindrome!".format...
true
8ada8c672d4e4e5fc5d99621003aaefee3719531
SMGuellord/PythonTut
/moreOnFunctions.py
1,063
4.15625
4
#argument with a default value. def get_gender(sex='unknown'): if sex is 'm': sex = "Male" elif sex is 'f': sex = "Female" print(sex) #using keyword argument def dumb_sentence(name='Bucky', action='ate', item='tuna'): print(name, action, item) #undefined number of arguments def add_n...
true
484f0730135dfa75d2dda0ae46d0ca88f153156c
HuiJing-C/PythonLearning
/cjh/06object_oriented_programming/05instance_and_Class.py
1,315
4.15625
4
# 由于Python是动态语言,根据类创建的实例可以任意绑定属性。给实例绑定属性的方法是通过实例变量,或者通过self变量 class Student(object): age = 18 def __init__(self, name): self.name = name if __name__ == '__main__': s = Student("jack") s.score = 90 print(s.name, s.score) # jack 90 # 但是,如果Student类本身需要绑定一个属性呢?可以直接在class中定义属性,这种属性是类属性,归...
false
224e7e8d6fa1306e5f48dc35bd50487167de057d
HuiJing-C/PythonLearning
/cjh/06object_oriented_programming/03inheritance_polymorphism.py
1,309
4.28125
4
# 多态 inheritance 继承 polymorphism class Animal(object): def run(self): print("Animal Run") class Dog(Animal): pass class Cat(Animal): # 多态 def run(self): print("Cat Run") def run_twice(animal): animal.run() animal.run() class Fish(object): def run(self): print(...
false
a5b66740552298a3373bfb4cd1068337577e47fd
GinaFabienne/python-dev
/Day2/mathOperators.py
377
4.1875
4
3 + 5 4 - 2 3 * 2 8 / 2 #when you are dividing you almost always end up with a float print(8 / 4) print(type(8 / 4)) #powers print(2 ** 2) #PEMDAS (from left to right) #Order of operations in python #() #** #* / #+- #multiplication and division are priotitised the same but the one on left will happen first when they...
true
45664a37ca38d8c7ea8af599be1958f48fd697b4
bnoel2777/CSSI19
/Day10/review.py
458
4.125
4
def Greater(x,y): if x>=y: return x else: return y x = float(raw_input("Enter your first number")) y = float(raw_input("Enter your second number")) print Greater(x,y): def Concatnation(): x = raw_input("Enter a string") return x + x : print Concatnation(): def Add(x,y,z): x = (raw_input("Enter your fi...
true
1c05ba0af10868c703e8e69eb2a9a66b37417792
l1onh3art88/bikingIndustry
/bicycles.py
1,393
4.4375
4
#Classes mirror the bike industry. There are 3 classes: Bicycle, Bike Shops, #and Customers class Bicycle(object): def __init__(self, model, weight, cost): self.model = model self.weight = weight self.cost = cost class BikeShop(object): def __init__(self, name,profit): ...
true
c88c866abdba67fee284b4f0eb3e62d286f24fc7
AvidDollars/project-euler-solutions-python
/2_even_fibonacci_numbers.py
1,458
4.125
4
""" Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. """ ...
true
3099801b30fc5781b0a94e2f250363cadb382477
saramissak/GWC-mini-projects
/TextAdventure.py
1,111
4.21875
4
# Update this text to match your story. start = ''' You wake up one morning and find that you aren't in your bed; you aren't even in your room. You're in the middle of a giant maze A sign is hanging from the ivy: "You have one hour. Don't touch the walls." There is a hallway to your right and to your left.''' print(...
true
b7b4e5ffde731bcfec622c9f55f0e18093c32a65
RishikaMachina/MySuper30
/Precourse 2/Exercise2.py
997
4.28125
4
def quicksort(arr): #when left part of right part is left with one number or no number; stop the recursion if (len(arr) ==0) or (len(arr)==1): return arr #considering first element as pivot pivot = arr[0] i = 0 for j in range(len(arr)): if arr[j] < pivot: # swap value...
true
01b89b6636c319d4daccf5c77c840755c4dc5270
robbiecares/Automate-the-Boring-Stuff
/07/RegexStripv2_firsttry.py
1,070
4.4375
4
# ! python3 # RegexStrip_firsttry.py - a regex version of the .strip method import re string = "***$123$***" #string = input("Please enter a string: ") StripChar = "*" #StripChar = input('''Please input the character that you'd like to trim from the ends of the string. If you'd like to trim whitespace only just press...
true
2acb1ff10853ef3a92daadb62f6e76f15cf0d061
Bradleyjr/E2020
/section_4/assignment_4b.py
403
4.1875
4
# This program draws form turtle import * # bgcolor() changes bgcolor("lightblue) color"red") shape("turtle" penup() # The crawl variable is used to crawl = 10 # The turn variable is used to turn = 35 for i in range(50): # stamp() is used to stamp() # With each loop, crawl is crawl = crawl + 3 ...
true
3740003dc7f81406634dfb7f77d617b6dc08a5cb
ShehryarX/python-cheatsheet
/classes.py
1,120
4.25
4
# A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object # Create class class User: # Constructor def __init__(self, name, email, age): self.name = name self.email = email self.age = age def gre...
true
8c08db7f77659258a8b3e0f9b61d4d7b5d271d00
TylerA73/Shapes
/triangle.py
2,989
4.25
4
# Imports import math from shape import Shape # Triangle class # Contains all of the details of the Triangle class Triangle(Shape): # __init__: Constructor # Construcst the Triangle # Sides of a Triangle: a, b, c def __init__(self, a, b, c): self.a = a self.b = b self.c = c ...
true
0b96f728e58497b9b1212fe6c3c7510de8a80b0f
LaxmiNarayanaMurthyVemuri/Mentor216A-CSPP-1
/FinalExam-Solutions/assignment3/tokenize.py
684
4.21875
4
''' Write a function to tokenize a given string and return a dictionary with the frequency of each word ''' import re def tokenize(string): ''' TOKENIZE ''' dictionary = {} for i in string: if i not in dictionary: dictionary[i] = 1 else: dictionary[i] += 1 ...
false
7d39246616234177c780e233239c93b30c5c5c51
vivsvaan/DSA-Python
/Mathematics/prime_factors.py
644
4.15625
4
""" Program to get prime factors of a number """ def prime_factors(number): res = [] if number <= 1: return res while not number % 2: res.append(2) number = number // 2 while not number % 3: res.append(3) number = number // 3 i = 5 while i*i < numbe...
false
2ce3222238c8087c4a7f8584bc1077a31ef2b52e
vivsvaan/DSA-Python
/Mathematics/palindrome_number.py
390
4.21875
4
""" Program to check if number is palindrome """ def is_palindrome(number): num = number reverse = 0 while num != 0: last_digit = num % 10 reverse = reverse*10 + last_digit num = num // 10 if reverse == number: return True return False number = int(input("Ente...
true
358aab90c724826fa6b63ca69d34fc461d29c854
ComradeMudkipz/lwp3
/Chapter 3/instanceJoe.py
619
4.21875
4
# Chapter 3 # turtleInstance.py - Program which uses multiple turtles on screen. import turtle # Set up the window environment wn = turtle.Screen() wn.bgcolor('lightgreen') wn.title('Tess & Alex') # Create tess and set some attributes tess = turtle.Turtle() tess.color('hotpink') tess.pensize(5) # Create alex alex ...
true
c4d1e4b637c7fca7810d69f54fa8e42c300c9550
ComradeMudkipz/lwp3
/Chapter 2/alarmClockConverter.py
623
4.53125
5
# Chapter 2 - Exercise 8 # alarmClockConverter.py - Converts the time (24 hr) with the number of hours # inputted and hours to pass. # Prompt for current time and sets to an integer timeNowPrompt = input("What time is it now? " ) timeNow = int(timeNowPrompt) # Prompt for number of hours to pass and sets to an integer...
true
fe8779680512758d6c1e991aab1053c3a46661f0
khanmazhar/python-journey
/task_lab.py
563
4.125
4
x = input('Enter a number.') y = input('Enter another number.') try: x_num = float(x) y_num = float(y) except: print('Invalid Input! Try again...') quit() if x_num % 2 == 1 and y_num % 2 == 1: print('Product of x and y is', x_num * y_num) if y_num % 11 == 0 and y_num % 13 != 0: if x_num % 11 ...
true
3b2dd979e59a1aee6beb6552c14033aae721d0f7
Xolo-T/Play-doh
/Python/Basics/conditions.py
1,923
4.34375
4
# you dont need brackets in your conditions # elif instead of else if # after contion we just add a ':' # ----------------------------------------------------------------------------- # Conditional # ----------------------------------------------------------------------------- # if, elif, els...
true
f22f0b9803f963e0ba0283ad810a6aea49065cf0
Xolo-T/Play-doh
/Python/Basics/generators.py
414
4.21875
4
# help us generate a sequence of values # a generator is a subset of iterable # a generator funtion is created using the range and the yeild keywords # yield poses the funtion and returns to it when next is called # next can only be called as much as the length of the range def generator_fn(num): for i in range...
true
b403cef706ae3a3e6e47c28dbe881b374f7087af
kritik-Trellis/python-Training
/Examples/checkprime.py
463
4.125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 10:39:11 2020 @author: trellis """ import math n=int(input("Enter the number of values you want to enter")) values=[int(input("Enter the values")) for i in range(n)] def checkPrime(num): for i in range(2,int(math.sqrt(num))+1): if(num%i==0): re...
true
e1ec56591180c7138000e62bcecc207664636791
jam941/hw
/hw06/selection_sort.py
1,818
4.4375
4
''' Author: Jarred Moyer <jam4936@rit.edu> Title: selection_sort.py Language: python3 Description: Uses selective sorting to sort a list from a file specified by the user. Assignment: Hw07 1: Insertion sort preforms better than selection sort the more sorted the list is initially. For example: the test case [1,2,3...
true
2711c8cfe027ee38dd9f6125d5256513f6475ddd
ellyanalinden/mad-libs
/mad-libs/Mad Lib/mad-libs/languageparts.py
1,554
4.46875
4
#!/usr/bin/env python # import modules here import random # Create a dictionary of language parts. It must contain: noun, verb, adjective. # The key should be one of the types of language (e.g. noun) and the value # should be the list of words that you choose. lang_parts = { 'noun': ['man', 'mountain', '...
true
52ea24de292acecbc102d5ea98fdb9412b2eb914
KevinQL/LGajes
/PYTHON/POO VIII. Herencia III - V31.py
978
4.21875
4
""" HERENCIA: Uso de dos funciones más utilizadas en python super() isinstance(9) Vocabulario: principio de sustentación ::: clasPadre "Es siempre un/a" clasHija ## isinstance(objeto, Clase) """ class Persona(): def __init__(self, nombre, edad, lugarResidencia): self.nombre = nombre self.edad = edad...
false
2a273126ad102d44f6bb4edf63f69acae261e01c
stratosm/NLP_modules
/src/class_ratio.py
662
4.25
4
# Author: Stratos Mansalis import pandas as pd def ratio_(df, cl): """ Calculates the frequency by class of the dataframe Arguments --------- df: the given dataframe cl: the name of the class Usage ----- df = ratio_(data, 'class') Re...
true
c3db6e40e20d3b746432443038ce632c370654b3
stein212/turtleProject
/tryTurtle.py
1,856
4.21875
4
import turtle # hide turtle turtle.ht() # or turtle.hideturtle() # set turtle speed to fastest turtle.speed(0) # fastest: 0 # fast: 10 # normal: 6 # slow: 3 # slowest: 1 # draw square manually for i in range(4): turtle.forward(10) turtle.left(90) # move turtle position turtle.penup() turtle.setpos(30, 0) turtle....
true
1b43aa798eec9071c0dc44fd4545494909506ec6
miraclecyq/pythonwork
/coffeeghost-q-in-py.py
975
4.15625
4
# -*- coding:utf-8 -*- # Quick Python Script Explanation for Programme # 给程序员的超快速Python脚本解说 import os def main(): print 'Hello World!' print "这是Alice\'的问候。" print '这是Bob\'的问候。' foo(5,10) print '=' * 10 print '这将直接执行'+os.getcwd() counter = 0 #变量得先实例化才可进一步计算 counter += 1 print...
false
956d829748aba3d4a631e871449e8468b21672bc
claudiuclement/Coursera-Data-Science-with-Python
/Week2-word-counter-problem.py
483
4.46875
4
#Word counter problem - Week 2 #This code is much simpler than the code provided by the course tutor #Code used below from collections import Counter #opens the file. the with statement here will automatically close it afterwards. with open("/Users/Claudiu/Downloads/word_cloud/98-0.txt") as input_file: #build a c...
true
669cf95f8ca83e5586452b090f1ebf1267a3c161
farahzuot/data-structures-and-algorithms-python
/tests/challenges/test_array_shipt.py
693
4.3125
4
from data_structures_and_algorithms.challenges.array_shift.array_shift import insertShiftArray """ type of list type of num add a number to odd list add a number to even list """ def test_list_type(): actual = insertShiftArray(5,4) expected = 'invalid input' assert actual == expected def test_num_type()...
true
00a3dd214090957c8387f75df441feb07360f7e3
farahzuot/data-structures-and-algorithms-python
/data_structures_and_algorithms/challenges/ll_zip/ll_zip.py
872
4.1875
4
# from data_structures_and_algorithms.data_structures.linked_list.linked_list import Linked_list def zipLists(first_l,sec_l): if type(first_l) != list or type(sec_l) != list: return "invalid input" ''' this function takes in two linked lists as arguments. Zip the two linked lists together into one ...
true
ff2f8db32772d21a9677160e1eb38564ddeee223
farahzuot/data-structures-and-algorithms-python
/tests/challenges/test_ll_zip.py
925
4.21875
4
from data_structures_and_algorithms.challenges.ll_zip.ll_zip import zipLists def test_happy_path(): ''' this function will test the normal path ''' actual = zipLists([1,2,3],[1,2,3]) expected = [1,1,2,2,3,3] assert actual == expected def test_invilid_input(): ''' this function will tes...
true
c630c22542fbde46f0a585d5b0e58dca12b840e0
malloryeastburn/Python
/pw.py
724
4.125
4
#! python3 # pw.py - An insecure password locker program. # password dict PASSWORD = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6', 'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt', 'luggage': '12345'} import sys, pyperclip # if user forgets to include a command line argument, instruct user if len(sy...
true
06eea92ff092eef3df728b082305ff0eb792b444
izark99/100DaysPython
/Day004/day4.4_rock_paper_scissors.py
1,259
4.25
4
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ...
false
49c4065b5e8c44814d8fb0cf973aec16b8e0cc74
helloworld755/Python_Algorithms
/dz2_task6.py
1,042
4.125
4
# В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать # не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше # введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, # то вывести загаданное число. fro...
false
fd00067ec525dd0f4be2d2fa29c9b9e6e4866f5b
reisthi/python-excercises
/tuples.py
1,258
4.25
4
"""Tuple exercises""" # Tuples and strings are immutable # A single item is not a tuple item. Ex: tuple = (1) # Unless you add a comma in the end. Ex: tuple = (1,) def get_oldest(bar1, bar2): """Return earliest of two MM/DD/YYYY-formatted date strings.""" year_one, year_two = bar1.split('/')[-1], bar2.split('...
true
12c9bd5d17c032731f1c5898b22c81f0086149a3
reisthi/python-excercises
/lists.py
925
4.4375
4
"""List exercises""" list_one = ['a', 'b', 'c', 1, 2, 3] list_deux = ["Un", "deux", "trois"] list_trois = ["Un", "deux", "trois"] list_quatre = ["UN", "deux", "trois"] def combine_lists(one, two): """Return a new list that combines the two given lists.""" return one + two def rotate_list(my_list): """M...
true
b19c48279f02a322bcfff4cca970090a2ec1b5e2
Ernest93/Ernest93
/Zajęcia 3.py
2,542
4.25
4
""" #escapowanie znaków specjlanych zmienna = r"To jest jakiś \ntekst z użytym znakiem nowej lini który ni będzie interpretowany" print(zmienna) zmienna = 'To jest jakiś: "tekst" z użytym cudzysłowem' print(zmienna) zmienna = 'To jest \n nowa linia' print(zmienna) """ #kilka sposobów na formatowanie stringów """ war...
false
feb9c24aa6bedfcae32654759a74b239fb3e84b1
vyashole/learn
/03-logic.py
835
4.34375
4
# just declaring some variables for use here x = 5 y = 10.5 z = 5 # Booleans: Booleans are logical values that can be True or False # you can use logical operators to check if an expression is True or False print(y > x) # True print(x == y) # False print(z < x) # True # Here are the different operators # This will...
true
5bef3ff143aefaf55973e00c9c52264afb50ab32
nhat117/Hello-World
/condition/con.py
431
4.125
4
a = 10 b = 10 c = 5 d = 5 if (a > b): print("Hello World") if (a != b): print("Hello World") if(a == b): print("Yes") else : print("No") #else if is elif if (a == b) : print("1") elif (a > b) : print("2") else : print("3") #and operator if a == b and c == d: print("Hello") #or operator if a == b or c == d :...
false
a91cb26dbc8806d7c72744322c1075839c73fa76
aambrioso1/CS-Projects
/tictactoe.py
2,302
4.125
4
# A program for solving the monkey tictactoe problem. # A list of rows in the game board row_list = ['COW', 'XXO', 'ABC'] # Other test games: # row_list = ['AAA', 'BBB', 'CCC'] # single winners: 3, doublewinners: 0 # row_list = ['ABA', 'BAB', 'ABA'] # single winners: 1, doublewinners: 1 # row_list = ['...
true
b47b3013b01d68ccd576d3fb31c2c899e6ac307f
aambrioso1/CS-Projects
/mumble.py
771
4.21875
4
def word_parse(text): 'Breaks up text into words defined as characters separted by a space' low = 0 # Position of the beginning of a word hi = 0 # Position of the end of a word word_list = [] for i in text: if i ==' ': # Check if we reached the end of a word word_list.a...
true
98a8af5f21dd3854aa73a14d49f6023fa692f77b
gauthamkrishna1312/python-basics
/Loop/Stars.py
320
4.125
4
num = int(input("Enter height : ")) row = 0 while row < num: space = num - row - 1 while space > 0: print(end =" ") space = space - 1 star = row + 1 while star > 0: print("*",end=" ") star = star - 1 row = row + 1 print() else: print("\n\nStar Finished")
false
079e25d42ab313c66358ed881aae7c2381bd5253
willkc15/CodingCurriculum
/01_Core/week05/submissions/pythonClasses.py
601
4.15625
4
#Abstract Class class Animal(): def __init__(self, name): self.name = name print("Hello, I'm {}".format(self.name)) def who_ami_i(self): raise NotImplementedError("Cannot create instances of an abstract class") class Dog(Animal): def who_am_i(self): print("I am a dog") ...
false
084402ba521a98fe595349274e8d499d5ddd6d20
cristinamais/exercicios_python
/Exercicios Loop/exercicio 22 - secao 06.py
701
4.28125
4
""" 22 - Escreva um programa completo que permita a qualquer aluno introduzir, pelo teclado, uma sequencia arbitrária de notas (válidas no intervalo de 10 a 20) e que mostre na tela, como resultado, a correspondente média aritmética. O número de notas com que o aluno pretenda efetuar o cálculo não será fornecido ao pro...
false
7fcdd203f8b6090aae41315e5640907f6d3d309e
cristinamais/exercicios_python
/Exercicios Colecoes Python/exercicio 02 - secao 07 - p1.py
513
4.21875
4
""" 02 - Crie um programa que lê 6 valores inteiros e, em seguida, mostre na tela os valores lidos """ # Minha resolução: """ listaN = [] for n in range(6): n = int(input('Digite o número: ')) listaN.append() print(f'O número digitado foi: {n}') """ # Resolução do professor. valores = [] # Re...
false
837d2e63f6492cad69210c57689589602a785a8a
cristinamais/exercicios_python
/Exercicios Loop/exercicio 47 - secao 06.py
1,594
4.375
4
""" 47 - Faça um programa que apresente um menu de opções para o cálculo das seguintes operações entre dois números: Adicao (opção 1) ..subtracao (opção 2)... multiplicacao (opção 3).. divisao (opção 4).. saida (opção 5) O programa deve possibilitar ao usuário a escolha da operação desejada, a exibição do resultado e a...
false
7ece04482a9465d97127a7d629af0531789a3594
cristinamais/exercicios_python
/Exercicios Estruturas Logicas e Condicionais/exercicio 01 - secao 05.py
501
4.125
4
""" 1 - Faça um programa que receba dois números e mostre qual deles é o maior. """ numero1 = int(input("Digite o primeiro número: ")) numero2 = int(input("Digite o segundo número: ")) if numero1 > numero2: print(f"Entre os números {numero1} e {numero2} .O número maior é: {numero1}") elif numero1 == numero2: ...
false
963ed4b25d1b60cda07b890614d5f6e6a4c5dc91
cristinamais/exercicios_python
/Exercicios Loop/exercicio 21 - secao 06.py
587
4.15625
4
""" 21 - Faça um programa que receba dois números. Calcule e mostre: a) A soma dos números pares desse intervalo de números, incluindo os números digitados; b) A multiplicação dos números ímpares desse intervalo, incluindo os digitados. """ numero1 = int(input('Digite o primeiro numero: ')) numero2 = int(input('Digite...
false
c08b69591c6d83f2f6de52e42ff44541bdfe8aeb
cristinamais/exercicios_python
/Exercicios Estruturas Logicas e Condicionais/exercicio 03 - secao 05.py
366
4.125
4
""" 3 - Leia um número real. Se o número for positivo imprima a raiz quadrada. Do contrário, imprima o número ao quadrado. """ numero = float(input("Digite um número: ")) if numero > 0: numero = numero ** (1/2) print(f'A raiz quadrada desse número é {numero:.2f}.') else: numero = numero ** 2 print(f'Es...
false
54cf8fa431ac0ab108f7f4bf8786d1f6f8ca70a3
cristinamais/exercicios_python
/Exercicios Loop/exercicio 49 - secao 06.py
1,125
4.21875
4
""" 49 - O funcionário chamado Carlos tem um colega chamado João que recebe um salário que equivale a um terço do seu salário. Carlos gosta de fazer aplicações na caderneta de poupança e vai aplicar seu salário integralmente nela, pois está rendendo 2% ao mês. João aplicará seu salário integralmente no fundo de renda f...
false
03306a34c58b5b490b157a3f261659b6b58406fd
cristinamais/exercicios_python
/Exercicios Estruturas Logicas e Condicionais/exercicio 13 - secao 05.py
1,247
4.34375
4
""" 13 - Faça um algorítmo que calcule a média ponderada das notas de 3 provas. A primeira e a segunda prova tem peso 1 e a terceira tem peso 2. Ao final, mostrar a média do aluno e indicar se o aluno foi aprovado ou reprovado. A nota para a aprovação deve ser igual ou superior a 60 pontos. """ nota1 = float(input("Di...
false
b12e1e77f9e87c3da76d4d8f0bd19f14b85d96d3
cristinamais/exercicios_python
/Exercicios Colecoes Python/exercicio 24 - secao 07 - p1.py
789
4.25
4
""" 24 - Faça um programa que leia dez conjuntos de dois valores, o primeiro representando o número do aluno e o segundo representado a sua altura em metros. Encontre o aluno mais baixo e o mais alto. Mostre o número do aluno mais baixo e do aluno mais alto, juntamente com suas alturas. """ data = {} for i in range(10...
false
5791abe088bbf292869b0f6a2e2b6dd098e841d5
cristinamais/exercicios_python
/Exercicios Estruturas Logicas e Condicionais/exercicio 26 - secao 05.py
1,114
4.1875
4
""" 26 - Leia a distância em KM e a quantidade de litros de gasolina consumidos por um carro em um percurso, calcule o consumo em km/l e escreva uma mensagem de acordo com a tabela abaixo: ---------------------------------------- CONSUMO | (Km/l) | MENSAGEM ------------------------------------...
false
babe1e0f299cfe2224cbadd51fadc2047c3d34d5
cristinamais/exercicios_python
/Exercicios List Comprehension/exercicio 14 - secao 08.py
744
4.28125
4
""" 14 - Faca uma funcao que receba a distancia em KM e a quantidade de litros de gasolina consumidos por um carro em um percurso, calcule o consumo em KM / l e escreva uma mensagem de acordo com a tabela abaixo: __________________________________ CONSUMO (KM /l) MENSAGEM ---------------------------------- meno...
false