blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
f8b70ce34396a0e5c3d0aac7f95ede04f9169254
sreekanth-s/python
/old_files/count_number_of_on_bits.py
350
4.28125
4
print("Enter a number to find the number of ON bits in a number.") num=int(input("Enter a positive integer: ")) print_num = num count=0 if num > 0: while num > 0: if num & 1: count+=1 num = num >> 1 print("The number entered", print_num, "has", count, "ON bits.") else: print...
true
0507f088e2b020bb677f3772efd8affcdf63f8b3
sreekanth-s/python
/old_files/factorial.py
730
4.46875
4
""" num=int(input("Enter a number to find factorial: ")) if (num <= 0): print("Enter a valid integer! ") else: print("You've entered ", num) for i in range(1,num): num=num*i print("and the factorial is ",num) """ num=int(input("Enter a number to find factorial: ")) print("You've entered ", num) ...
true
9363df1f25908275c4b4446c0911a110d7c7585b
sreekanth-s/python
/data_structures/stack_implementation.py
2,510
4.28125
4
def execution(): opr = input("Enter an operation to perform: ") if opr == "1" or opr == "push": value = input("Enter a value to push: ") ret = stack_push(value) if ret == None: print("The stack is full. try popping. \n \n") execution() else: ...
true
33c2bf53a6057e5985882bcb595bbf81c995cb8b
moisesvega/Design-Patterns-in-Python
/src/Creational Patterns/Factory Method/Factory.py
710
4.21875
4
''' Created on Jul 16, 2011 @author: moises ''' '''Defines the interface of objects the factory method creates''' class Product: pass '''Implements the Product interface''' class ConcreteProductA( Product ): def __init__( self ): self.product = "Guitar" '''Implements the Product interface''' class C...
true
b5ce82a388586bf89689129118e1f9ce9a4a749a
JackRossProjects/cs-module-project-recursive-sorting
/src/sorting/sorting.py
1,708
4.21875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements indexM = 0 while (len(arrA) > 0) & (len(arrB) > 0): if arrA[0] <= arrB[0]: merged_arr[indexM] = arrA.pop(0) e...
false
cae9cefa76b2a60f0d07f80b40946fca22e40def
AmandaRH07/PythonUdemy
/3. Programação Orientada a Objetos/112_Metaclasses.py
1,005
4.3125
4
""" Metaclasses Em Python tudo é objeto, incluindo classes Metaclasses são classes que criam classes Ex: type é uma metaclasse """ class Meta(type): def __new__(mcs, name, bases, namespace): print(name) if name == "A": return type.__new__(mcs, name, bases, namespace) print(name...
false
3c274abda74e08daecf01b020f49b323b8246366
AmandaRH07/PythonUdemy
/2. Intermediário/47- Ex01.py
1,360
4.3125
4
""" 1 - Crie uma função que exibe uma saudação com os parâmetros saudacao e nome. """ def saudacao(saudacao, nome): print(f"{saudacao} {nome}") saudacao("Olá","Maria") """ 2 - Crie uma função que recebe 3 números como parâmetros e exiba a soma entre eles. """ def soma(n1,n2,n3): print(f"{n1} + {n2} + {n3} =...
false
7a7ea125fd59dbdf811747afd70283ae9429c947
VamshiPriyaVoruganti/HackerRank
/Programs/Python functionals/lambda.py
342
4.15625
4
cube = lambda x: pow(x,3) # complete the lambda function def fibonacci(n): a=0;b=1;l=[] if n>0: l.append(a) if n>1: l.append(b) for x in range(n-2): c=a+b l.append(c) a=b b=c return l # return a list...
false
dd011849fd5a7129d7fc90f9f0df97a8f2c5094f
felipellima83/wiki.python.org.br-EstruturaSequencial
/Exercicio07.py
452
4.1875
4
#Felipe Lima #Linguagem: Python #Exercício 07 do site: https://wiki.python.org.br/EstruturaSequencial #Entra com a altura do quadrado altura = float(input("Qual a altura do quadrado: ")) #Entra com a base do quadrado: base = float(input("Qual a largura do quadrado: ")) #Realiza os cálculos area = base*altura dobro =...
false
3625d90df67e51c6683231dbe2fe15ab18776c5b
JudoboyAlex/python_fundamentals2
/reinforcement_exercise2.py
1,392
4.15625
4
# Let's take a different approach to film recommendations: create the same variables containing your potential film recommendations and then ask the user to rate their appreciation for 1. documentaries 2. dramas 3. comedies on a scale from one to five. If they rate documentaries four or higher, recommend the documentar...
true
942c7fe91f9833c7804f86a42f4b5dcb6aa49e5b
vineetbaj/Python-Exercises
/30 days of code/Day 3 - Intro to Conditional Statements.py
946
4.5625
5
""" ***Day 3*** Objective In this challenge, we learn about conditional statements. Check out the Tutorial tab for learning materials and an instructional video. Task Given an integer, , perform the following conditional actions: If is odd, print Weird If is even and in the inclusive range of to , print Not Weird ...
true
ed57527d425099403a508453e90d0850c3e8e825
0f11/Python
/pr04_adding/adding.py
2,513
4.21875
4
"""Adding.""" def get_max_element(int_list): """ Return the maximum element in the list. If the list is empty return None. :param int_list: List of integers :return: largest int """ if len(int_list) == 0: return None return max(int_list) pass def get_min_element(int_li...
true
f91ab594ea14320cd78b821af01b64ed200abb3a
0f11/Python
/pr02_triangle/pr02_triangle.py
1,440
4.3125
4
"""Triangle info.""" import math def find_triangle_info(a, b, c): """ Write a function which finds perimeter, area and type of triangle based on given side lengths. (Note: a <= b <= c). The function should print "{type_by_length} {type_by_angle} triangle with perimeter of {perimeter} units and area ...
false
ca58251889ad80531e12647fc58181b86fe0f808
sonhal/python-course-b-code
/user_loop.py
421
4.125
4
# CLI program for pointlessly asking the user if they want to continue loop_counter = 0 while(True): print("looped: "+ str(loop_counter)) loop_counter += 1 user_input = input("Should we continue? ") if user_input == "yes": continue elif user_input == "no": print("Thank you for playi...
true
274acbf8fa74954bcf8885b4e0a203f14e6604c3
donyu/euler_project
/p14.py
1,028
4.3125
4
def collatz_chain(max): longest_chain.max = max longest_chain.max_len = 0 longest_chain(1, 1) return longest_chain.max_len def longest_chain(x, length): """Will find longest Collatz sequence by working backwards recursively""" if length > 10: return # base case if number over 1,000,000 if x > longe...
true
309aea1305c2be0d6acfcb41f6877965499388a4
malakani/PythonGit
/mCoramKilometers.py
757
4.71875
5
# Program name: mCoramKilometers.py # Author: Melissa Coram # Date last updated: September 21, 2013 # Purpose: Accepts a distance in kilometers and outputs the distance in kilometers # and miles. # main program def main(): # get the distance in kilometers distance = int(input('Enter the distance in kilometers:...
true
cbd34a38ce7d9d31317024c247563515d3bb48ad
malakani/PythonGit
/mCoramPenniesForPay.py
1,171
4.59375
5
# Program name: mCoramPenniesForPay.py # Author: Melissa Coram # Date last updated: 10/24/2013 # Purpose: Calculates and displays the daily salary and total pay earned. def main(): # Get the number of days from the user. print('You start a job working for one penny a day and your pay doubles every day thereaft...
true
59a6d3c3e45ad3b18ac8089856e5feda50877c3a
CharlieDaniels/Puzzles
/trailing.py
410
4.25
4
#Given an integer n, return the number of trailing zeroes in n! from math import factorial def trailing(n): #find the factorial of n f = factorial(n) #cast it as a string f_string = str(f) #initialize counters num_zeroes = 0 counter = -1 #count the number of zeroes in n, starting from the end while f_string[...
true
58dae9443233c7661c2740523f7dfd559d313401
TanvirAhmed16/Advanced_Python_Functional_Programming
/11. List Comprehensions.py
1,716
4.46875
4
''' # Comprehensions in Python - Comprehensions in Python provide us with a short and concise way to construct new sequences (such as lists, set, dictionary etc.) using sequences which have been already defined. Python supports the following 4 types of comprehensions: # List Comprehensions # Dictiona...
true
ff474eb65652308fee85de0d5d38885903b7372e
aaronyang24/python
/Assignment_Ch02-01_Yang.py
320
4.15625
4
time = int(input("Enter the elapsed time in seconds: ")) hours = time // 3600 remainder = time % 3600 min = remainder // 60 sec = remainder % 60 print("\n" + "The elapsed time in seconds = " + str(time )) print ("\n" + "The equivalent time in hours:minutes:seconds = " + str(hours) +":" + str(min)+":" + str(sec) )
true
e5651299e4b4159e6331e910dac0380344e35ba3
phillib/Python-On-Treehouse.com
/Python-Collections/string_factory.py
565
4.28125
4
#Created using Python 3.4.1 #This will create a list of name and food pairs using the given string. #Example: "Hi, I'm Michelangelo and I love to eat PIZZA!" dicts = [ {'name': 'Michelangelo', 'food': 'PIZZA'}, {'name': 'Garfield', 'food': 'lasanga'}, {'name': 'Walter', 'food': 'pancakes'...
true
277698d0c991dcf689dac18f73eb70137e75c573
elliehendersonn/a02
/02.py
766
4.65625
5
""" Problem: The function 'powers' takes an integer input, n, between 1 and 100. If n is a square number, it should print 'Square' If n is a cube number, it should print 'Cube' If n is both square and cube, it should print 'Square and Cube'. For anything else, print 'Not a power' Cube numbers ...
true
5a7ca588a04c1717f05edb329cd3dda69519b0d7
ShemarYap/FE595-Python-Refresher
/Python_Refresher_Huq.py
1,220
4.1875
4
# Importing numpy and matplotlib import numpy as np import matplotlib.pyplot as plt # Setting the X values in the x variable x = np.arange(0, 2*np.pi, 0.01) # Setting the values for Sine in the sin_y variable sin_y = np.sin(x) # Plotting with x variable for X-axis and sin_y for Y-axis. # The linewidth arg...
true
13939777116661ac7fcd97f066470d0cd139d195
ramkishor-hosamane/Python-programming
/comb.py
646
4.25
4
def list_powerset(lst): # the power set of the empty set has one element, the empty set result = [[]] for x in lst: # for every additional element in our set # the power set consists of the subsets that don't # contain this element (just take the previous power set) # plus th...
true
75adbfcf31be2ec4bde27deffa4dde1782e2e5a7
Darlight/Algoritmos_proyectos
/proyecto_lamda.py
1,240
4.15625
4
""" Universidad del Valle de Guatemala CC3041 - Analisis y diseño de algoritmos Ing. Tomas Galvez Mario Perdomo Carnet 18029 proyecto_lamda.py """ #Usando la manera pythonica de los lambdas: https://realpython.com/python-lambda/ f = lambda x: x+1 g = lambda x: 2 * x h = lambda x, y: x**2 + y**2 cero = lambda fn, x: ...
false
286551edca202747a0b390aa212e35136b4f3e21
yegornikitin/itstep
/lesson12/triple_result.py
717
4.15625
4
try: a = int(input("Please, insert first integer: ")) b = int(input("Please, insert first integer: ")) # First function, that will only show a + b def add(a, b): return a + b print("---------------") print("Result without decorator: ", add(a, b)) # Second function wi...
true
72d6893e88e7ae669fd7d5df179cbfb186f83e4d
simonisacoder/AI
/lab/lab1 数据集处理/re.sub.py
346
4.15625
4
import re # first way to check whether a word has number def hasNum1(string): return any(char.isdigit() for char in string) #second way: regular expression def hasNum2(string) s = "123 a:1 b:2 c:3 ab cd ef" s = s.split() print(s) for i in s: if re.search(r'\d',s(i),flag=0): print(s(i).group()) e...
true
a2669deb7b77b947e9eed229a36010a02af6f7e7
Allen-heh/learnpython
/d8/point.py
818
4.21875
4
#!/usr/bin/env python import math class point(object): def __init__(self, x, y): self._x = x self._y = y self.__z = x def move_to(self, x1, y1): self._x = x1 self._y = y1 def move_by(self, dx, dy): self._x += dx self._y += dy def distance(self,...
false
5ea76df223d67ff9b2bf3f6d1046997dc34ffcf0
bhanurangani/code-days-ml-code100
/code/day-2/5.Getting Input From User/AppendingN ame.py
407
4.46875
4
#appending first name and last name name=str(input("enter the first name")) surname=str(input("enter the last name")) #no such function to append the string, but simply it can be done this way name=name +" "+ surname print(name) #using %s we can use to in cur the values to print z="%s is son of Mr. %s"%(name,surname) p...
true
f80b64c0f93213a777b10faa04c7a974bb75ecd8
vijayxtreme/ctci-challenge
/Arrays/isUnique_r1.py
822
4.28125
4
#Is Unique ''' I rewrote this one for ASCII / Alphabet Basically if there are more than 256 characters, this can't be unique because there are only 256 ASCII characters allowed. If we wanted to just do letters, we could do 26 letters and lowercase all entries The trick here is that unicode goes up to 128, so we can...
true
d2d7eaabb74520239b0efdccd27413c4b742894b
zwagner42/dailyprogrammer
/Easy Programs/Problems1-20/Calendar_Date.py
2,005
4.625
5
#Program to find the day of the month based on a given number day, number month, and number year from sys import argv, exit from calendar import isleap, monthrange, weekday from Input_Check import is_Number, is_Number_Range #Displays an error message for an incorrect argument list def error_Message_Argument_List(): ...
true
cb8284d5ee30e8184ecf6c0bd3579829540a5923
cjohlmacher/PythonSyntax
/words.py
367
4.3125
4
def print_upper_words(wordList,must_start_with): """Prints the upper-cased version of each word from a word list that starts with a letter in the given set""" for word in wordList: if word[0] in must_start_with: print(word.upper()) print_upper_words(["hello", "hey", "goodbye", "yo", "yes"],...
true
3012f4a88f70458121ad44ac54f5fcbf2d6bbbb7
Lievi77/csl-LATAM-graph
/public/data/LATAM_filter.py
2,206
4.21875
4
import pandas as pd # Script to filter out COVID-19 Data # by: Lev Cesar Guzman Aparicio lguzm77@gmail.com # ----------------------------METHODS------------------------------------------------------------------ # ------------------------------MAIN---------------------------------------------------------------------...
true
c05d8a1ab12e4ba46536fcbc1388c1ce99b990fe
ppppdm/mtcpsoft
/test/sharedMemory_test2.py
892
4.1875
4
# -*- coding:gbk -*- # author : pdm # email : ppppdm@gmail.com # # test shareMemory use import mmap with mmap.mmap(-1, 13) as map: map.write(b'helloworld') map.close() import mmap # write a simple example file with open("hello.txt", "wb") as f: f.write(b"Hello Python!\n") with open(...
true
407390b8637167b2ee74d8e96907547ac93f358c
iamSubhoKarmakar/Python_Practice
/inheritance.py
463
4.21875
4
class Parent(): def print_last_name(self): print('Bro') class Child(Parent): # we took the details from the parent class that's inheritance def print_first_name(self): print('BroJr') ''' #we gonna understand how to over write the parent last name def print_last_name(self)...
false
9c7870676af46b7a15cdcb2c193a4a3b6a789903
iamSubhoKarmakar/Python_Practice
/abstract-classes.py
788
4.125
4
#abstract classes - can not be instantiated, can only be ingerited, base class #it can not directly creeate an object but the data of this class can only be inherited to a #child clss for in an object #lets do cal salary from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod d...
true
dc30aba7ef2f24014fe1aecfbd7eb7226f272e4a
Tavares-NT/Curso_NExT
/MóduloPython/Extras04.py
803
4.1875
4
'''Faça um programa, com uma função que necessite de uma quantidade de argumentos indefinida, e um argumento de operação dos valores. Esta função deverá returnar o resultado da operação destes valores.''' def soma(valores): resultado = 0 for x in valores: resultado += x return resultado def calculadora(*va...
false
60910e3586893a7907446f288d24467d6bc58843
Tavares-NT/Curso_NExT
/MóduloPython/Ex44.py
338
4.15625
4
'''Crie um programa que receba um valor inteiro e avalie se ele é positivo ou negativo. Essa avaliação deve ocorrer dentro de uma função que retorna um valor booleano.''' def verificaSinal(): if n > 0: return print("Positivo") else: return print("Negativo") n = int(input("Digite um número inteiro: ")) ver...
false
ec1e387ffee6638ecc4084d227a4e4946d5ca223
akelkarmit/sample_python
/date_to_day.py
1,210
4.28125
4
print "this program asks for your birthday and tells you the day of the\nweek when you were born" import calendar birthdate=raw_input("enter your birthdate in dd-mm-yyyy format:") #raw_input assumes the input is a string date_of_birth=birthdate.split('-') day_of_birth=int(date_of_birth[0]) month_of_birth=int(date_of...
true
6176fd13f6bdf06ff6f1a66564d1d5c68b6a93b7
bhavikjadav/Python_Crash_Course_Eric_Matthes_Chapter_8
/8.8_User Album.py
914
4.46875
4
#!/usr/bin/env python # coding: utf-8 # # 8-8. User Albums: Start with your program from Exercise 8-7. Write a while loop that allows users to enter an album’s artist and title. Once you have that information, call make_album() with the user’s input and print the dictionary that’s created. Be sure to include a quit va...
true
3f83c54243c409dbc54082293f92a03ec42cabe8
marahalqaisi/Python-Course
/Week 1/Practice 1-A.py
971
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[17]: #Practice 1-A name = str (input ("Enter your name: ")) num1 = float (input ("Enter the 1st number: ")) num2 = float (input ("Enter the 2nd number: ")) add = float (num1 + num2) sub = float (num1 - num2) multi = float (num1 * num2) div = float (num1 / num2) reminder...
false
a6abd5d887e00d0a0b2a4b1b768dc9805d238b61
Danieldevop/Python-examples
/strings.py
234
4.3125
4
# -*- coding:utf -*- my_string = "platzi" my_string[len(my_string)-1] my_string.upper() otro = "EDIFICIO" otro.lower() otro.find("F") cadena = raw_input("digita cadena de text: ") print("el numero de caracteres es: ", len(cadena))
false
2b866761322eea62a1ae60e8df76f28c0eb9132b
Pavan53/Python
/phone_directory.py
789
4.21875
4
# program to create a dictionary with name and mobile numbers phones = {} while True: name = input("Enter name :") if name == "end": break mobile = input("Enter mobile number :") if name in phones: # name is found phones[name].add(mobile) # add new number to existing set else: ...
true
02ab80bea53b59c274ed247a2ea518e91af9da8a
HeyItsFelipe/python_tutorial
/12_if_statements.py
640
4.3125
4
######## If Statements ######## is_male = True if is_male: print("You are a male.") else: print("You are not a male.") is_tall = True if is_male or is_tall: print("You are a male or tall or both.") else: print("You are neither male or tall.") if is_male and is_tall: print("You are a tall male...
true
005f339a14302990e4093adebbd0428893e55377
mauroindigne/Python_fundementals
/02_basic_datatypes/1_numbers/02_01_cylinder.py
296
4.25
4
''' Write the necessary code calculate the volume and surface area of a cylinder with a radius of 3.14 and a height of 5. Print out the result. ''' h = 5 r = 3.14 pie = 3.14159265359 volume = (pie * (r ** 2) * h) surface = ((2 * pie * r * h) + (2 * pie * (r ** 2))) print(volume) print(surface)
true
f2ec17a815493ee02a2719a193f13f13072e1dae
mauroindigne/Python_fundementals
/04_conditionals_loops/04_00_star_loop.py
443
4.625
5
''' Write a loop that for a number n prints n rows of stars in a triangle shape. For example if n is 3, you print: * ** *** ''' n = 5 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number of columns # values is changing according to outer loop for j in range(0, i + 1...
true
e358b650105e95f0ab0a8d3ced40804d66fe7605
Tuzosdaniel12/learningPython
/pythonBasics/if.py
567
4.1875
4
first_name = input("What is your first name? ") print("Hello,", first_name) if first_name == "Daniel": print(first_name, "is learning Python") elif first_name == "Dan": print(first_name, "is learning with fellow student in the community! Me too!") else: #ask if user is under or equal the age of 6 age ...
true
1aa0a846265f753285fd6ba6fde13f5428dd8b8a
Dex4n/algoritmos-python
/CalculoSalario.py
1,143
4.1875
4
#Recebe o valor pago ao trabalhador por hora trabalhada. valor_por_hora=0.0 #Recebe o valor da quantidade de horas trabalhadas pelo trabalhador no mês. numero_horas_trabalhadas=0.0 #Esta variável irá fazer a operação de cálculo (multiplicação) entre a variável valor_por_hora e a variável numero_horas_trabalhadas. calcu...
false
ce9097e61112db7ffe0aff654197eaf7b5c3b523
thatvictor7/Python-Intro
/chapter7/chp7-solution3.py
1,611
4.5
4
''' Victor Montoya Chapter 7 Solution 3 Fat Gram Calculator 7 July 2019 ''' MULTIPLIER = 9 MIN = 0 TO_PERCENT = 100 LOW_FAT_LIMIT = 29 def main(): print("This program calculates the % of calories from fat in a food,\n" "and signals when a food is low fat.\n", "When asked,...\n", "enter the number of f...
true
3948e50e14e929686ac4bd5be841110740e37e45
thatvictor7/Python-Intro
/chapter5/chp5-solution9.py
1,458
4.25
4
# Victor Montoya # Chapter 5 Solution 9 # Pennies for Pay # Declared constants DAY_ADDITION = 1 PAY_DOUBLER = 2 STARTING_POINT = 1 # Declared variables that will hold input, current pay getting doubles and the addition of salary days = 0 current_pay = .01 running_total = .01 def main(): display_program_and_obta...
true
f373e03756c50870dbd58f0ebecf4c85b4fe7d77
thatvictor7/Python-Intro
/chapter5/chp5-solution8.py
933
4.3125
4
# Victor Montoya # Chapter 5 Solution 8 # Celcius to Farenheit Table # Declared constants for celcius to farenheit formula and the number of times t]the loop will be executed FARENHEIT_MULTIPLIER = 1.8 FARENHEIT_ADDITION = 32 MAX_CELCIUS = 21 def main(): iterator() def iterator(): # for loop will iterate fro...
true
a0848d243527fa1cf17542b9c5fc6d1e34a78cfc
maknetaRo/python-exercises
/definition/def3.py
273
4.34375
4
"""3. Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7) Expected Output : -336 """ def multiply_all(lst): total = 1 for num in lst: total *= num return total lst = [8, 2, 3, -1, 7] print(multiply_all(lst))
true
72b912889edb8a0e1491922c0b5afbbe0ac2e1ff
JakeEdm/CP1404Practicals
/prac_05/hex_colours.py
529
4.25
4
"""Hex Colours""" COLOUR_TO_HEX = {"blueviolet": "#8a2be2", "chocolate": "#d2691e", "green": "#00ff00", "hotpink": "#ff69b4", "light": "#eedd82", "lightsalmon": "#ffa07a", "medium": "#66cdaa", "navyblue": "#000080", "pale": "#db7093", "red": "#ff0000"} colour = input("Enter a colour:...
false
07f0eabd1a032f5644e2709ed716cfc9adc36341
liwaya29/python
/7_conditions.py
1,122
4.34375
4
x = 2 y = 3 # equality operators print(x == y) z = x == y print(z) print(type(z)) print(x > y) print(x < y) print(x <= y) print(x >= y) pets = [1, 2, 3, "bob"] print(1 in pets) print("bob" in pets) print(4 not in pets) # negation = not if x == y: print("this is false") if x <= y: print("this is true...
false
6e03cba810edb3796f2ad6a4a2bd6650b343c946
liuzh825/myAlgorithm
/Algorithm/如何实现栈/ep_02.py
1,545
4.125
4
''' 使用链表实现栈 具体方法 是否为空 栈的大小 栈顶元素 弹栈 压栈 后进先出 ''' class LNode(): def __init__(self, value=None): self.value = value self.next = None class MyStack(): def __init__(self, head=None): self.head = head # 是否为空 def isEmpty(self): return self.head == None or self.head.ne...
false
a323e99def52bd1f33d117695c02bb184c32bcb3
kozhukalov/snippets
/python/insertion_sort.py
321
4.1875
4
def insertion_sort(array): for i in range(1, len(array)): for j in reversed(range(i)): if array[j + 1] < array[j]: array[j], array[j + 1] = array[j + 1], array[j] else: break return array array = [7, 2, 1, 3, 4, 6, 5] print(insertion_sort(array)) ...
false
7db1b5ac4431d1aaeb4594ae6c001f2820814d14
s1s1ty/Learn-Data_Structure-Algorithm-by-Python
/Data Structure/Linked List/linked_list.py
1,548
4.15625
4
class Node: def __init__(self, item, next): self.item = item self.next = next class LinkedList: def __init__(self): self.head = None # Add an item to the head of the linked list def add(self, item): self.head = Node(item, self.head) # Delete the first item of the l...
true
893663f7761aa2739091d0bbeac4dadbfc913e88
Billdapart/Py3
/nestedFORLOOPpattern.py
380
4.125
4
# Write a Python program to construct the following pattern, using a nested for loop. # * # * * # * * * # * * * * # * * * * * # * * * * # * * * # * * # * num=5; for star in range(num): for repeat in range(star): print ('* ', end="") print('') for star in range(num,0,-1): for repe...
true
c6c19165d5a3b173c8f70261bfd76b088e5303f8
wasimusu/Algorithms
/sorting/mergeSort.py
1,409
4.34375
4
""" Implement merge sort using recursion Time complexity O(n*log(n)) Space complexity O(n) """ import random def merge(L, R): """ :param L: sorted array of numbers :param R: sorted array of numbers :return: L and R merged into one """ L = sorted(L) R = sorted(R) output = [] while...
true
51956ef9a3f2acc307c32feaddb78485acedbf7a
BhosaleAkshay8055/tkinter-examples
/examples/Tuttle/螺旋线绘制.py
304
4.25
4
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # 螺旋线绘制 import turtle import time turtle.speed("fastest") turtle.pensize(2) for x in range(100): turtle.forward(2 * x) # 角度的控制 # 不同的值不同, 绘制的图像会不同 turtle.left(90) time.sleep(3) turtle.done()
false
f2234cb106640a6bcb4bbc2f686292f01495bf9e
Pierina0410/PierinaYasminPalaciosUlloque
/flotante.py
793
4.21875
4
#1-convertir el entero 300 a flotante x=200 a= float (x) print(a,type(a)) #2_convertir el entero 450 a flotante y=450 a=float(y) print(a,type(a)) #3-convertir entero 450 a flotante z=450 a=float(a) print(a,type(z)) #4-convertir la cadena 500 a flotante B="500" a=float(B) print(a,type(a)) #5-convertir la...
false
7bfa89d3b9a120e66b12658ae499a42a9c5b6e82
TiagoTitericz/chapter2-py4e
/Chapter6/exercise3.py
456
4.125
4
'''Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) ''' def count(word, letter): count = 0 for l in word: if l == let...
true
66fa6baf13c984638065754b49a5e36b299a8e38
TiagoTitericz/chapter2-py4e
/Chapter6/exercise5.py
536
4.5
4
'''Exercise 5: Take the following Python code that stores a string: str = 'X-DSPAM-Confidence:0.8475' Use find and string slicing to extract the portion of the string after the colon character and then use the float function to convert the extracted string into a floating point number.''' #First way str = 'X-DSPAM-Con...
true
e58425d79803ac7c48ddd3f3376cfe660d2b8ad3
TiagoTitericz/chapter2-py4e
/Chapter2/fourth.py
272
4.34375
4
# Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, # and print out the converted temperature. tcelsius = float(input("Enter temp in Celsius: ")) tfahr = (tcelsius * (9 / 5)) + 32 print("Temp in Fahrenheit:", tfahr)
true
9368923c7d8c3c9200b926cb0a759ad33d65b026
DeniZhekova/Python
/uni-Lesson1.py
571
4.15625
4
name = input('What is your name?\n') print ('Hi, %s' , name) age=input("Enter your age: ") print ( "Hmm, " , age , "is a nice age to be...") address = input('What is your address?\n') print ('Probably it is nice to live in %s.' % address ) phoneNumber = input('What is your phone number?\n') print ('Probably I will gi...
false
c51f7510238e8d65b83540fa0e1d975913ad4b60
a19131100/260201084
/lab7/exercise5.py
532
4.21875
4
password = input("Please enter the password: ") upper_count = 0 lower_count = 0 number_count = 0 if len(password)<8: print("Password is not valid") else: for element in password: if element.isdigit(): number_count += 1 else: if element.isalpha(): if element.isupper(): upper_c...
true
931f3f69d1a04c6dea7df3e5d252c235f28f8ddc
chrddav/CSC-121
/CSC121_Lab02_Lab02_Problem2.py
534
4.125
4
Lab1 = float(input('Enter the score for Lab 1: ')) Lab2 = float(input('Enter the score for Lab 2: ')) Lab3 = float(input('Enter the score for Lab 3: ')) Test1= float(input('Enter the score for Test 1: ')) Test2= float(input('Enter the score for Test 2: ')) LabAverage = (Lab1 + Lab2 + Lab3) / 3 TestAverage = (Test1 + Te...
true
13b039ed807ac7a7d98cca0fa3cd9c97c3241cf4
chrddav/CSC-121
/CSC121_Lab12_Lab12P2.py
1,480
4.40625
4
print('Converting US Dollar to a foreign currency') def main(): foreign_currency, dollar_amount = get_user_input() currency_calculator(foreign_currency, dollar_amount) def get_user_input(): """Prompts user to determine which currency they want to convert to and how much money they are converting""" ...
true
dd103c6e61ade3def3f8360a013a6089b8691af6
chrddav/CSC-121
/CSC121_Lab03_Lab03P3.py
410
4.28125
4
X = float(input('Enter first number: ')) Y = float(input('Enter second number: ')) Z = float(input('Enter third number: ')) if X > Y and X > Z: print ('The largest number is: ', X) else: if Y > X and Y > Z: print ('The largest number is: ', Y) else: if Z > X and Z > Y: print ('Th...
false
67b11455fa9442605617caa1e4d8927b0de22daf
raihanrms/py-practice
/sqr_sum-vs-sum_sqr.py
398
4.21875
4
''' The difference between the squared sum and the sum of squared of first n natural numbers ''' def sum_difference(n=2): sum_of_squares = 0 square_of_sum = 0 for num in range(1, n+1): sum_of_squares += num * num square_of_sum += num square_of_sum = square_of_sum ** 2...
true
0eeaf290bdaea1e8b28ca1aefa174acb35151313
TiscoDisco/Python-codes
/Collatz Length.py
925
4.28125
4
# collatz_length (n) produces the number of steps that is required to get to one # using the Collatz method # collatz_length: Num -> Num # required: n != float n has to be positive # Examples: collatz_length(2) => 1 # collatz_length(42) => 8 import math import check def collatz_length (n): ...
true
e52d780ec9dd8967ec05ae1cd5ec39bcc8b70114
TiscoDisco/Python-codes
/Check by Queen.py
2,075
4.125
4
## check_by_queen (queen_pos, king_pos) prduces "Check!!!" if king's position can be ## attacked by the queen. Queen can moving infinite positions horizontally, vertically ## diagonally ## check_by_queen: Str Str -> None ## print (anyof "Check!!!" nothing) ## Required: quee...
true
fabbf7c356274e3deebe666c50592d92610d889c
JetimLee/DI_Bootcamp
/pythonlearning/week1/listsMethods.py
724
4.15625
4
basket = [1, 2, 3, 4, 5] print(len(basket)) basket.append('hello') print(basket) basket.pop() print(basket) basket.insert(3, 'gavin') # here insert takes the index and then the thing you want to insert # list methods do not give a new list, they just change the list # this means you cannot reassign the changed list ...
true
f2004af1ad010067a47f3489ffa5b485bbe918ea
JetimLee/DI_Bootcamp
/pythonlearning/week1/tuples.py
260
4.25
4
# A tuple is like a list, but you cannot modify them - they're immutable my_tuple = (1, 2, 3, 4, 5) # my_tuple[1] = 'z' can't do this print(my_tuple[1]) print(4 in my_tuple) new_tuple = my_tuple[1:2] print(new_tuple) # only has 2 methods - count and index
true
471ce224eae83b54bb1430ee2779d7a02a1d324d
ValentinaKelly/Fundamentos_informatica
/Tp2.py/Ejercicio3.py
436
4.1875
4
#Escribí un programa que dado un número # del 1 al 6, ingresado por teclado, # muestre cuál es el número que está en la # cara opuesta de un dado. Si el número es # menor a 1 y mayor a 6 se debe mostrar un # mensaje indicando que es incorrecto el número ingresado. numero = int(input("ingrese un numero del 1 al 6:...
false
91882bc96685253a25b283c7744a8a43b20981d0
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Udemy/colecoes/tuplas/Exercicios/exe02.py
303
4.3125
4
'''Exercício02 - Escreva um programa que receba do usuário o tamanho de uma tupla e seus respectivos itens''' r = int(input('qual o tamanho da sua tupla+')) tupla = range(r) tuplex = () for i in tupla: a = int(input('Digite um item para a sua tupla\n')) tuplex = tuplex + (a,) print(tuplex)
false
044b162288a9ed08502b6dba05c38fb116111f3b
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Pense_em_Python/cap02/Exercicio_02-2-1.py
394
4.34375
4
# Pratique o uso do interpretador do Python como uma calculadora # 1. O volume de uma esfera com raio r é de 4/3 pi r ^ 3. # Calcule o volume de uma esfera em que o raio é dado pelo usuário # dica: 1 metro cúbico = 1000 litros raio = float(input("digite o valor do raio\n")) volume = (4 * 3.14 * (raio ** 3))/3 print(...
false
8e8eb256191f0f58bb08a672b23337919db8d55f
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap07/Exercicio_07-06.py
689
4.15625
4
""" Escreva um programa que leia três strings. Imprima o resultado da substituição na primeira, dos caracteres da segunda pelos da terceira. """ string1 = input("Digite a primeira String") string2 = input("Digite a segunda String") string3 = input("Digite a terceira String") if len(string2) == len(string3): resul...
false
0095d6b7437be4309a964d7e13e4b323dfc803e4
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap07/Exercicio_07-02.py
329
4.125
4
""" * Escreva um programa que leia duas strings e gere uma terceira com * os caracteres comuns às duas strings lidas. """ string1 = input("Insira a primeira String ") string2 = input("Insira a segunda String ") L =[] for i in string1: for j in string2: if i == j: L.append(i) print(f'{", ".join...
false
097613cf683631893c17cd6fee257791908d046f
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap05/Exercicio_05-22.py
1,051
4.1875
4
""" Escreva um programa que exiba uma lista de opções(menu): adição, subtração, divisão, multiplicação e sair. Imprima a tabuada da operação escolhida. Repita até que a opção saída seja escolhida. """ while True: print("Escolha a opção equivalente a operação desejada") opcao = int(input(''' ADIÇÃO = 1 ...
false
8aa1345b44241869ed8e8a6770e5a187d5e9d607
timetoady/pythonBits1
/cipher_text2.py
306
4.25
4
plain_text = input("Enter a message: ") distance = int(input("Enter the distance value: ")) code = "" for ch in plain_text: ordvalue = ord(ch) cipher_value = ordvalue + distance if cipher_value > ord('~'): cipher_value = ord(' ') + distance - 1 code += chr(cipher_value) print(code)
false
b1c34dfcd2f1c0ccedc19b71f18f56d8868a6543
jeffclough/handy
/patch-cal
2,605
4.34375
4
#!/usr/bin/env python3 import argparse,os,sys from datetime import date,timedelta def month_bounds(year,month): """Return a tuple of two datetime.date instances whose values are the first and last days of the given month.""" first=date(year,month,1) if month==12: last=date(year+1,1,1) else: last=da...
true
b30026b349867c47c5b5b3624b8445847228de29
AbhinavAshish/ctci-python
/Data Structures/solution1_2.py
499
4.28125
4
#Implement a function which reverses a string #Approach use a temporary variable and replace. Solution in n def reverseString (inputStr) : inputString= list(inputStr) for index in range(0,len(inputString)/2): temp = inputString[index] inputString[index]= inputString[len(inputString)-1-index] inputString[len...
true
bb56d7c2c701f8a8526438cc68f97078a9bb2b66
smksevov/Grokking-the-coding-interview
/two pointers/comparing strings containing backspaces.py
1,397
4.3125
4
# Given two strings containing backspaces (identified by the character ‘#’), # check if the two strings are equal. # Example: # Input: str1="xy#z", str2="xzz#" # Output: true # Explanation: After applying backspaces the strings become "xz" and "xz" respectively. # O(M+N) where ‘M’ and ‘N’ are the lengths of the two ...
true
4958f912d9d158a4bec20790b7d608a9c018f68a
smksevov/Grokking-the-coding-interview
/bitwise XOR/two single numbers.py
771
4.15625
4
# In a non-empty array of numbers, every number appears exactly twice except two numbers that appear only once. # Find the two numbers that appear only once. # Example 1: # Input: [1, 4, 2, 1, 3, 5, 6, 2, 3, 5] # Output: [4, 6] # Input: [2, 1, 3, 2] # Output: [1, 3] # O(N) space: O(1) def find_two_single_numbers(ar...
true
d3ea31721c808160ccb18f5b5f7616d0399927ff
Oroko/python-project
/pay.py
428
4.1875
4
# A program to prompt the user for hours and rate per hour to compute gross pay hours = input('Enter Hours:') hourly_rate = input('Enter Hourly Rate:') overtime_hrs = input('Enter Overtime hours:') regular_pay = float(hours) * float(hourly_rate) if float(overtime_hrs)==0: print(regular_pay) elif float(overtime_hrs)>...
true
cda5bd086248bd8cb906e6a7f7af16d0cdc98b2c
bretonne/workbook
/src/Chapter6/ex128.py
1,404
4.53125
5
# Exercise 128: Reverse Lookup # (Solved—40 Lines) # Write a function named reverseLookup that finds all of the keys in a dictionary # that map to a specific value. The function will take the dictionary and the value to # search for as its only parameters. It will return a (possibly empty) list of keys from # the dicti...
true
fb5f09e30b07839d8dc63a0a28eb89ce1372e85c
bretonne/workbook
/src/Chapter6/ex136.py
1,305
4.1875
4
# Exercise 136:Anagrams Again # (48 Lines) # The notion of anagrams can be extended to multiple words. For example, “William # Shakespeare” and “I am a weakish speller” are anagrams when capitalization and # spacing are ignored. # 66 6 Dictionary Exercises # Extend your program from Exercise 135 so that it is able to c...
true
95be2a49b9ada465c8495de39c0149eb490d6699
covcom/122COM_sorting_algorithms
/lab_sorting.py
2,636
4.15625
4
#!/usr/bin/python3 def bubble_sort( sequence ): # COMPLETE ME - Green task return sequence def selection_sort( sequence ): # COMPLETE ME - Yellow task return sequence def quick_sort( sequence ): # COMPLETE ME - Yellow task return sequence def quick_sort_inplace( sequence, start=None, end=...
true
30718fec059ba9171c0a3118afe7035976d9dd48
pythonmentor/johann-session-20190320
/input.py
402
4.1875
4
def int_input(message, min, max): """Asks user to enter an integer between min and max.""" while True: n = input(message) if n.isdigit(): n = int(n) else: continue if min <= n <= max: return n user_input = int_input("Entrez un nombre...
false
61d5bc282770b82855ad904bc889e1eb64d09087
pranayvwork/mypy
/stringsDemo.py
775
4.25
4
message = 'My Wolrd' print(message) #apostrophe myString = "Cat's world" print(myString) #multi line string literal longString = """This is a multi line string spanning to the second line. """ print(longString) #find the length of string print(len(myString)) #upper or lower print(myString[6:].upper()) #count method pr...
true
53d6b7d3dfd2f467ac972b119af3fbd40a4e64db
BhagyashreeKarale/more-exercise
/cipher2.0.py
1,951
4.1875
4
# Cipher 2.0 # Encrypt function ek message input leta hai aur firr uss message ko encrypt karta hai. # Encrypt karne ke liye yeh har character ko 3 character aage wale character se change kar deta hai. # Aisa karne ke liye yeh har character ki ascii value ko 3 se increase kar deta hai. # Jaise: v ki ASCII value 118 ...
false
592c5a195ee4892d0f59525431184e53b40c7d54
Muhammad-Salman-Hassan/Python_Basic
/DSA_2.py
2,315
4.1875
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Structure to store node pair onto stack class snode: def __init__(self, l, r): self.l = l self.r = r ''' Helper functio...
true
16526d38dbdc2ee31a40de3dbdf48362aac10d36
gokadroid/Python3Examples
/applesOranges.py
2,022
4.1875
4
#!/bin/python3 import math import os import random import re import sys # Complete the countApplesAndOranges function below. def countApplesAndOranges(s, t, a, b, apples, oranges): applesCount=0 orangeCount=0 for i in range(0,len(apples)): if apples[i] > 0 and apples[i]+a >= s and apples[i]+a<=t: ...
false
ac18bb5814d50470d24a021c012c39f6cce5e813
judecafranca/PYTHON
/PALINDROME.py
318
4.3125
4
def isPalindrome(): string = input('Enter a string: ') string1 = string[::-1] if string[0] == string[(len(string)-1)]\ and string[1:(len(string)-2)] == string1[1:(len(string)-2)]: print('It is a palindrome') else: print('It is not a palindrome') isPalindrome()
true
48a33d647557269a36e6e6508f2921bba66f0b76
arnjr1986/Curso-Python-3
/ex_039_Alistamento.py
795
4.15625
4
"""LER O ANO DE NASC. DE UM JOVEM E INFORMAR: - SE AINDA VAI SE ALISTAR AO SERVIÇO MILITAR - SE É A HORA DE SE ALISTAR - SE JA PASSOU O TEMPO DE ALISTAMENTO -MOSTRAR QUANTO TEMPO FALTA OU QUE PASSOU DO PRAZO""" from datetime import date nasc = int(input('Digite o ano de Nascimento: ')) alist = int(18) ano ...
false
da112b4679ad6e09910ecd900df4d153a4f4b7a2
arnjr1986/Curso-Python-3
/ex_026_conta_Posiçao.py
536
4.25
4
"""Ler uma frase e mostrar quantas vezes aparece a letra 'a' em que posição ela aparece a primeira vez e em qual posição ela aparece pela ultima vez""" frase = str(input('Digite uma frase: ')).upper().strip()#Maiusculas e sem espaços print('A letra *A* aparece {} vezes na frase.'.format(frase.count('A')))#count c...
false
62697abe7952f1da294fa61d81e77fc3b08721c9
arnjr1986/Curso-Python-3
/ex_009_tab.py
563
4.15625
4
#Tabuada num = int(input('Digite um numero para ver sua tabuada: ')) print('-'*12) print('{} x {:2} = {}'.format(num, 1,num*1)) print('{} x {:2} = {}'.format(num, 2,num*2)) print('{} x {:2} = {}'.format(num, 3,num*3)) print('{} x {:2} = {}'.format(num, 4,num*4)) print('{} x {:2} = {}'.format(num, 5,num*5)) ...
false
ef431b986c659ee6943577f8606b75db0ca1e8d5
leonardotdleal/python-basic-course
/primitive-variables/primitive-variables.py
428
4.15625
4
# PRIMITIVE VARIABLES IN PYTHON # # String name = 'Leonardo Leal' # Integer age = 25 # Float height = 1.68 # Boolean student = True print(name) print(age) print(height) print(student) # None (is similar to null in others languages) working = None print(working) # OPERATIONS # new_age = age + 2 name_and_city = ...
true
a2b927ab8854238ee6c16fbcc6dd94f6a6869c27
krishnapratapmishra/PythonScripts
/bitwise.py
333
4.125
4
#Manipulating Bits """ | OR & AND ~ NOT ^ XOR << Shift Left >> Shift Right """ #Swap the values without third variable a=10 b=5 print('a =' ,a ,'\tb =',b) #1010 ^ 0101 = 1111 (decimal 15) a=a^b #1111 ^ 0101 = 1010 (decimal 10) b= a^b #1111 ^ 1010 = 0101 a=a^b print('a=',a,'\...
false