blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
2173ad098596254036763aeafa11b98aebfa1fd4
maro199111/programming-fundamentals
/Exercises/exercise17.py
583
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 16 16:26:29 2019 @author: edoardottt """ #Write a function that take as input three numbers g,m,a (with a odd, in this way we avoid leap years) # and it returns True or False depending on the three numbers make a valid date. #Es. 30/2/2017 False; 1...
true
e0398fb3a6d508963caeb41fa5849c642ea2d414
SairaQadir/python-assignment
/ass2/ass-2.py
1,590
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[3]: print("Enter 'x' for exit."); #question1 print("Enter marks obtained in 5 subjects: "); mark1 = input(); if mark1 == 'x': exit(); else: mark1 = int(mark1); mark2 = int(input()); mark3 = int(input()); mark4 = int(input()); mark5 = int(input()); ...
true
1d16d6b2bcb5ed20b8d80d4644f8faa455f71225
KrystalGates/Bk1Ch4Dictionaries
/dictionaryOfWords.py
1,325
4.59375
5
# """ # Create a dictionary with key value pairs to # represent words (key) and its definition (value) # """ word_definitions = dict() print(word_definitions) # """ # Add several more words and their definitions # Example: word_definitions["Awesome"] = "The feeling of students when they are learning Python" # """ w...
true
dd342084a237127b3358df48285c3541cab20ef3
mrmichaelgallen/Course-Work-TTA
/Python/PythonInADay/Python_Item20_Script.py
428
4.21875
4
# String Manipulation name = "Guido" print name[0] print name.upper() print name.lower() print name.capitalize() # Formate a Date date = "11/12/2013" # Go through string and split # Where there is a '/' date_manip = date.split('/') #Show the outcome print date_manip print date_manip[0] print date_manip[1] pri...
true
d1653e5fed55296e9546b46e7a0865072f55470e
vishrutarya/grpc-calculator
/calculator.py
269
4.1875
4
import math def square_root(num: int): """ Returns the square root of the arg `num`. """ result = math.sqrt(num) return result def square(num: int): """ Returns the square of the `num` param. """ result = num ** 2 return result
true
75d37d4417f0fb4dd3decb8aa3fa506139ad9544
AllieJackson/Rice-Python-Certification
/RPSLS.py
2,772
4.1875
4
# Rock-paper-scissors-lizard-Spock template #Imports import random # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors # helper functions # Take the user's ...
true
23e5502f4418219a78ab515e60be0a49de72c492
gmanproxtreme/rps
/rps.py
1,407
4.21875
4
import random, math def Draw(): print("We both picked the same.") return def PWin(): print("Well done you win.") return def CWin(): print("You lose.") return StrUserType = input("Select Paper, Rock or Scissors (P,R or S)") ComputerType = math.floor(random.random()*3) #random.random(3) # 0==...
true
169fc98fcdeec215e501af357eae3122a46a0396
ryandancy/project-euler
/problem145.py
1,361
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Project Euler Problem 145: Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are reversib...
true
3c6b82f854695233a25f58a869b8ed2b3e91239a
ryandancy/project-euler
/problem1.py
439
4.21875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Project Euler Problem 1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ # Add multiples of 3 to multiples of 5 which are no...
true
31f112f9bddd7f691305e842293e37715bd65616
vincent507cpu/Comprehensive-Algorithm-Solution
/LintCode/ladder 07 data structure/必修/494. Implement Stack by Two Queues/.ipynb_checkpoints/solution-checkpoint.py
1,059
4.1875
4
# For python class import queue class Stack: def __init__(self): self.queue1 = queue.Queue() self.queue2 = queue.Queue() """ @param: x: An integer @return: nothing """ def push(self, x): # write your code here self.queue1.put(x) """ @return: nothing ...
false
e474a3325c48bc7ae870cb28bbcccbe756b672e6
CMWelch/Python_Projects
/Python/Python_Exercises/Paper Doll.py
293
4.1875
4
def paper_doll(string): new_string = "" for letter in string: if letter == " ": new_string = new_string + letter else: new_string = new_string + letter * 3 return new_string x = input("Input a string: ") print(paper_doll(x))
true
d3ad38b74a30be421c8d3ba453ddfd6df0545d34
Batukhanyui/pancake
/turtleber/11.py
227
4.1875
4
import turtle turtle.shape('turtle') for i in range(1,6): for j in range(360//i): turtle.forward(i*i) turtle.left(i) for j in range(360//i): turtle.forward(i*i) turtle.right(i) input()
false
5c1560c964288474b7a6a91834522b6410396ca5
imn00133/PythonSeminar
/TeachingMaterials/BookAndLecutreData/python_middle_class/chapter3_data_model/p_chapter03_02.py
1,143
4.1875
4
class Vector(object): def __init__(self, *args): """ Create a vector, example = Vector(5, 10) :param args: x, y """ if len(args) == 0: self._x, self._y = 0, 0 else: self._x, self._y = args def __repr__(self): """ :r...
false
a8627eb2f89fc73226d44390e7bf7af895f02ff8
benjimortal/face_recognition
/first/toturial/2.py
1,259
4.3125
4
def days_to_units(num_of_days, conversion_unit): if conversion_unit == 'hours': return f"{num_of_days} days are {num_of_days * 24} hours" elif conversion_unit == 'minutes': return f"{num_of_days} days are {num_of_days * 24 * 60} minutes" else: return 'unsupported unit' def validat...
true
b105d2c2229bec44e5e3de2400f883ae3669cc70
benjimortal/face_recognition
/first/Python_Exercises_skolan/6.py
490
4.15625
4
def main(): notes = { '1' : 'George Washington', '2' : 'Thomas Jefferson', '5' : 'Abraham', '10': 'Alexander Hamilton', '20': 'Ulysses S.Grant', '50': 'Andrew Jackson', '100':'Benjamin Franklin' } value = input('Please ente...
true
161e6533b74de7eafb66172b68746e863a40d121
eisendaniel/ENGR_PHYS_LABS
/Lab 1/Python_Intorduction.py
973
4.34375
4
#Lets learn Python 3+4 #if we want to see the result we need to print it print(3+4) #Printing text needs 'quote marks' print('abc') #assign a varible a=1.602**2 print(a+3) #can have creative names newvariblewithmorecreativename=4 print(a+newvariblewithmorecreativename) #Arrays A=[1,2,3,4,5] print(A) #ind...
true
56470a1df35f1b0959fe161adff34183fdc281b9
zhuhanqing/Data-Structures-Algorithms-Goodrich
/Chapter04_Recursion/xPowerN.py
232
4.1875
4
def power(x,n): """ Compute the value of x raised to power n """ if n==0: return (1) else: return (x * power(x,n-1)) #Code Fragment 4.11: Computing the power function using trivial recursion.
true
3bb68bfe85229cc2d0672c672db657c98c31e489
zhuhanqing/Data-Structures-Algorithms-Goodrich
/Chapter04_Recursion/sumOfArray_UsingBinaryRecursion.py
549
4.1875
4
def binary_sum(S,start,stop): """ Return the sum of the numbers in implicit slice S[start:stop]. """ if start >= stop: # zero elements in slice return (0) elif start == stop-1: # One element in slice return (S[start]) else: ...
true
1d12a62805e70d7bda3879142c3970e8863bead8
lvkeeper/programming-language-entry-record
/fuzzing/src/fuzzingbook/fuzzingbook_utils/Timer.py
2,103
4.3125
4
# 官方的代码写的很好,读起来很有收获,我这里敲一遍 # python time 模块:https://docs.python.org/3/library/time.html # 事实上,当我们向文件导入某个模块时,导入的是该模块中那些名称不以下划线(单下划线“_”或者双下划线“__”)开头的变量、函数和类。 # 因此,如果我们不想模块文件中的某个成员被引入到其它文件中使用,可以在其名称前添加下划线。 # 在普通模块中使用时,表示一个模块中允许哪些属性可以被导入到别的模块中 # 或许这是一个不错的东西,可以直观看到哪些内容会被导入到别的模块 # 仅对模糊导入时起到作用。如:from xxx import * # __all__...
false
f25516ec401c9387a98463b7fefa334e45a5be15
nathanstouffer/adv-alg
/little-algs/mergesort.py
1,017
4.3125
4
# a short program to mergesort some lists import random # method to recursively divide the mergesort def mergesort(nums): mid = int(len(nums) / 2) if (mid == 0): return nums else: nums1 = nums[:mid] nums2 = nums[mid:] return merge(mergesort(nums1), mergesort(nums2)) # meth...
true
b61305eafd0017a606e4490f18c2cfe30125bbcb
chaoticfractal/Python_Code
/Students_Final_Grades.py
1,979
4.125
4
""" This a little script that will take 3 dictonaries of Students name that contain lists of objects like homework scores, tests scores etc. that are then taken by funcitons to calculate final grade and averages. """ lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40....
true
1b42d041dcdce21ceeed5837d0a6b052e2f49225
danielnzlz01/Christmas-tree-drawn-with-characters
/main(9).py
640
4.15625
4
# Pinito de navidad print("This program will draw a tree, tell me the height of the tree:") niveles=int(input()) espacios=niveles-1 #número de espacios que van antes del primer asterisco asteriscos=1 contador=0 while contador<niveles: contador+=1 for x in range (espacios): #espacios antes de los asteriscos prin...
false
db553849968f52596e9e8494af602051f0913b3d
TinaArts/leetcode
/array/rotate-array.py
1,220
4.3125
4
"""Rotate Array Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]...
true
4af14b72dfcd78682fff9235735bc938ffff6165
MarcosLazarin/Curso-de-Python
/ex072.py
760
4.34375
4
# Criar uma tupla totalmente preenchida com uma contagem por extenso, de zero até vinte. # O programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso. continuar = 'S' numeros = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze'...
false
d3a4f74658e87b78a086ccbec165af91a3d1536f
MarcosLazarin/Curso-de-Python
/ex039.py
1,373
4.125
4
# Escreva um programa que leia o ano de nascimento de uma pessoa de acordo com sua idade e diga: # Se ele ainda vai se alistar ao serviço militar # Se é hora de se alistar # Se já passou o tempo de alistamento # O programa deve identificar quanto tempo falta ou passou de se alistar. from datetime import date idade = i...
false
1e2532758ba7e4718381ad1de6f6dff41cb2d675
xyzhangaa/ltsolution
/BTreeInorder.py
1,630
4.15625
4
###Given a binary tree, return the inorder traversal of its nodes' values. # O(n), O(n) def iterative_inorder(self,root,list): stack = [] while root or stack: if root: stack.append(root) root = root.left else: root = stack.pop() list.append(root.val) root= root.right return list def inorder(roo...
true
973c6c4a2bc42f7774c6cedb01100948e1e5af8e
xyzhangaa/ltsolution
/ReverseWordsinaStringII.py
808
4.125
4
# Time: O(n) # Space:O(1) # # Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. # # The input string does not contain leading or trailing spaces and the words are always separated by a single space. # # For example, # Given s = "the sky is blue", # return...
true
ad67bdef83de3cc2f3bb7dd4c16bc06f60e3cdce
Quinneth/Election_Analysis
/Temperature.py
293
4.5625
5
#delcared by asking user to input int() wrapped statement-->converts user input type from string to integer then used to assess if-else statement temperature = int(input("What is the temperature outside")) if temperature > 80: print("turn on the AC.") Else: print("Open the windows.")
true
8932a7e8052a2835b793425407c36b84546d1cfc
Jmarshall1994/PRG105
/99bottles.py
227
4.125
4
bottles = input('How many bottles?') while bottles > 0: print bottles, 'bottles of beer on the wall, ',bottles,' of beer. Take one down and pass it around,', bottles-1,' bottles of beer on the wall' bottles = bottles -1
true
c8aa9c40d811e7c302711f32edb49a742f4963cb
arinablake/python-selenium-automation
/hw_algorithms_5/hw_5_2.py
794
4.3125
4
# Вводится ненормированная строка, у которой могут быть пробелы в начале, в конце и между словами более одного пробела. # Привести ее к нормированному виду, т.е. удалить все пробелы в начале и конце, а между словами оставить только один пробел. ' Enter some abnormal string ' def clean_string(string): cl...
false
35c01a577cc7c7fb9517413e112b8c8711699c3d
arinablake/python-selenium-automation
/hw_algorithms_1/Return Negative.py
317
4.46875
4
#In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? def make_negative( number ): if number > 0: return - number elif number < 0: return number else: return 0 print(make_negative(-10)) print(make_negative(25))
true
60cfd5e18f77aaef3ed49a163311c3eed17d819e
benjamin22-314/learn_python_the_hard_way
/ex31.py
649
4.1875
4
print("""You enter a room. There is a chair in the room. There is a door in the room.""") print("""Do you sit on the chair (press '1') or go through the door (press '2')""") choice = input("> ") if choice == '1': print("The chair is an illusion, you fall on your bum") elif choice == '2': print("The door is j...
true
64a6261b37c4498244a300a8930776e330703f8f
huynhtritaiml2/Python_Basic_Summary
/list2.py
2,867
4.28125
4
greetings = ["hi", "hello", "wassap"] print(greetings[2]) # wassap print(len(greetings)) # 3 # n --> list size # highest index = n - 1 # for item in greetings: print(item) for i in range(len(greetings)): print(greetings[i]); # backpack = ["sword", "rubber duck", "slice of pizza", "parachute", "sword", "sw...
true
ce071793eb12f7205d5eb0726c053024bbf50a58
giovane-aG/exercicios-curso-em-video-python
/desafio033.py
281
4.15625
4
print('Digite 3 números') n1 = float(input('Primeiro número:')) n2 = float(input('Segundo número:')) n3 = float(input('Terceiro número:')) numbers = [n1,n2,n3] bigest = max(numbers) smallest = min(numbers) print('O maior número é {} e o menor é {}'.format(bigest, smallest))
false
c42e9d6757228d28bb035ff809d6daa1cb0db733
srea8/cookbook_python
/03/CalculatingWithFractions.py
698
4.1875
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Author: Srea # @Date: 2019-09-26 17:17:22 # @Last Modified by: shenzhijie # @Last Modified time: 2019-09-26 17:25:09 #****************************# #fractions 模块可以被用来执行包含分数的数学运算 #****************************# from fractions import Fraction a = Fraction(10,19) prin...
false
c4beb3d5a41bbcd6c6c115a13ef7f0f85a60f0da
alinasansevich/coding-playground
/grokking_algorithms/g_a_Ch2_SortSmallestToLargest.py
870
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 10 14:49:32 2021 @author: alina Code from the book "Grokking Algorithms", exercises, examples, my experiments with it, etc. """ def find_smallest(arr): """ (list of int) -> int Returns the smallest integer in a list of integers (I co...
true
1206e0ce85952fbe5508676e1a7bfa99e75195d9
pronouncedlyle/DS-and-Algos-Practice
/Sandbox/linked_list.py
1,551
4.1875
4
import time #define node (like the constructor) class node: def __init__(self, data = None): self.data = data self.next = None # define a linked list (using the definition of node) class linked_list: def __init__(self): self.head = node() #add to a linked list def append (self, dat...
true
0dea9e43ee7c33731ce954ac2eef9b6d661fb30a
holdbar/misc_python_stuff
/patterns/creational_patterns/abstract_factory.py
1,404
4.3125
4
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class Beer(metaclass=ABCMeta): pass class Snack(metaclass=ABCMeta): @abstractmethod def interact(self, beer: Beer) -> None: pass class AbstractShop(metaclass=ABCMeta): @abstractmethod def buy_beer(self) -> Beer: ...
true
1e68f059b845813c5070ba6c5ec2e050c96b6050
spettigrew/cs2-fundamentals-practice
/mod1-Python_Basics/basic_operations.py
388
4.34375
4
""" 1. Assign two different types to the variables "a" and "b". 2. Use basic operators to create a list that contains three instances of "a" and three instances of "b". """ # Modify the code below to meet the requirements outlined above a = "Goodbye " b = "Lambda" both = a + b print(both) a_list = [a] * 3 b_list = [...
true
a9da736b044dcc59d74510bb1cb4527c12ef3e86
seb-patron/Algorithms-and-Data-Structures
/mergesort/mergesort.py
1,176
4.15625
4
# implements week 1 merge sort # Pseudocode # # recursive call # if length of array > 1: # mergeSort(1st half), mergeSort(2nd half) # # # merge: # c = outputArray a = 1st sorted Array(n/2) b = 2nd sorted Array(n/2) # # i = 1; j = 1 # for k = 1 to n # if a(i) < b(j): # c(k) = ...
false
3dcc4ac57b0ce744901cf619bb131b7410435c04
RAMKUMAR7799/Python-program
/Beginner/Gnumbers.py
286
4.25
4
num1=int(input("Enter your number")) num2=int(input("Enter your number")) num3=int(input("Enter your number")) if(num1>=num2 and num1>=num3): print(num1,"is greatest number") elif(num2>=num1 and num2>=num3): print(num2,"is greatest number") else: print(num3,"is greatest number")
true
c820a8e1c9d53f94054205ccd56514df45e95322
Eric-Xie98/CrashCoursePython
/CrashCoursePython/Chapter 8/PassingRandom.py
2,246
4.84375
5
## Sometimes we don't know how many arguments we're going to pass into the function, so Python let's use the * ## and create a tuple that takes in arguments: def make_pizza(*toppings): for topping in toppings: print(topping) ## No matter how many arguments are given, Python treats them the same and pack...
true
fe6c2bc5f7c1e6bfed845a6ca016675fc6c0246a
Eric-Xie98/CrashCoursePython
/CrashCoursePython/Chapter 10/writingFile.py
2,196
4.5625
5
## One of the simplest ways to save data is to write to a file. Even after the program is closed, you can ## still look at the output file in its stored location as well as share it to others. You can also ## write programs that read it back into memory and work with it again later. # To write in a file, we use the op...
true
456d3ff0b114ec6d98f6e3a3628d786a2b36a17e
Eric-Xie98/CrashCoursePython
/CrashCoursePython/Chapter 4/Looping.py
1,525
4.59375
5
## Rather than individually index each element in a list, we can utilize a for loop: numbers = ["1", '2', '3', '4'] for number in numbers: print("I'm on number " + number) print("\n") names = ['Eric', 'Max', 'Bryan', 'Allinn', 'Nate', 'Edwin'] for i in range(0, 3): print("Wow, " + names[i] + " that was a g...
true
e480d9ce1b35de66f0393131ef8befc18dc99dc9
Eric-Xie98/CrashCoursePython
/CrashCoursePython/Chapter 7/whileLists.py
2,851
4.46875
4
## While loops can be used with lists and dictionaries and allows for modification while traversing them ## We can move items in one list to another using a while loop: unconfirmed_users = ['eric', 'max', 'allinn'] confirmed_users = [] while unconfirmed_users: current = unconfirmed_users.pop() print("Verifyi...
true
36b74c1fc61414c30e9d401c3c5dfb90f6c103de
crenault73/training
/python/tutograven/src/04_list/cre_split.py
282
4.125
4
# Exemple: Liste à partir de split # Récuppération d'une liste à partir d'une chaine de la forme: email-pseudo-motdepasse text = input("Entrer une chaine de la forme: email-pseudo-motdepasse ").split("-") print(text) print("Salut {}, ton e-mail est {}".format(text[1],text[0]))
false
66744cf2fbb266be280279cce690d21209609fed
VladShokun/lazy_python
/lazypython09.py
1,214
4.4375
4
""" Метод срок string.isalpha() - все символы алфавитные string.isalnum() - и алфавитные и цефровые символы string.isdigit() - все символы в строке евляються цифрами string.islower() - все символы из нижнего регистра string.isupper() - все символы из верхнего регистра string.istitle() - проверка на то что каждое слово ...
false
cacecdc7e6b9ccb7efe90f953200e0cb59ec2d8e
csumithra/pythonUtils
/03_generate_dict.py
457
4.21875
4
#With a given integral number n, write a program to generate a dictionary that contains (i, i x i) such that is an integral number # between 1 and n (both included). and then the program should print the dictionary. # Suppose the following input is supplied to the program: 8 #Then, the output should be: #{1: 1, 2: 4,...
true
ee945e5b0086fee77ce3b3d30443758ddd06c3e3
csumithra/pythonUtils
/23_24_sqaure_number.py
246
4.15625
4
#Write a method which can calculate square value of number def square_num(num): ''' Returns the square value of the input number. ''' return num ** 2 print(square_num.__doc__) print(square_num(int(input('Enter a number: '))))
true
65640293c12bcfc29e9286d84e48502afaf8a9d8
csumithra/pythonUtils
/18_CheckPassword_validity.py
1,091
4.1875
4
# Following are the criteria for checking the password: # At least 1 letter between [a-z] # At least 1 number between [0-9] # At least 1 letter between [A-Z] # At least 1 character from [$#@] # Minimum length of transaction password: 6 # Maximum length of transaction password: 12 # Your program should accept a sequenc...
true
cfe9703339f8e79ca07db80d9cb713aff1def06d
enzosison/lab0.1
/lab-0-enzosison-master/planets.py
439
4.1875
4
# float string -> float # Given earth weight and planet, returns weight on provided planet def weight_on_planets(pounds, planet): # write your code here return 0.0 if __name__ == '__main__': pounds = float(input("What do you weigh on earth? ")) print("\nOn Mars you would weigh", weight_on_planets(p...
true
c1b8c156121f86fdf828f400df08ae45d3e8dd56
nelliher/IS51Test2
/test_2.py
1,466
4.15625
4
""" This program will display the class exam averages based on the total number of grades. The first calculation will display the number of grades. The second calculation will display the average of the total grades. The third calculation will display the total percentage of the grades abover average. There will be t...
true
96ec75d796df27044f683ff8b16a0d53b86c74b5
hkmangla/ML_mini_projects
/quiz.py
908
4.25
4
"""Count words.""" def count_words(s, n): """Return the n most frequently occuring words in s.""" # TODO: Count the number of occurences of each word in s l = s.split(); occurrenceList = {} for i in l: if i in occurrenceList.keys(): occurrenceList[i] += 1 else: ...
true
98bbbc24bcb57f9ccfe76b1532cec9ea83e35558
MalAnna/geekbrains-homework
/algorithms python/lesson2/task8.py
872
4.1875
4
# 8.Посчитать, сколько раз встречается определенная цифра в введенной # последовательности чисел. Количество вводимых чисел и цифра, которую # необходимо посчитать, задаются вводом с клавиатуры. digit_count = 0 print('Сколько чисел хотите вводить?') count = int(input('count = ')) print('Какую цифру хотите найти?') dig...
false
9f94c8ea9a5278d3b57bc8e9eebf413e370dd6cf
233-wang-233/python
/day6/face_object.py
1,249
4.25
4
class Student(object): # __init__是一个特殊方法用于在创建对象时进行初始化操作 # 通过这个方法我们可以为学生对象绑定name和age两个属性 def __init__(self,name,age): self.name=name self.age=age def study(self,course_name): print('%s正在学习%s.'%(self.name,course_name)) # PEP 8要求标识符的名字用全小写多个单词用下划线连接 # 但是部分程序员和公司...
false
01e06eb1c3001bddefaa09ced8952b3bb17c6b8d
SCollinA/python104
/square2.py
901
4.34375
4
# Ask user for length of square. Print square using one * character per unit length of square. BAD_INPUT = True # set flag for asking for user input ERROR_MESSAGE = "Bad user input." # message if bad input received while BAD_INPUT: # continue to ask for input until is is int try: # prompt user for size of square ...
true
53266a0ba7e13ea1c9ffe3cb4af43cec27cb8be5
SCollinA/python104
/square.py
416
4.15625
4
# Print a 5x5 square of * characters row_counter = 5 # number of rows while row_counter > 0: # loop through all rows col_counter = 5 # number of columns while col_counter > 0: # loop through all cols print('*', end='') # print one * per col without starting new line col_counter -= 1 # decremen...
true
5850c4b0d8dfc977e0b94d88313474deafaa4241
chigginss/HackerRank
/cracking_the_coding_interview/python_solutions.py
490
4.3125
4
# Cracking the Coding Interview Problems from HackerRank """ 1) Array Left Rotation A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5] then the array would become [3,4,5,1,2]. Given an array a of n intege...
true
b910a79338e52c34ca9f005ca5a8c9b0894edbf9
gozeberke/python_temel_projeler
/loop-method.py
741
4.28125
4
#range #1 den başla 10a kadar git ''' for item in range(1,10): print(item) ''' #2 den başla 2 şer 2 şer artarak 20 ye kadar git for m in range(2,20,2): print(m) #döngünün dışında da kullanılabilir #1 den başlayıp 10 a kadar 2 şer 2 şer artar bunun list çevririr ve ekrana yazdırır. print(list(range(1,20,2))) ...
false
da2733853971436ec9f3d09c8bb0b34d930186b4
sourcery-ai-bot/Python-Curso-em-Video
/python_exercicios/desafio041.py
926
4.15625
4
# A Confederação Nacional de Natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: # - Até 9 anos: MIRIM # - Até 14 anos: INFANTIL # - Até 19 anos: JÚNIOR # - Até 25 anos: SÊNIOR # - Acima de 25 anos: MASTER from datetime import date anonasc = int(inpu...
false
0af7622fa9152a670732e2e36931070ec8640447
Bichwaa/xtractor
/xtractor/xtractor/extractor.py
1,032
4.125
4
''' This module contains functions which get the text content of an xml file, strips it of its xml tags and returns what is left. the get_text function can also parse text from ordinary text files (format txt) and html files. ''' import re, fire def get_text(enc='utf-8', filepath=None): """returns...
true
90c3f5756220e27d6ed387d351a987a7de3d006a
vvveracruz/ossu
/mit-intro-to-cs/ps0/ps0.py
434
4.21875
4
# Write a program that does the following in order: # 1. Asks the user to enter a number “x” # 2. Asks the user to enter a number “y” # 3. Prints out number “x”, raised to the power “y”. # 4. Prints out the log (base 2) of “x”. import numpy as np x = float( input( ' Enter a number x: ' ) ) y = float( input( ' Enter...
true
a407b5c53068955c7b60a03899b001fb4804777c
600000rpmaker/funutils
/keybyvalue.py
717
4.21875
4
# -*- coding: utf-8 -*- #!/usr/bin/env python def get_key_by_value(dict, value): for k, v in dict.items(): if v == value: print "Found key: \"" + str(k) + "\" with type: " + str(type(k)) + " for the specified value: \"" + str(value)+"\"" + " in the dict: " + str(dict) return k el...
false
c9f3079ae8a217c5a860e446bae77d285b09f343
sohailshaikh1432/BasicPrograms
/FactorialFind.py
342
4.21875
4
def main(): # declaring vairiables input = userInput fact = 1 #!For loop to find factorial of given input for i in range(1, input+1): fact= fact*i print("Factorial of ", input ," is :", fact) if __name__ == "__main__": # Taking input from the user userInput = int(input("Enter n...
true
636dc6d3956a31975061555eb94baf2380c0bf50
Matvey2009/HardChildhood
/Python/Lessons/Lesson0.7 - операторы .py
1,529
4.15625
4
# Операторы x = 5 #input("Ввод в консоль - ") print("Конвертация в число - ", int(x)) print("Конвертация в дробное число - ", float(x)) print("") x = "Hello Word" print("Длина строки - ", len(x)) print("Конвертация в строку - ", str(len(x)) + " - Штук") print("Транформация в список - ", list(x)) print("Транформация в...
false
3826627ba652855ef9b4266e245487d6bbfae012
97joseph/Digital-Intelligence-2
/hw2problem2.py
2,813
4.1875
4
# PUT YOUR NAME HERE # PUT YOUR SBU ID NUMBER HERE # PUT YOUR NETID (BLACKBOARD USERNAME) HERE # # IAE 101 (Fall 2021) # HW 2, Problem 2 def frequency(c, s): # ADD YOUR CODE HERE return -1 # CHANGE OR REMOVE THIS LINE # 1. First, count the number of times that c appears in s. c_occ = 0 for ch in ...
true
2ab29e82d6febd71753b2cf4920f1f85760374e5
sm-sarkar/Python-28June
/day3.py
632
4.34375
4
#CALCULATOR TO PERFORM ALL ARITHMETIC OPERATIONS '''USER INPUT''' print("Welcome To Python Calculator") a = int(input("Enter First Number")) b = int(input("Enter Second Number")) '''ADDITION''' s = a+b print( f"The sum of {a} and {b} is {s}") '''SUBTRACTION''' m = a-b print( f"The difference of {a} and ...
false
ea490952881942ccb298d4703bc51089fb4368c8
deminovamv/lesson1
/list.py
683
4.1875
4
#Задание # Создайте список из чисел 3, 5, 7, 9 и 10.5 # Выведите содержимое списка на экран # Добавьте в конец списка строку "Python" # Выведите длину списка на экран# phones = [3, 5, 7, 9 , 10.5] print(phones) phones.append("Python") print(phones) print(len(phones)) print(f'Начальный элемент списка: {phones[0]}') prin...
false
78368a525bcf610efa7f1d09ddf571bc89074fa1
Shwetapatil05/new-python
/control_flow_statements/for_loop.py
1,198
4.21875
4
#------------------------------------------------------- #Description : for loop #syntax : # for item in items: # statements; #About : Iterates over single character of a string #------------------------------------------------------- player = 'sudeep'; print("------------Iterating over a String-...
true
ad7ade34ea80f05b2d687e3eebd3200ddef14af4
noy20-meet/meet2018y1lab7
/fun2.py
1,471
4.1875
4
import turtle turtle.goto(0,0) UP = 0 DOWN= 1 LEFT= 2 RIGHT= 3 SPACE= 4 direction = None pen_is_up = False def up(): global direction direction= UP print("You pressed the up key.") on_move(10, 20) def down(): global direction direction= DOWN print("You pressed the down key.") ...
false
b45b49e7fa5d900b3bd741393e6cd48cc6f05813
countvajhula/composer
/composer/timeperiod/utils.py
710
4.21875
4
from datetime import timedelta def get_next_day(date): """Given a date, return the next day by consulting the python date module :param :class:`datetime.date` date: The date to increment :returns :class:`datetime.date`: The next date """ next_day = date + timedelta(days=1) return next_day...
true
8e47468aeab29400f67729f5d8908eb4c23e22f7
Itz-Cook1e/College-Mailbox-File
/main.py
1,036
4.25
4
# Assignment: # Write a program to prompt the user to provide a file name # (use the file that is provided, mbox-short.txt) read through the file, and print the first 50 characters of each line that begins with 'Subject' # (line by line). Lastly, provide a count of the number of these lines. # Your program should incl...
true
55982d0837bb9a8288fb9261c5ea7f00690f1327
PROxZIMA/Python-Projects
/User_Packages/amult.py
236
4.125
4
def mult(): L=[] b=1 num=int(input("Enter how many numbers you are multiplying : ")) for i in range(num): n=float(input("Enter the numbers : ")) L.append(n) b=b*n print('Multiplication of the numbers is =',b)
true
ce3d1049e7150520a9695f3343e19ff00918d3ec
vinhlee95/oop-python
/instance_class_static_methods/main.py
1,663
4.375
4
from typing import List class MyClass: foo = "bar" def method(self): """ Instance method could be invoked only from a class instance It could modify the instance's propery, but not the class itself """ return f"instance method called. foo is {self.foo}" @classmethod def classmethod(cls): """ Class...
true
df816e3e75ebdaf4d9a723b4f95586363fae2151
StoopDJ/Second_Year_College
/Python/Overloading.py
2,021
4.46875
4
# Function: # 1. Write a class to represent an Item - each item has name, price and quantity. # Include a method to calculate total price. Test your class by creating few Item objects. # 2. Write a class to represent a complex number. # Complex numbers can be written in the form of a+bi where a and b are real numbe...
true
63f15acc67fd66d8f80a31b9c49eca272589424c
tingyu-ui/test
/demo_class.py
1,876
4.25
4
#通过class关键字,定义了一个类 #创建一个人类 class Person: #类变量 name = "default" age = 0 gender = 'male' weight = 0 #构造方法,在类实例化的时候被调用 def __init__(self,name,age,gender,weight): self.name = name self.age = age self.gender = gender self.weight = weight # print("...
false
d4f5c2c432b228ea23e98c35b684d8da3d14514f
RUCKUSJERRY/Python_Practice
/Python01/com/test03/test.py
684
4.125
4
# 1번 문제 x = input('숫자 입력 : ') a, b = 0, 1 while a < int(x): print(a, end=" ") a, b = b, a+b print() # 2번 문제 def fibo1(x): a, b = 0, 1 while a < int(x): print(a, end=" ") a, b = b, a+b print() # 3번 문제 x = input('숫자 입력 : ') res = [] a, b = 0, 1 while a < int(x): res.appe...
false
171955d3878d5b80117e1ad0e116814933795550
ssarber/PythonClass
/algorithms/reverse_array.py
856
4.3125
4
# Task # Given an array, A , of N integers, print A's elements in reverse order as a single line of space-separated numbers. # Input Format # The first line contains an integer, N (the size of our array). # The second line contains space-separated integers describing array A's elements. # Output Format # Print t...
true
eff3d354e94012123d2469011b63875e44065fbd
ssarber/PythonClass
/fibonacci.py
765
4.21875
4
# def fibonacci(n): # if n == 1 return 1 # elif n == 0 return 0 # y = 1 # x = 2 # for x in range (0, n): # x = 0 + 1 def factorial(num): # product = 1 # for i in range(num): # product *= (i+1) # return product if num <= 1: return 1 return num * factorial(num - 1) # print(factorial(5)) # d...
false
c0e7f85663ca77ab696771f4f1baa11e9e7be9f0
BernardoLpz/python_tutorial_ptbr
/05_es_tela_formato/04_entrada_dados_tela.py
722
4.34375
4
# # Autor : LF Silva # Data : 13/04/2020 # # Formato da entrada de dados em tela # A entrada de dados, por padrão, é para variáveis do tipo string. Portanto, é # necessário SEMPRE converter a variável para o tipo desejado. # # Comando input para entrar com informação em tela idade = input("Entre com sua idade: ") # ...
false
97c17d27cc0767e5952b5102cee24c3f58b22f84
BernardoLpz/python_tutorial_ptbr
/04_modulos_basico/02_module_numpy_basic.py
1,975
4.34375
4
# # Autor : LF Silva # Data : 01/05/2018 # # Usando módulo Numpy import numpy as np # O principal objetivo do módulo NumPy é o tratamento de arrays (listas) # homogêneas (de apenas um tipo de variável) e multidimensionais (vetores, # matrizes etc). O array é tratado como uma tabela de elementos (usualmente # números...
false
da5c62c91ad02ba3de961f43a0f0c4d8ea072622
BernardoLpz/python_tutorial_ptbr
/11_numpy/04_copia_arrays.py
2,692
4.40625
4
# # Autor: LF Silva # Data : 23/11/2020 # # Introdução ao uso de Numpy - Cópia de arrays # O problema de shallow e deep copy import numpy as np # Python é bem espertinho ao alocar a memória para suas variáveis. # Mas isso pode gerar algumas situações complicadas com o # compartilhamento de informações na memória. x ...
false
36a8a44107be97f1470f0d15dfc0dd886b1b3379
gladystyn/MCQ_biology_revision_program
/app.py
2,740
4.25
4
print("Title of program: MCQ biology revision program") print() counter = 0 score = 0 total_num_of_qn = 3 counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "What does the liver produce?") print(" a) Salivary amylase") print(" b) Pancreatic amylase") print(" c) Bile") print("...
true
05de78717af1e3c22bf978c5593410db9850883c
pujalb/100-days-of-python
/Day-08-Function-Parameters-&-Caesar-Cipher/Interactive Coding Exercise - Day 8.2 Prime Number Checker/main.py
726
4.21875
4
#Write your code below this line 👇 from math import sqrt, ceil def prime_checker(number): # Ceck if number is greater than 1 if number < 2: print("It's not a prime number.") return # Instead of checking all numbers from 0 to number, just check from 0 to square root of the number last_...
true
5d9f5f14d35c6ea272b6df47ccbab10b72a9a3c5
sharder996/hacker-hell
/leetcode/python3/[208]_implement-trie-prefix-tree.py
1,640
4.1875
4
# # @lc app=leetcode id=208 lang=python3 # # [208] Implement Trie (Prefix Tree) # # @lc code=start class TrieNode: def __init__(self, val: set, next): self.val = val self.next = next self.terminal = False class Trie: ''' Accepted 15/15 cases passed (176 ms) Your runtime beats 65.22 % of python3 ...
true
7d9917a5b0e25d38d509e0f8fda62700203cefad
gmolinsm/PythonP2
/Exceptions/main.py
438
4.21875
4
# A simple example in how to catch exceptions try: num = input("Give me a number: ") num = int(num) num2 = input("Give me another number: ") num2 = int(num2) result = num / num2 except ValueError: print("Please give me a proper number") except ZeroDivisionError: print("The second number can...
true
fffa83c7ff04e72062d67214030c71801be66501
DikranHachikyan/CPYT210713
/ex66.py
1,197
4.25
4
# 1.дефиниция на класа class Point(): def __init__(self, x = 0, y = 0, *args, **kwargs): print('Point Ctor') # данни на обекта self.x = x self.y = y # методи на обекта def draw(self): print(f'draw point at ({self.x}, {self.y})') def move_to(self, dx, dy): ...
false
91b3eb9a9d705d92178bf2a8e465c1a9cfd0cead
VladyslavHnatchenko/theory_python
/function.py
1,231
4.125
4
"""Function Parameters and Arguments.""" def cylinder(h, r=1): side = 2 * 3.14 * r * h circle = 3.14 * r ** 2 full = side + 2 * circle return full figure1 = cylinder(4, 44) figure2 = cylinder(232) print(figure1) print(figure2) """Programming Functions.""" # def rectangle(): # a = float(input("W...
false
92d7ce74f89e34e9e906ee3917e63fc26782c7ae
polivares/FullStackPython2021-1
/Clase3/multipleargs.py
896
4.28125
4
# Puedes agregar múltiples argumentos a las funciones y de distintas maneras def f1(a,b,c): print(a,b,c) f1(1,2,3) f1(b=1,c=2,a=3) # Formas de indicar argumentos de entrada def f2(a, b,*args): print(a,b) for i in args: print(i) print("Función llamada con dos argumentos") f2(1,2) # Esto muestra l...
false
b5d5d914b2cd271d0a401646d4eb7298eca3234a
rybakovas/Python
/Python/basic/calculator_full.py
415
4.125
4
from math import * num1 = float(input("Enter first number: ")) op = input("Enter you operator: ") num2 = float(input("Enter second number: ")) if op == "+": result = num1 + num2 elif op == "-": result = num1 - num2 elif op == "/": result = num1 / num2 elif op == "*": result = num1 * num2 else: res...
false
a6c3fae7387c6ebe7a2593a0f5a55f6b445df0ca
rybakovas/Python
/Python/basic/if_statement_comparison.py
390
4.125
4
def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: print("Number " + str(num1) + " is the bigger") elif num2 >= num1 and num2 >= num3: print("Number " + str(num2) + " is the bigger") else: print("Number " + str(num3) + " is the bigger") max_num(300, 400, 5) # == equa...
true
0834c5ba0b3caa6836d6ad1e26eb9da989fac8bc
santokalayil/my_python_programs
/name_age_turning_100.py
1,356
4.15625
4
# Creator : Santo K. Thomas '''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.''' import datetime now = datetime.datetime.now() this_year = now.year name = str(input('Enter Your Name?')) while True: ...
true
0e16eeb99d2583a8bc229813196f9d976b674ac9
michaelwise12/cmpt120wise
/bankaccount.py
1,310
4.15625
4
# bankaccount.py class BankAccount: """Bank Account protected by a pin number.""" def __init__(self, pin): """Initial account balance is 0 and pin is 'pin'.""" self.balance = 0 print("Welcome to your bank account!") self.pin = pin def deposit(self, pin, amount):...
true
7249e01fd01776deca989d0ac449bc9021f147b7
Amarmuddana/python-training
/Day9/day9.py
1,236
4.25
4
#How to create a dictionary # empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'text1', 2: 'text2'} # dictionary with mixed keys my_dict = {'name': 'ram', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = d...
true
15ebb008327450bfe50afb4f0928fc099f1863cb
Amarmuddana/python-training
/Day7/day7.py
791
4.59375
5
Formatters # .formats in strings print("ravi has {} balloons.".format(5)) string = "ravi loves {}." print(string.format("python")) string = "ravi loves {} {}." print(string.format("open-source", "software")) string = "ravi loves {} {}, and has {} {}." print(stri...
false
242954fda3a7a3e112413a3dac56c9e42534867f
Ronak912/Programming_Fun
/Array/LargetSumContiguousSubArray.py
634
4.15625
4
# https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/ # Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers # which has the largest sum. # ex: lst = [-2, -3, 4, -1, -2, 1, 5, -3] # Answer: Maximum sum is for subarray [4, -1, -2, 1, 5] = 7 def getMax...
true
45291fb16c1e03a09bdba50879e6df0cc4ee93a4
Ronak912/Programming_Fun
/String/GroupWordsWithSameSetChar.py
1,454
4.40625
4
# http://www.geeksforgeeks.org/print-words-together-set-characters/ """Group words with same set of characters Given a list of words with lower cases. Implement a function to find all Words that have the same unique character set . Example: Input: words[] = { "may", "student", "students", "dog", "st...
true
f0c815fa098139a73e9f53b7f7e1c57d407d0e05
Ronak912/Programming_Fun
/String/LongestSubsequenceWithAtleastKTimes.py
1,022
4.15625
4
# https://www.geeksforgeeks.org/longest-subsequence-where-every-character-appears-at-least-k-times/ ''' Method 1 (Brute force) We generate all subsequences (check file GetAllSubString.py). For every subsequence count distinct characters in it and find the longest subsequence where every character appears at-least k tim...
true
454d52168a772d064bde8aea9ea92381c30cb877
Ronak912/Programming_Fun
/hashmap/FindItinerary.py
1,135
4.46875
4
# http://www.geeksforgeeks.org/find-itinerary-from-a-given-list-of-tickets/ # # Find Itinerary from a given list of tickets # Given a list of tickets, find itinerary in order using the given list. # # Example: # # Input: # "Chennai" -> "Banglore" # "Bombay" -> "Delhi" # "Goa" -> "Chennai" # "Delhi" -> "Goa" # # Out...
true
cd903b6bda471945b827c95f743e0221a18770f7
Ronak912/Programming_Fun
/LinkedList/printReverseLinkedListUsingRecursive.py
492
4.40625
4
# http://www.geeksforgeeks.org/write-a-recursive-function-to-print-reverse-of-a-linked-list/ # Write a recursive function to print reverse of a Linked List import LinkedList def printReverseRecur(node): if node is None: return printReverseRecur(node.next) print node.data, if __name__ == "__ma...
true