blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
9ece6a57789ce37c67ded0bdb2b2e5cf367d4cb7
souljudge/studying
/for_loop.py
237
4.15625
4
mylist=["罗乃霞","崔建军","崔虎巡"] for name in mylist: print(name) for number in range(10): print(number) #notice:range(10),其实省略了前面的0,range(0,10)才是原样,右边界限的数一般无法输出
false
c6508c8a9db4f03fc0e7ddc2a02a23668f028ee6
souljudge/studying
/list_comprehension.py
620
4.125
4
#list comprehension 列表解析式 #list生成新list的过程就是list comprehension的一种 #我的需求:从0-10的数字分别乘以2,然后放到新的列表里 # newlist=[] # for i in range(11): # newlist.append(i*2) # # print(newlist) # print([i*2 for i in range(11)]) # #这个就是列表解析式写法,将4行代码浓缩为1行 list=['崔虎巡','崔建军','罗乃霞','罗小凡','罗乃将'] # emptylist=[] # for name in l...
false
cfb42c8f3dfa6aa9368953c40094f8c436986b17
NAKO41/Classes
/Classes practice pt 1.py
1,082
4.125
4
class FireBall(object): #this is the class object #it will be used to track weather an attack hits or not def __init__(self): #each ball will start at (0,0) self.y = 0 self.x = 0 def move_forward(self): self.x += 1 #create a fireball and make it move forward fire_ba...
true
811aef10c87431213551ed5bbe44a23d8957029e
summerfang/study
/collatzconjecture/collatz_recursion.py
911
4.375
4
# 3n + 1 problem is also called Collatz Conjecture. Please refer to https://en.wikipedia.org/wiki/Collatz_conjecture # Giving any positive integer, return the sequence according to Collatz Conjecture. collatzconjecture_list = list() def collatzconjecture(i): if i == 1: collatzconjecture_list.append(i) ...
true
95b01804886ecbe5547f8ae70db88fe5a3f34182
plmon/python-CookBook
/chapter 3/3.7 处理无穷大和NaN.py
914
4.1875
4
# 3.7 处理无穷大和NaN # 目标:对浮点数的无穷大、负无穷大和NaN(Not a number)进行判断测试 # 解决方案: a = float('inf') b = float('-inf') c = float('nan') print(a) # inf print(b) # -inf print(c) # nan # 可以使用math.isinf()和math.isnan()函数判断: import math result = math.isinf(a) print(result) # True result = math.isinf(b) print(result) # True res...
false
1cdd49fcc31773c4ca758c91c36ffa87841d184e
unins/K-Mooc
/package_i/calc_rectangular_area.py
629
4.1875
4
def choice(): shape = int(input("type in shape(rectangle = 1, triangle = 2, circle = 3)")) if shape == 1: weight = int(input("\ntype in Rectangle Weight:")) height = int(input("type in Rectangle Height :")) return print(("Rectangle area is %d") %(weight*height)) elif shape == 2: weight = int(input("\ntype in...
true
8f4073779fbac7eed417ef5880e49c2d7093824e
addison-hill/CS-Build-Week-2
/LeetCode/DecodeString.py
2,131
4.125
4
""" Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. You may assume that the input string is always valid; No extra white spaces, squar...
true
a72db85874ec2f1bf62b9407487068709f9ef8f1
Lawren123/Randomfiles
/Chatbot2.py
2,866
4.1875
4
# --- Define your functions below! --- # The chatbot introduces itself and gives the user instructions. def intro(): print("Hi, my name is Phyllis. Let's talk!") print("Type something and hit enter.") # Choose a response based on the user's input. def process_input(answer): # Define a list of possible ...
true
84bbbf8888bd5646f892d1e3fc700a103c797721
fer77/OSSU-CS-Curriculum
/intro-cs-python/week1-2/pset1/problem-3.py
821
4.375
4
''' Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh In the case of ties, print the first subst...
true
93b861ca4f92a3184cb02bc29d0267c3aa15cb43
bartoszmaleta/3rd-Self-instructed-week
/loop control statements/while/Loop_control_statements.py
443
4.375
4
# Here is a simple Python example which adds the first ten integers together: total = 0 i = 1 while i <= 10: total += i print(total) i += 1 print('\n-------------------------------------------- ') # numbers is a list of numbers -- we don't know what the numbers are! numbers = [1, 5, 2, 12, 14, 7, 18, 30,...
true
5f5cf8bcf373e898279ee54dd5ed10fb52383ba7
bartoszmaleta/3rd-Self-instructed-week
/sorting/sorting_how_ to/lambda_expressions.py
971
4.5625
5
# Small anonymous functions can be created with the lambda keyword. # This function returns the sum of its two arguments: lambda a, b: a+b. # Lambda functions can be used wherever function objects are required. # They are syntactically restricted to a single expression. # Semantically, they are just syntactic sugar...
true
457bf2de01c95c82b3febd7eae03b35b48042cce
bartoszmaleta/3rd-Self-instructed-week
/functions/exe4 - return_values.py
564
4.25
4
def calculate_the_factorial_of_a_given_number(given_number_str): given_number = int(given_number_str) # total = 1 # given_number = 5 # i = 0 if given_number <= 0: print("Wrong number. ") if given_number == 1: return 1 # for given_number in range(1, given_number + 1)...
true
213e2dde435c17a0c6484cfc867ebf38d1ba6cf0
bartoszmaleta/3rd-Self-instructed-week
/Working with Dictionaries, and more Collection types/ranges/ranges.py
629
4.65625
5
# print the integers from 0 to 9 print(list(range(10))) # print the integers from 1 to 10 print(list(range(1, 11))) # print the odd integers from 1 to 10 print(list(range(1, 11, 2))) # We create a range by calling the range function. As you can see, if we pass a single parameter to the range function, # it is used a...
true
1183206db30f71bffd121a93b3ebcd5a1ced07cd
kristinbrooks/lpthw
/src/ex19.py
1,032
4.15625
4
# defines the function. names it & defines its arguments. then indent what will be done when the function is called def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a pa...
true
20dd021a971a341e22644431916fc1fed06763e5
mousaayoubi/lens_slice
/script.py
656
4.34375
4
#Create toppings list toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"] #Create prices list prices = [2, 6, 1, 3, 2, 7, 2] #Length of toppings num_pizzas = len(toppings) print("We sell "+str(num_pizzas)+" different kinds of pizza!") #Combine price list with toppings list...
true
27affa01e14c441390538e60af25253600082d9b
tommydo89/CTCI
/17. Hard Problems/circusTower.py
1,277
4.125
4
# A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter # than the person below him or her. Given the heights and weights of each person in the circus, write # a method to compute the largest po...
true
24185973d76ecf62fa816c7b2dbeb52cc89397c7
tommydo89/CTCI
/16. Moderate Problems/pondSizes.py
1,797
4.28125
4
# You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of # water connected vertically, horizontally, or diagonally. The size of the pond is the total number of # connected water cells. Write a...
true
17a49eb54c369a43f2c3445b291be65936677273
tommydo89/CTCI
/2. Linked Lists/palindrome.py
1,058
4.3125
4
# Implement a function to check if a linked list is a palindrome. class Node: def __init__(self, val): self.val = val self.next = None Node1 = Node(1) Node2 = Node(0) Node3 = Node(1) Node1.next = Node2 Node2.next = Node3 # def palindrome(node): # reversed_LL = palindrome_recursion(node) # while (reversed_LL...
true
ce2a5c7371177bd7c44bfc1f77c802afe5d37f87
tommydo89/CTCI
/5. Bit Manipulation/insertion.py
863
4.21875
4
# You are given two 32-bit numbers, N and M, and two bit positions, i and # j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You # can assume that the bits j through i have enough space to fit all of M. That is, if # M = 10011, you can assume that there are at least 5 bits between j a...
true
8174667c3319d5a75b118e31a583ae58330b3100
tommydo89/CTCI
/1. Arrays/URLify.py
435
4.15625
4
# Write a method to replace all spaces in a string with '%20'. You may assume that the string # has sufficient space at the end to hold the additional characters, and that you are given the "true" # length of the string. (Note: If implementing in Java, please use a character array so that you can # perform this operati...
true
5bc76b5c51d6ad868f36e0a0cde6c7f4c9cceb14
jdingus/discount_calculator
/discount_calculator.py
847
4.25
4
def calculate_discount(item_cost, relative_discount, absolute_discount): """ Calculate the discount price of an item in the shopping cart, First relative_discount is applied then absolute_discount is applied, final purchase price is the then returned (price) """ if relative_discount > 1. or absolute_discount > 1:...
true
79a592eb784a078a6224ac0105a34aa5dc9432c0
patixa08/QS
/calculator.py
1,720
4.28125
4
#Funcao de boas vindas ao user def boasvindas(): print(''' Bem Vindo User! ''') def calcular(): operation = input(''' Por favor indique o tipo de operação que deseja através dos seguintes caracteres : + , - , * , / , ** ou % ''') #Pedido dos valores para efetua...
false
26362fcee2e89a58574c3d9dc68cff945d8c776a
JacobWashington/python_scripting_food_sales
/my_script.py
1,850
4.28125
4
# Read only def read_only(): ''' a method that only reads the file ''' try: file1 = open('data.txt') text = file1.read() print(text) file1.close() # the reason for closing, is to prevent a file from remaining open in memory except FileNotFoundError: text = None ...
true
ac4a60ec2e36e3595babfe3c7c9a452f947651da
achan90/python3-hardway
/exercises/ex16.py
1,246
4.25
4
# Start import string. from sys import argv # Unpack argv to variables. script, filename = argv # Print the string, format variable in as raw. print("We're going to erase {}".format(filename)) # Print the string. print("If you don't want that, hit CTRL-C.") print("If you do want that, hit ENTER") # Prompt for user i...
true
bff642d35d826ab6371374cf15a997e00b0581f3
Sean-McLeod/ICS3U-Unit2-01-Python
/area_of_circle.py
456
4.21875
4
#!/usr/bin/env python3 # Created by Sean McLeod # Created on November 2020 # This program can calculate the area and perimeter of a circle with # a radius of 15mm import math def main(): # This function calculates the area and perimeter of a circle print("If a circle has a radius of 15mm:") print("") ...
true
9e48b08db7c1a798678150d75f5dd30feb0fd8c6
BulochkaBU/stepik_python_one
/13.py
561
4.34375
4
''' Условие задачи: Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после первого введенного нуля выводит сумму полученных на вход чисел. Sample Input 1: 5 -3 8 4 0 Sample Output 1: 14 Sample Input 2: 0 Sample Output 2: 0 ''' #Code # put your python code here n = i...
false
0b98f43b8373fd1ed68230a9cf8c39073d6a9593
ChadDiaz/CS-masterdoc
/1.2 Data Structures & Algorithms/Number Bases and Character Encoding/ReverseIntegerBits.py
538
4.3125
4
""" Given an integer, write a function that reverses the bits (in binary) and returns the integer result. Examples: csReverseIntegerBits(417) -> 267 417 in binary is 110100001. Reversing the binary is 100001011, which is 267 in decimal. csReverseIntegerBits(267) -> 417 csReverseIntegerBits(0) -> 0 Notes: The input inte...
true
81918ebc623dc5f056379388da9217097124c330
ChadDiaz/CS-masterdoc
/1.1/Python II/schoolYearsAndGroups.py
992
4.1875
4
''' Imagine a school that children attend for years. In each year, there are a certain number of groups started, marked with the letters. So if years = 7 and groups = 4For the first year, the groups are 1a, 1b, 1c, 1d, and for the last year, the groups are 7a, 7b, 7c, 7d. Write a function that returns the groups in t...
true
e4ca5ef5250917fcc4df116e3e79a65ea6a6d14b
thanuganesh/thanuganeshtestprojects
/iterables.py
2,176
4.28125
4
"""This function helps to learn about iterables""" #List is iterable but not iterator #iterable somthing can be looped over becaz we can loop over list #how we can say some thing is iterable???? #__iter__() method in iterable then its called iterable #iterator is object with the state it rembers where its during...
true
27c34eafa416a0ada55670ee72004ad292e33a39
csankaraiah/cousera_python_class
/Python_Assignment/Ch6Strings/ex6_3.py
292
4.15625
4
def count_word(word, ch): count = 0 for letter in word: if letter == ch: count = count + 1 return count word_in = raw_input("Enter the word: ") ch_in = raw_input("Enter the character you want to count: ") count_ch = count_word(word_in, ch_in) print count_ch
true
8210aa7e5b27f65c07b1874f51f5260d1ad387bf
ClarkChiu/learn-python-tw
/src/operators/test_identity.py
1,203
4.46875
4
"""恆等運算子 @詳見: https://www.w3schools.com/python/python_operators.asp 恆等運算子用途為比較物件,不僅是比較物件的內容,而是會更進一步比較到物件的記憶體位址 """ def test_identity_operators(): """恆等運算子""" # 讓我們使用以下的串列來說明恆等運算子 first_fruits_list = ["apple", "banana"] second_fruits_list = ["apple", "banana"] third_fruits_list = first_fruits_li...
false
a9dcb63a962456b3ec45766a3a990135405d7aa7
premsub/learningpython
/learndict.py
567
4.34375
4
# This program is a learning exercise for dictionaries in perl # Parse through a dict and print months = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' } # print "Enter month>" # month=raw_inp...
true
b726154fcdd333f51421a3cc44c9c2aa45cca490
serenityd/Coursera-Code
/ex1/computeCost.py
644
4.3125
4
import numpy as np def computeCost(X, y, theta): """ computes the cost of using theta as the parameter for linear regression to fit the data points in X and y """ theta=np.mat(theta).T X=np.mat(X) y=np.mat(y) m = y.size print(X.shape,y.shape,theta.shape) # =================...
true
836e33d711e3f67a14a887a30b464976530ff6d3
selmansem/pycourse
/variables.py
1,436
4.125
4
# import only system from os from os import system, name # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # now call function we defined above clear() ##################...
true
1e7f8506a5038e42ffe5180d196af4b7e11fb44c
selmansem/pycourse
/numbers.py
1,247
4.21875
4
# import only system from os from os import system, name # define our clear function def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') # now call function we defined above clear() ##################...
true
042e3b8c7ad92fa71e3cf7c7e6fbdf33ae97be93
gdomiciano/intro2python
/python3-4beginners/lessons/loops_for.py
406
4.21875
4
ninjas = ['ryu', 'crystal', 'yoshi', 'ken'] # for ninja in ninjas: # print(ninja) # # loop through a section of the list # for ninja in ninjas[1:3]: # print(ninja) for ninja in ninjas: if ninja == 'yoshi': print(f'{ninja} - black belt') else: print(ninja) #break a loop for ninja in ninjas: if ninj...
false
ece2157471c376a950e06a08cf7cd945ff0c8873
Tezameru/scripts
/python/pythoncrashcourse/0015_seeing-the-world.py
2,051
4.84375
5
# Seeing the World: Think of at least five places in the world you’d like to # visit. Store the locations in a list. Make sure the list is not in alphabetical order. countries = ['Paraguay', 'France', 'Greece', 'Italy', 'Sweden'] # Print your list in its original order. Don’t worry about printing the list neatly, # ju...
true
bfac445de754be4667af5ad4566787a099019e11
frankShih/LeetCodePractice
/sorting_practice/insertionSort.py
443
4.15625
4
def insertion_sort(InputList): # from head to tail for i in range(1, len(InputList)): j = i curr = InputList[i] # move current element to sorted position (at left part of list) while (InputList[j-1] > curr) and (j >= 1): InputList[j] = InputList[j-1] ...
true
13468e46256ebf8586a4a49c1b29674bcff52754
lingyenlee/MIT6.0001-Intro-to-CS
/ps1b.py
880
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 9 09:54:12 2019 @author: apple """ annual_salary = float(input("Enter your annual salary:")) semi_annual_raise = float(input("Enter your raise as decimal:")) portion_saved = float(input("Enter the portion saved:")) total_cost = float(input("Enter ...
true
b969117ca7174c1f3f77d2422f64a41fa6dcd8e4
Goldabj/IntroToProgramming
/Session03_LoopsAndUsingObjects/src/m1e_using_objects_and_zellegraphics.py
2,391
4.34375
4
""" This module uses ZELLEGRAPHICS to demonstrate: -- CONSTRUCTING objects, -- applying METHODS to them, and -- accessing their DATA via INSTANCE VARIABLES (aka FIELDS). Authors: David Mutchler, Amanda Stouder, Chandan Rupakheti, Katie Dion, Claude Anderson, Delvin Defoe, Curt Clifton, Matt Boutell, ...
true
b2ac9f97f436bfd924a71dd23feb0d63ec9c4383
vladshults/python_modules
/job_interview_algs/fizzbuzz.py
481
4.125
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' Created on 24 02 2016 @author: vlad ''' def multiple_of_3(number): return number % 3 == 0 def multiple_of_5(number): return number % 5 == 0 for i in range(1, 100): if not multiple_of_3(i) and not multiple_of_5(i): print i continue ...
false
faba8af94dda061f2acc45742658108fc0c5cf7e
ClemXIX/Solo_Learn_Courses
/Python/Beginner/23.2_Leap_Year.py
978
4.5625
5
""" else Statement You need to make a program to take a year as input and output "Leap year" if it’s a leap year, and "Not a leap year", if it’s not. To check whether a year is a leap year or not, you need to check the following: 1) If the year is evenly divisible by 4, go to step 2. Otherwise, the year is NOT leap ...
true
d760adfa1d6c6444b0f6c36f6ea35f7904806589
ClemXIX/Solo_Learn_Courses
/Python/Beginner/20_Tip_Calculator.py
554
4.28125
4
""" Tip Calculator When you go out to eat, you always tip 20% of the bill amount. But who’s got the time to calculate the right tip amount every time? Not you that’s for sure! You’re making a program to calculate tips and save some time. Your program needs to take the bill amount as input and output the tip as a flo...
true
f9c5686400afa04ea29ec2e217f18e027857f7c2
ClemXIX/Solo_Learn_Courses
/Python/Intermediate/2 Functional Programming/12.2_How_Much.py
499
4.125
4
""" Lambda You are given code that should calculate the corresponding percentage of a price. Somebody wrote a lambda function to accomplish that, however the lambda is wrong. Fix the code to output the given percentage of the price. Sample Input 50 10 Sample Output 5.0 The first input is the price, while the second...
true
2054b0c9ca187bd13b6e9fc5829e6a63d3136f5b
ClemXIX/Solo_Learn_Courses
/Python/Core_Course/2_Strings_Variables/09.2_More_Lines_More_Better.py
366
4.21875
4
""" Newlines in Strings Working with strings is an essential programming skill. Task: The given code outputs A B C D (each letter is separated by a space). Modify the code to output each letter on a separate line, resulting in the following output: A B C D Consult the Python Strings lesson if you do not remember the...
true
4c932287be178731406195e0e49a55acd8bbdb5f
RenanRibeiroDaSilva/Meu-Aprendizado-Python
/Exercicios/Ex055.py
1,084
4.34375
4
""" Ex - 055 - Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor pesos lidos.""" # Como eu fiz # Cabeçalho: print(f'{"":=^40}') print(f'{"> MAIOR PESO LIDO <":=^40}') print(f'{"":=^40}') # Var: maior_peso = 0 menor_peso = 1000 # ...
false
c27103282e46a8ffb68ac4452997be9d70f245cc
RenanRibeiroDaSilva/Meu-Aprendizado-Python
/Exercicios/Ex102.py
2,142
4.375
4
""" Ex - 102 - Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial. """ # Como...
false
515016c99fe0627527569744f6ac27de6260448d
RenanRibeiroDaSilva/Meu-Aprendizado-Python
/Aulas Python/Aula014.py
1,242
4.15625
4
""" Aula - 014 - Estrutura de Repetição While (parte 2).""" # Fase teórica. ''' Vimos as diferenças entre o while e o for. Chamamos o while de "Estrutura de repetição com teste lógico". Le-se "while" como "enquanto" enqunto não maça | while not maçã: passo | passo ...
false
962b33f48f935ac57de975c7df1a7f54209cfe8e
RenanRibeiroDaSilva/Meu-Aprendizado-Python
/Aulas Python/Aula010.py
1,273
4.53125
5
""" Aula - 010 - Condições Simples e Compostas: Nesta aula vamos aprender como ultilizar estruturas condicionais simples e compostas nos programas em Python.""" # Fase Teórica # Aqui aprendemos o uso do if else, e como contruir a sua identação. # if variavel.ação_desejada(): # bloco True # e...
false
7343dd357eb4cd0ea64111b65cca82faa7b8c6e1
RenanRibeiroDaSilva/Meu-Aprendizado-Python
/Exercicios/Ex022.py
1,645
4.5
4
""" Ex-022- Crie um programa que leia o nome completo de uma pessoa e mostre: > O nome com todas as letras maiúsculas e minúsculas. > Quantas letras ao todo (sem considerar espaços). Quantas letras tem o primeiro nome.""" # Usamos .strip() para descartar espaços vazios antes e depois da string nom...
false
491c6db30d4724556b9f0376b6b291aae9283585
pranav1214/Python-practice
/lec3/p9.py
315
4.21875
4
# to read a string and count the number of letters, #digits and other s1 = input("Enter a string: ") lc, dc, oc = 0, 0, 0 for s in s1: if (('A' <= s <= 'Z') or ('a' <= s <= 'z')): lc = lc + 1 elif ('0' <= s <= '9'): dc = dc + 1 else: oc = oc + 1 print("Letters: ", lc, "Digits: ", dc, "Other: ", oc)
true
01712f7719db69bd26adfd8372710cf9d38c15dc
DunnBC22/BasicPythonProjects
/PlayingWithNumbers.py
1,067
4.28125
4
import math ''' Take a number that is inputted and split it into 2s and 3s (maximize the number of 3s first). Take those numbers and multiply them together to get the maximum product of the values. ''' def defineNumber(): number = input('Please enter a number ') try: (isinstance(type(number), int)) ...
true
72e8a939273e0c6c8e4c1825e9c23a70b4103ca0
tarv7/Trabalhos-da-faculdade-UESC
/Codecademy/Python/08 - Laços/08.1 - Laços/12 - Para seu A.py
206
4.125
4
phrase = "Um passaro na mao..." # Adicione seu laco for for char in phrase: if char == 'A' or char == 'a': print 'X', else: print char, #Nao delete esta declaracao print! print
false
5f77ed8ab840fc2a8bb9280eb2ee7d2652c52738
tom1mol/python-fundamentals
/dictionaries/dictionaries1.py
1,050
4.71875
5
# Provides with a means of storing data in a more meaningful way # Sometimes we need a more structured way of storing our information in a collection. To do this, we use dictionaries # Dictionaries allow us to take things a step further when it comes to storing information in a collection. Dictionaries # will enable ...
true
6e384bb841ec5c2e5ba365ea1d9082546f9744ac
tom1mol/python-fundamentals
/there-and-back-again/while-loops1.py
1,798
4.5
4
countdown_number = 10 print("Initiating Countdown Sequence...") print("Lift Off Will Commence In...") while countdown_number >= 0: print("%s seconds..." % countdown_number) countdown_number -= 1 print("And We Have Lift Off!") # In this example we declare a variable called countdown_number, then we proceed ...
true
be03930099432c1f744dbf25cd4708564f318e6a
tom1mol/python-fundamentals
/break_and_continue/99bottles.py
1,953
4.375
4
for number in range(99, 0, -1): line_one = "{0} bottle(s) of beer on the wall. {0} bottle(s) of beer" line_two = "Take one down, pass it around. {0} bottle(s) of beer on the wall\n" print(line_one.format(number)) print(line_two.format(number - 1)) # OUTPUT: # Python 3.6.1 (default, Dec 2...
true
055730012920bf3dd282d898c5a67358c20b8d04
tom1mol/python-fundamentals
/there-and-back-again/range1.py
1,241
4.78125
5
for item in range(5): print(item) # OUTPUT: # Python 3.6.1 (default, Dec 2015, 13:05:11) # [GCC 4.8.2] on linux # 0 # 1 # 2 # 3 # 4 # NOTES: # Instead of just starting from 0, we can use additional arguments to achieve various sequence combinations. # We know this by looking at the Pytho...
true
b1d992f84b5be48b7acc1ca7490f5119d688b6cd
tom1mol/python-fundamentals
/mutability-and-immutability/mutability-and-immutability3.py
753
4.4375
4
# Tuples, however, are not mutable, meaning that they cannot be changed or modified and have a fixed size # and fixed values. Therefore if we create a tuple containing two items, then it will always have two items. # It cannot be changed. If we wanted to use the del keyword on an item in a tuple, then Python will com...
true
5769f5662f13e5393432a3ca24319a8d90400900
tho-hoffmann/100DaysOfCode
/Day007/Challenges/ch01.py
837
4.3125
4
#Step 1 word_list = ["aardvark", "baboon", "camel"] #TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word. import random chosen_word = random.choice(word_list) #TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowerca...
true
1513dc748e97fa9529d7dff58b535f75305b7f74
Apekshahande/Python_small_project
/rockpapergame.py
2,386
4.21875
4
from random import randint def win():# def is pree difine keyword. win is variable name and we pass the prameter inside the parenteses. print ('You win!') # return ('You win!')# if we are returen the function then i have to print this function when i will pass then argument. def lose():# def is pree dif...
true
745e2bb0bbd2a55e7f49c0c788ec1fc8a0d4a0eb
ballib/Forritun1
/assignment 9 (files and exceptions)/dæmi3.py
562
4.28125
4
def open_file(filename): file_object = open(filename, "r") return file_object def longest(file_object): longest_word = '' count = 0 for word in file_object: strip = word.strip().replace(' ', '') if len(strip) > len(longest_word): longest_word = strip count +=...
true
5290553652abe667784a4526453b6e958b1990c4
AndrewShmorhunGit/py-learning
/builtin/decorator_fn.py
2,241
4.375
4
""" Decorators with or without arguments """ import functools def decorator1(fn_or_dec_arg): """ Simplest variant - No need to use named args for decorator - Different wrapper's for decorator with and without arguments - Decorator argument can't be a function """ if callable(fn_or_dec_arg...
true
d99ee17fad86c162cf30edb35fb4bce5bfcc7007
fcue/movie_project
/movies.py
1,224
4.3125
4
movies = [ {'title': 'movie 1', 'year': 2001}, {'title': 'movie 2', 'year': 2002}, {'title': 'movie 3', 'year': 2006}, {'title': 'movie 4', 'year': 2004} ] def add_movie(): get_title = input('Enter the title of the movie: ') get_year = input('Enter the year: ') movies.append( { ...
false
8d84a372cd5822799126eeaaa8421fb745769752
DanielMagallon/Python-dev
/PrimerosPasos/Curso/Arreglos.py
1,825
4.375
4
calificaciones = {"Luis":3,"Manuel":2,1:"Pedro"} #set alumnos = ["Juan","Pedro","Daniel","Javier","Lalo"] #list print(alumnos[0:2]) #Las llaves de rizo {} crean dictionaries o sets. Los corchetes crean lists. print(calificaciones["Luis"]) print(calificaciones[1]) print(alumnos) x = 4 d = 2 if x >= 2 and d>=2: ...
false
f9036151afb3f796786f8aefbcff7e35f6da31a7
h15200/notes
/python/fundamentals.py
573
4.125
4
# using args in for loops <starting, ending, increment> for i in ["a", "b"]: print(i) # prints the actual List items nums = [10, 20, 30] for i in range(len(nums) - 1, -1, -1): print("item is", nums[i]) # input, string template literal with `f` for formatted string literal # try/except dangerous blocks of c...
true
3cea8b8c4d009cf5d049d3df9fb40d2308e7cb1c
cuber-it/aktueller-kurs
/Archiv/Tag1/01_list_tuple_set.py
852
4.53125
5
# Create a list, a tuple, and a set with the same elements my_list = [1, 2, 3, 3, 4, 5] my_tuple = (1, 2, 3, 3, 4, 5) my_set = {1, 2, 3, 3, 4, 5} # Print the elements in each data structure print("List:") for x in my_list: print(x) print("Tuple:") for x in my_tuple: print(x) print("Set:") for x in my_set: ...
true
10122b6e8d395d9817ccd9fc9c26597ead045439
cuber-it/aktueller-kurs
/Archiv/Tag1/02_comprehensions.py
1,216
4.125
4
# Creating a list of squares of numbers 0 to 9 squares = [x**2 for x in range(10)] print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # Creating a list of even numbers from another list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [x for x in numbers if x % 2 == 0] print(evens) # Output: [2, 4, 6, 8,...
true
eb8e8072b9526941522dbb22e789573ee8106474
faizan2sheikh/PythonPracticeSets
/sem2set2/Q11.py
2,014
4.46875
4
# 11. In ocean navigation, locations are measured in degrees and minutes of latitude and longitude. Thus if you’re lying off # the mouth of Papeete Harbor in Tahiti, your location is 149 degrees 34.8 minutes west longitude, and 17 degrees 31.5 # minutes south latitude. This is written as 149°34.8’ W, 17°31.5’ S. Ther...
true
d686267126f4b318cb3620df49471f49e0959099
faizan2sheikh/PythonPracticeSets
/sem2set2/Q10.py
1,057
4.375
4
# Write code to create a class called Time that has separate member data for hours, minutes, and seconds. Make # constructor to initialize these attributes, with 0 being the default value. Add a method to display time in 11:59:59 # format. Add another method addTime which takes one argument of Time type and add this ...
true
6f02dbdbbf180593ebfcbc4b8c14d870485491df
deejayM/wagtail_sb_goals
/sb_goals/lib/shared-lib/calendar.py
1,119
4.34375
4
import datetime def days_in_month(year, month): """ Inputs: year - an integer between datetime.MINYEAR and datetime.MAXYEAR representing the year month - an integer between 1 and 12 representing the month Returns: The number of days in the input month. """ #if mont...
true
749d231fdbeeeb0f6b02aac9f9976263baaaffe5
ashish8796/Codewars
/python-kata/count_smiley_faces.py
633
4.15625
4
''' Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces. Valid smiley face examples: :) :D ;-D :~) Invalid smiley faces: ;( :> :} :] ''' arr = [':D',':~)',';~D',':)'] def count_smileys(arr): symb = [[':', ';'], ['-', '~',')', 'D']] count...
true
86dc1856142f81e6d7eef77ef5baae3b51d080e7
ashish8796/Codewars
/python-kata/head_at_wrong_end.py
675
4.28125
4
''' You're at the zoo... all the meerkats look weird. Something has gone terribly wrong - someone has gone and switched their heads and tails around! Save the animals by switching them back. You will be given an array which will have three values (tail, body, head). It is your job to re-arrange the array so that the...
true
924e88e3af15706a42d0c15fe319f2149168df54
kshitijzutshi/Text-Mining-in-Python
/Handling Text in Python.py
286
4.46875
4
#Examples for text handling using python #!/usr/bin/env python# -*- coding: utf-8 -*- text1="Hi my name is Maxwell edward Stark" text2=text1.split(' ') print (text2) for w in text2: if len(w) > 3: print(w) print("Words in caps =") for w in text2: if w.istitle(): print(w)
false
d22f09a44fdaef9abf9d9acd54100add5aff00e2
GuileStr/proyectos-py
/AnioB.py
318
4.21875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 14:34:06 2020 @author: palar """ def is_leap(year): leap = False if year%4==0 and year%100==0 and year%400==0: leap=True else: leap=False # Write your logic here return leap year = int(input()) l = is_leap(year) print(l)
false
b366aab4c0bf455cf6129a826658b95ea024cee7
tommygod3/isc-exercises
/python_exercises/exercise1.py
651
4.21875
4
print("---------- Exercise 1 script ----------") print("Question 1:") course = "python" rating = 10 print(f"Course: {course}, rating: {rating}") print("Question 2:") b = 3 c = 4 a = ((b*b) + (c*c))**0.5 print(f"a = {a}") print("Question 3:") print(f"a's type: {type(a)}") print(f"b's type: {type(b)}") print(f"c's typ...
false
2db69ce29e4f3f12776acbd1b793b29bf5797baa
XjorgeX/Usando-Git
/Listas.py
798
4.125
4
>>> lista = ["abc", 42, 3.1415] >>> lista[0] # Acceder a un elemento por su ndice 'abc' >>> lista[-1] # Acceder a un elemento usando un ndice negativo 3.1415 >>> lista.append(True) # Aadir un elemento al final de la lista >>> lista ['abc', 42, 3.1415, True] >>> del lista[3] # Borra un elemento de la lista usando un ndi...
false
c6826de606a4ee7e9bf17c40057a0b9eda0ea76a
imolina218/Practica
/Modulo01/Parte_04_02_products_bill.py
1,752
4.46875
4
# Create a program that have a list of products by code. # Then the user can choose the product and the amount, the option to choose more than # one product needs to be available. # Once the user doesn't want to enter any more products the program will print the # bill with all the product/s and the quantity d...
true
c7b730f182c1e0068f5e58a51ef99b00723bb95c
imolina218/Practica
/PYnative/lists.py
2,862
4.15625
4
# Take a list and reverse it. # a_lsit = [100, 200, 300, 400, 500] # print(a_lsit) # # a_lsit.reverse() # print(a_lsit[::-1]) # print(a_lsit) ################################################## # Concatenate the following two lists index-wise. # list1 = ["M", "na", "i", "Ke"] # list2 = ["y", "me", "s", "lly"] ...
false
492151b1f4d9af62b1ccd1f1d5c762e17306cc88
jj1165922611/SET_hogwarts
/python_base/base8/base8_1/base8_1.py
596
4.28125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020-07-26 # @Author : Joey Jiang # @File : base8_1.py # @Software : PyCharm # @Description: python脚本编写实战(一) # 1、冒泡排序 def bubble_sort(): list=[1,3,5,2,7,6] for i in range(len(list)-1): for j in range(len(list)-i-1): ...
false
7493f14ffb26d3fdeea0cb65a822ac7609cd3295
yshshrm/Algorithms-And-Data-Structures
/python/Sorts/quick_sort.py
920
4.15625
4
# Implementation of Quick Sort in Python # Last Edited 10/21/17 (implemented qsort_firstE(arr)) # Worst case performance: O(n^2) # Average performance: O(nlogn) # In this first implementation of quick sort, the choice of pivot # is always the first element in the array, namely arr[0] def qsort_firstE(arr): # if th...
true
5d53368ee0c009da195721291844f7f7ae592799
sonikku10/primes
/primes.py
509
4.34375
4
import math #Import the math module def is_prime(num): ''' This function will determine whether a given integer is prime or not. Input: An integer. Output: True/False Statement :param num: :return: ''' if num % 2 == 0 and num > 2: #All even numbers greater than 2 are not prime. ...
true
ff085804195df8c213d1a4b6571b6256ccfaa110
KaraKala1427/python_labs
/task 2/53.py
339
4.125
4
rate = float(input("Enter the rating : ")) if rate == 0: print("Unacceptable performance") elif rate>0 and rate<0.4 or rate>0.4 and rate<0.6: print("Error") elif rate == 0.4: print("Acceptable performance", "Employee's raise= $", 2400*0.4) elif rate >= 0.6: print("Meritorious performance", "Employee's r...
true
7460834272f861fabf6ae5d9682ad057cdec10b3
afwcc/CST8279
/question12.py
276
4.125
4
user_enter_fahrenheit_degrees_string = input("Please enter the fahrenheit degrees") user_enter_fahrenheit_degrees_float = float(user_enter_fahrenheit_degrees_string) celsius_degrees_float = float((user_enter_fahrenheit_degrees_float-32)*(5/9)) print(celsius_degrees_float)
false
f27357315751de19f22270227e3c3bb73c9f977c
oliverschwartz/leet
/longest_univalue_path/longest_univalue_path.py
1,070
4.125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: if not root: return 0 self.global_max = 0 def long...
true
747249001d522782d1042f4097c370d5989011eb
Shinrei-Boku/kreis_academy_python
/lesson07.py
817
4.125
4
#class 抽象クラス lesson07.py import abc class Person(metaclass=abc.ABCMeta): def __init__(self,name,age): print("create new Person") self.__name = name self.__age = age def myname(self): print("my name is {}".format(self.__name)) def myage(self): print( "{}の{}歳です。".fo...
false
5e265310ffb378751e71d486f0f94416c12372ba
OSL303560/Parenitics
/Source codes/Beginning.py
1,976
4.15625
4
import time from os import system temp = 0 def startstory(): print("In February 2019, ", end = "") time.sleep(1) print("the Hong Kong government proposed the ") time.sleep(0.5) print("\nFugitive Offenders and Mutual legal Assistance in Criminal Matters Legislation (Amendment) Bill 2019.") ...
true
190f6a92cad55fa3b8ca1f757f8b6c42eac5f13d
PhilipMottershead/Practice-Python
/Tutorials/Exercise 13 - Fibonacci.py
656
4.4375
4
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. # Make sure to ask the user to enter the number of numbers in the sequence to generate. starting_number = [1] def next_number(num): if num == 1 or...
true
cca82bcf32c9f686707d821e20d7232e978d6624
PhilipMottershead/Practice-Python
/Tutorials/Exercise 01 - Character_Input.py
802
4.1875
4
# Create a program that asks the user to enter their name and their age. # Print out a message addressed to them that tells them the year that they will turn 100 years old. # Extras: # Add on to the previous program by asking the user for another number # and printing out that many copies of the previous message. (Hint...
true
f48533f2a1fae162aa7356dee9335e772e791424
GAUTAMSETHI123/PYTHON-PROGRAM
/DIST.py
213
4.125
4
x1=int(input("enter the value:")) x2=int(input("enter the value:")) y1=int(input("enter the value:")) y2=int(input("enter the value:")) dist=((y2-y1)*2+(x2-x1)*2)*1/2 print("the distance between two points",dist)
false
a98ec918c69cf8b6926f80cd0388b716ec1f9b71
jim-cassidy/foursquare-with-flask
/module/createtable.py
1,914
4.1875
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) ...
true
00ed0a5bf8383fc9cc31344c481bad2e2ea8cd7e
dr01/python-workbench
/lettfreq.py
2,125
4.21875
4
#!/usr/bin/env python3 """ Print number of occurrences and frequency of letters in a text """ __author__ = "Daniele Raffo" __version__ = "0.1" __date__ = "14/10/2018" import argparse from string import ascii_lowercase as _alphabet from collections import Counter as _Counter def parse_command_line(): """Pa...
true
816706b0788b7bac1bea4c218fa77cec1cdf2492
Bajpai-30/Coffee-Machine-in-python---hyperskill
/stage4.py
2,135
4.1875
4
amount = 550 water = 1200 milk = 540 coffee = 120 cups = 9 def print_state(): print('The coffee machine has:') print(f'{water} of water') print(f'{milk} of milk') print(f'{coffee} of coffee beans') print(f'{cups} of disposable cups') print(f'{amount} of money') print() d...
true
849f167637b964a3e8d0de273a0a43ad7c3857cd
CiaranGruber/CP1404practicals
/prac_10/extension_test_date.py
2,244
4.4375
4
""" Create the class Date which contains code to add days according to leap years Date Class. Created by Ciaran Gruber - 28/08/18 """ import doctest class Date: """Represent the Date""" month_to_day = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} def __init__(...
true
d1dddeb8a44b1cb0f4430fc9971653dced1c7a19
CiaranGruber/CP1404practicals
/prac_02/exceptions_demo.py
889
4.53125
5
""" CP1404/CP5632 - Practical Answer the following questions: 1. When will a ValueError occur? Value Error will occur if you use a non-integer 2. When will a ZeroDivisionError occur? This will occur when the person puts the denominator as a 0 3. Could you change the code to avoid the possibility of a ZeroDivisi...
true
5aa245f1f5016cc8dc8dbf92a64783972b106e4e
CiaranGruber/CP1404practicals
/prac_05/hex_colours.py
1,062
4.1875
4
""" Prints hexadecimal code when user enters colour name. 21/08/18 - Hex Colours. Created by Ciaran Gruber. """ COLOURS = {'alice blue': '#f0f8ff', 'antique white': '#faebd7', 'aquamarine 1': '#7fffd4', 'azure 1': '#f0ffff', 'beige': '#f5f5dc', 'blanched almond': '#ffebcd', 'blue': '#0000FF', 'brown': '#a5...
false
81f48937b938e454999489819a76eb86c83d5e27
henrikvalmin/visual-sorting-algorithms
/main_menu.py
957
4.1875
4
from sorting import sorting def __main__(): while True: print("\nChoose an algorithm to sort with!") print("1: Bubble Sort") print("2: Insertion Sort") print("3: Selection Sort") print("4: Quick Sort") print("5: Shell Sort") choice = input("Use algorithm nr...
false
6beb646b7ab8163e5fc1ed77e008d46a0256c332
satinder01/projecteuler
/9_special_pythagorean_triplet.py
479
4.15625
4
#!/Users/satinderjitsingh/anaconda3/bin/python ''' Special Pythagorean triplet Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc....
false
b0a6f193b22b83b4f6ad92957fef9b6489c08bbc
HenziKou/CIS-211
/Projects/duck_compiler-master/alu.py
1,891
4.21875
4
""" The arithmetic logic unit (ALU) is the part of the central processing unit (CPU, or 'core') that performs arithmetic operations such as addition, subtraction, etc but also logical "arithmetic" such as and, or, and shifting. """ from instr_format import OpCode, CondFlag from typing import Tuple class ALU(object):...
true
dc166da896dfb8f0dd23df11aa008e4ee2e8cbb1
viniciusldn/Learning-Python
/POO - Programação Orientada a Objetos/POO_Geeters_Setters_Estados.py
1,240
4.4375
4
# language: PT """ Existem alguns padrões de bas práticas na programação. É aconselhavél que: - Classes sejam nomeadas com substantivos e a primeira letra capital. - Atributos de classe sejam nomeados com substantivos minusculos. - metodos sejam nomeados com verbos que indiquem sua ação. - Util...
false
b953de6e34b2eb3e482e94f97f41fe1503d30319
syedsaad92/MIT-6.0001
/week3Problem3_printing_all_available_letters.py
573
4.15625
4
# Next, implement the function getAvailableLetters that takes in one parameter - a list of letters, lettersGuessed. This function returns a string that is comprised of lowercase English letters - all lowercase English letters that are not in lettersGuessed. def getAvailableLetters(lettersGuessed): temp = '' imp...
true