blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
45f5407c770e494c7d9be2fbcbf1802e56c74e21 | rohan-krishna/dsapractice | /arrays/array_rotate.py | 533 | 4.125 | 4 | # for the sake of simplicity, we'll use python list
# this is also known as Left Shifting of Arrays
def rotateArray(arr, d):
# arr = the input array
# d = number of rotations
shift_elements = arr[0:d]
arr[:d] = []
arr.extend(shift_elements)
return arr
if __name__ == "__main__":
print("How m... | true |
b6587aace2006e8cca1e4e546b3bc4bb716fcfa0 | federicodiazgerstner/sd_excercises_uade | /Ejercicio 4.07.py | 542 | 4.21875 | 4 | #Realizar un programa para ingresar desde el teclado un conjunto de números y
#mostrar por pantalla el menor y el mayor de ellos. Finalizar la lectura de datos
#con un valor -1.
n = int(input("Insertar un número, o -1 para terminar: "))
menor = n
mayor = n
while n != -1:
if n > mayor:
mayor = n
elif n ... | false |
11d53956ee5844db459788f17b93d07b8594243d | bhargav-s-271100/Python-Programs | /Calculator using OOPS concept.py | 1,081 | 4.1875 | 4 | class calculator:
def __init__(self,a,b):
self.c=a
self.d=b
def add(self):
return self.c+self.d
def subtract(self):
if self.c>self.d:
self.c-self.d
else:
return self.c-self.d
def multiply(self):
return self.c*self.d
... | false |
bba98a339cc3fe159b5db7a6979f37a1e6467eee | shridharkute/sk_learn_practice | /recursion.py | 668 | 4.375 | 4 | #!/usr/bin/python3
'''
This is recursion example.
recursion is method to call itself while running.
Below is the example which will create addition till we get 1.
Eg.
If we below funcation as "tri_resolution(6)" the result will be
Rcursion example result
1 1
2 3
3 6
4 10
5 15
6 21
But in the background it will execu... | true |
521b61d372e351a005221c1919dc4bacf070fe51 | shridharkute/sk_learn_practice | /if_else.py | 432 | 4.15625 | 4 | #/usr/bin/python3
a = int(input("Please type number :"))
b = int(input("Please type number :"))
if a < b:
print("%d is smaller than %d" % (a,b))
elif a < b:
print("%d is grater than %d" % (a,b))
else:
print("%d is equal to %d" %(a,b))
if a < b or a == b:
print("%d is smaller or equal to %d" %(a,b))
... | false |
600409d5897e5a6a2a8fa5900a8ca197abf294f7 | DAVIDCRUZ0202/cs-module-project-recursive-sorting | /src/searching/searching.py | 798 | 4.34375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
if len(arr) == 0:
return -1
low = start
high = end
middle = (low+high)//2
if arr[middle] == target:
return middle
if arr[middle] > target:
return binary_search(ar... | true |
1e4ecc5c66f4f79c0f912313acd769edb3a92008 | harshal-jain/Python_Core | /22-Lists.py | 1,980 | 4.375 | 4 | list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
"""
print ("list1[0]: ", list1[0]) #Offsets start at zero
print ("list2[1:5]: ", list2[1:5]) #Slicing fetches sections
print ("list1[-2]: ", list1[-2]) #Negative: count from the right
print ("Value available at index 2 : ", list1[2])
list1[... | true |
71356cbfce0df685f7b02f7b719289bd3b395b21 | Sarayin/Ejercicios-de-trabajo | /ejercicio 12.py | 559 | 4.125 | 4 | '''Escribir una función que, dado un string,
retorne la longitud de la última palabra.
Se considera que las palabras están separadas
por uno o más espacios. También podría haber espacios
al principio o al final del string pasado por parámetro.'''
def lenramiro(frase):
if len(frase)==0:
return 0
... | false |
b253f828fc56c2f9e7148e13ae2a910c542f1249 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 05/ProgrammingExercises/03_budget_analysis.py | 1,540 | 4.40625 | 4 | # Write a program that asks the user to enter the amount that they have
# budgeted for a month. A loop should then prompt the user to enter each of
# their expenses for the month, and keep a running total. When the loop
# finishes, the program should display the amount that the user is over
# or under budget.
def budg... | true |
88cfb1d6b2746e689d6a661caa34e5545f044670 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 04/ProgrammingExercises/09_shipping_charges.py | 1,098 | 4.4375 | 4 | # The Fast Freight Shipping Company charges the following rates:
#
# Weight of Package Rate per Pound
# 2 pounds or less $1.10
# Over 2 pounds but not more than 6 pounds $2.20
# Over 6 pounds but not more than 10 pounds $3.70
#... | true |
4d24d83ec69531dd864ef55ed900a6d154589fd8 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 03/ProgrammingExercise/04_automobile_costs.py | 1,248 | 4.34375 | 4 | # Write a program that asks the user to enter the monthly costs for the
# following expenses incurred from operating his or her automobile: loan
# payment, insurance, gas, oil, tires, and maintenance. The program should
# then display the total monthly cost of these expenses, and the total
# annual cost of these expens... | true |
36e179b5db4afaf4b7bc2b6a51f0a81735ac2002 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 06/ProgrammingExercises/01_feet_to_inches.py | 521 | 4.40625 | 4 | # One foot equals 12 inches. Write a function named feet_to_inches that
# accepts a number of feet as an argument, and returns the number of inches
# in that many feet. Use the function in a program that prompts the user
# to enter a number of feet and then displays the number of inches in that
# many feet.
def main()... | true |
a8bf3cc39005180b6d3b2d18a751c43f3665ec23 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 07/ProgrammingExercises/09_exception_handling.py | 348 | 4.125 | 4 | # Modify the program that you wrote for Exercise 6 so it handles the following
# exceptions:
# • It should handle any IOError exceptions that are raised when the file is
# opened and data is read from it.
# • It should handle any ValueError exceptions that are raised when the items
# that are read from the file are... | true |
3d4cba89be0858b757da7c59a4845ab4360d28d3 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 06/ProgrammingExercises/05_kinetic_energy.py | 1,110 | 4.40625 | 4 | # In physics, an object that is in motion is said to have kinetic energy (KE).
# The following formula can be used to determine a moving object’s kinetic
# energy:
#
# KE = (1/2) * m * v^2
#
# The variables in the formula are as follows: KE is the kinetic energy in
# joules, m is the object’s mass in kilogr... | true |
8cccedbab97b4439c53bbec5f443011066947897 | kescalante01/learning-python | /Address.py | 867 | 4.28125 | 4 | #Use raw_input() to allow a user to type an address
#If that address contains a quadrant (NW, NE, SE, SW), then add it to that quadrant's list.
#Allow user to enter 3 addresses; after three, print the length and contents of each list.
ne_adds = []
nw_adds = []
se_adds = []
sw_adds = []
address1 = raw_input("Whats y... | true |
15e748a72d65e156856ef84264c8700e9e7e3c83 | uciharis/Udemy-dletorey | /Python Programming Masterclass/Python/Squences/joining_things.py | 228 | 4.125 | 4 | flowers = [
"Daffodil",
"Crocus",
"Iris",
"Tulip",
"Rose",
"Lily",
]
# for flower in flowers:
# print(flower)
separator = " | "
output = separator.join(flowers)
print(output)
print(",".join(flowers)) | false |
6d72e4e2ce4447de1dfee99def28204c089f7faf | riteshsingh1/learn-python | /string_function.py | 406 | 4.34375 | 4 | string="Why This Kolaveri DI"
# 1
# len(string)
# This function returns length of string
print(len(string))
# 2
# In Python Every String is Array
string = "Hello There"
print(string[6])
# 3
# index()
# Returns index of specific character / Word - First Occurance
string="Python is better than PHP."
print(string.inde... | true |
6b8442b9cd22aa2eeb37966d42ca6511f3ba6c17 | antoninabondarchuk/algorithms_and_data_structures | /sorting/merge_sort.py | 797 | 4.125 | 4 | def merge_sort(array):
if len(array) < 2:
return array
sorted_array = []
middle = int(len(array) / 2)
left = merge_sort(array[:middle])
right = merge_sort(array[middle:])
left_i = 0
right_i = 0
while left_i < len(left) and right_i < len(right):
if left[left_i] > right[rig... | true |
12ee12d7d101ed158bae6079f14e8a6360c424f6 | elicecheng/Python-Practice-Code | /Exercise1.py | 359 | 4.15625 | 4 | #Exercise 1
#Asks the user to enter their name and age.
#Print out a message addressed to them that
#tells them the year that they will turn 100 years old.
import datetime
name = input("What is your name?")
age = int(input("How old are you?"))
now = datetime.datetime.now()
year = (now.year - age) + 100
print(name, ... | true |
cb04890ea51898c5c225686f982e77da4dc71535 | playwithbear/Casino-Games | /Roulette Basic.py | 1,488 | 4.28125 | 4 | # Basic Roulette Mechanics
#
# Key attributes:
# 1. Provide a player with a balance
# 2. Take a player bet
# 3. 'Spin' Roulette wheel
# 4. Return result to player and update balance if necessary with winnings
#
# NB. This roulette generator only assumes a bet on one of the evens i.e. red of black to test a gam... | true |
c413add161722e8efad1b4319463ede4f5a3aff8 | ramsundaravel/PythonBeyondBasics | /999_Misc/004_generators.py | 1,140 | 4.375 | 4 | # Generators -
# Regular function returns all the values at a time and goes off
# but generator provides one value at a time and waits for next value to get off. function will remain live
# it basically yields or stops for next call
# basically not returning all values together. returning one value at a time
def gene... | true |
d70c7e14cb9974a1320850eb1e70fa2fb1e14dd7 | AhmedElatreby/python_basic | /while_loop.py | 2,392 | 4.4375 | 4 | """
# While Loop
A while loop allows code to be repeated an unknown number of times as long as a condition is being met.
=======================================================================================================
# For Loop
A for loop allows code to be repeated known number of loops/ iterations
"""
# impo... | true |
4280063ba51d897bdb1049d6a1a84c6625ed0a39 | igor-kurchatov/python-tasks | /Warmup1/pos_neg/pos_neg_run.py | 355 | 4.1875 | 4 | #################################
# Task 8 - implementation
# Desription: Given 2 int values, return True if one is negative and one is positive.
# Except if the parameter "negative" is True, then return True only if both are negative.
# Author : Igor Kurchatov 5/12/2016
#################################
from ... | true |
0fe469e04d72b5e225fdc4279f6f4c9542031644 | AmeyMankar/PracticePython | /Exercise2.py | 462 | 4.28125 | 4 | # Let us find the sum of several numbers (more than two). It will be useful to do this in a loop.
#http://www.codeabbey.com/index/task_view/sum-in-loop
user_input = []
sum_of_numbers = 0
choice=1
while choice != 2:
user_input.append(int(input("Please enter your number: \t")))
choice = int(input("Do you want to add... | true |
edbc80e91c8a9ad244bee62bcfe3809a3dce876a | ethanpierce/DrZhao | /LinkedList/unitTestLinkedList.py | 644 | 4.15625 | 4 | from linkedlist import LinkedList
def main():
#Create list of names
listOfNames = { "Tom", "Harry","Susan","Ethan","Willy","Shaina"}
#Create linkedlist object
testinglist = LinkedList()
#Test insertion method
for name in listOfNames:
testinglist.insert(name)
#Test size of list
... | true |
97fc123c1a6beb45aa2893c0c4a8d21bfc41b174 | dvcolin/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 2,387 | 4.1875 | 4 | class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.nex... | true |
1041fe53fa1dbc0a91f0602f20530a4608656069 | tadeograch/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 483 | 4.3125 | 4 | #!/usr/bin/python3
"""
0. Integers addition
A function that adds 2 integers
add_integer(a, b)
"""
def add_integer(a, b=98):
"""
Function that add two integers
"""
if not type(a) is int and not type(a) is float:
raise TypeError("a must be an integer")
if not type(b) is int and not type(b) ... | true |
0725747b9015941bac5f87ff3c5a9372ab9fd5cc | uoshvis/py-data-structures-and-algorithms | /sorting_and_selection/selection.py | 1,527 | 4.15625 | 4 | # An example of prune-and-search design pattern
import random
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False ... | true |
ac1dbc3d5be3fcf1cb6ec271833e8a19af1f6af6 | abmport/Python | /1Semestre/inverter_numero.py | 265 | 4.15625 | 4 | num = int(input("Escolha um número de três dígitos para o invertermos: "))
print("O número escolhido é: ",num)
p1=num%10
p2=num//10
p2=p2*11
p2=p2%10
p3=p1+p2*10
p3=num-p3
p3=p3//100
print("O número invertido é: ",p1,p2,p3)
input ()
| false |
0ae6074efd9a9b393439a72b9f596d4baf09f7c8 | v13aer14ls/exercism | /salao_de_beleza.py | 1,538 | 4.21875 | 4 | #!/bin/python2/env
#Guilherme Amaral
#Mais um exercicio daqueles
hairstyles = ["bouffant", "pixie", "dreadlocks", "crew", "bowl", "bob", "mohawk", "flattop"]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2, 1]
#1. Create a variable total_price, and set it to 0.
total_price = 0
#2. I... | true |
ff01b081c831b0593ebb3722ee47ca04b2406991 | Praneeth313/Python | /Loops.py | 1,363 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 6 23:02:40 2021
@author: Lenovo
Assignment 5: Basic Loop
Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number and for the multiples of five
print "Buzz".
For numbers which are multiples of ... | true |
9018be0092cebcda903279b87fcdb9e78a8c79fb | akshat12000/Python-Run-And-Learn-Series | /Codes/98) list_comprehension_in_nested_list.py | 389 | 4.53125 | 5 | # List comprehension in nested list
# We want the list --> [[1,2,3], [1,2,3], [1,2,3]]
# Method 1)--> without list comprehension
l=[]
for i in range(3):
p=[]
for j in range(1,4):
p.append(j)
l.append(p)
print(l)
# Method 2)--> with list comprehension
l1=[[i for i in range(1,4)] for _ in... | true |
8f9ef1a6b1b42b511331646021caa6a7e9b298eb | akshat12000/Python-Run-And-Learn-Series | /Codes/104) args_as_argument.py | 296 | 4.28125 | 4 | def multiply(*args):
mul=1
print(f"Elements in args are {args}")
for i in args:
mul*=i
return mul
l=[1,2,3]
t=(1,2,3)
print(multiply(l)) # OUTPUT: [1,2,3]
print(multiply(*l)) # OUTPUT: 6 , here all the elements of the list will get unpacked
print(multiply(*t))
| true |
3790cba15164331e7f6d5ff4635b4190729526b7 | akshat12000/Python-Run-And-Learn-Series | /Codes/86) fromkeys_get_copy_clear.py | 1,523 | 4.25 | 4 | # fromkeys
d=dict.fromkeys(['name','age','height'],'unknown')
# this will create dictionary like this {'name':'unknown','age':'unknown','height':'unknown'}
print(d)
d1=dict.fromkeys(('name','age','height'),'unknown')
print(d1) # same as dictionary d
d2=dict.fromkeys("ABC",'unknown')
# this will create dictionary... | false |
3513342cbbba1aee157d3c27dce319c2eef4bcbc | akshat12000/Python-Run-And-Learn-Series | /Codes/100) dictionary_comprehension_with_if_else.py | 446 | 4.40625 | 4 | # Dictionary Comprehension with if else statements
# we have to create a dictionary in such a way that when key is odd then it's value will be 'odd' and same goes with even keys
# Method 1)--> without dictionary comprehension
d={}
for i in range(1,11):
if i%2:
d[i]='odd'
else:
d[i]='ev... | false |
9065b40cebe0cd5dbe74649d0ed526ac17b4e9d2 | akshat12000/Python-Run-And-Learn-Series | /Codes/46) step_in_range.py | 245 | 4.15625 | 4 | for i in range(1,11): # i will increment by 1
print(i)
print() # this automatically create a newline
for i in range(1,11,2): # i will increment by 2
print(i)
print()
for i in range(10,0,-1): # i will decrement by 1
print(i)
| false |
4cd283528b382fab7369630629c6f46d0993590c | akshat12000/Python-Run-And-Learn-Series | /Codes/134) generators_intro.py | 569 | 4.65625 | 5 | # generators are iterators
# iterators vs iterables
l=[1,2,3,4] # iterable
l1=map(lambda a:a**2,l) # iterator
# We can use loops to iterate through both iterables and iterators!!
li=[1,2,3,4,5]
# memory --- [1,2,3,4,5], list, it will store as a chunk of memory!!
# memory --- (1)->(2)->(3)->(4)->(5), genera... | true |
82703ca80bd6745995fd86e4de8a7ae6e978efc5 | akshat12000/Python-Run-And-Learn-Series | /Codes/137) generators_comprehension.py | 444 | 4.21875 | 4 | # Genrators comprehension
square=[i**2 for i in range(1,11)] # list comprehension
print(square)
square1=(i**2 for i in range(1,11)) # generator comprehension
print(square1)
for i in square1:
print(i)
for i in square1:
print(i)
# Notice that it will print only once!!
square2=(i**2 for i in r... | true |
5e5bcdee2c5fd58e9532872a8c4403e8cf47d49f | akshat12000/Python-Run-And-Learn-Series | /Codes/22) string_methods2.py | 298 | 4.25 | 4 | string="He is good in sport and he is also good in programming"
# 1. replace() method
print(string.replace(" ","_"))
print(string.replace("is","was",1))
print(string.replace("is","was",2))
# 2. find() method
print(string.find("is"))
print(string.find("also"))
print(string.find("is",5))
| true |
7613ae3e2b62c471be17440d5ce22679b7d61d0d | akshat12000/Python-Run-And-Learn-Series | /Codes/119) any_all_practice.py | 421 | 4.1875 | 4 | # Write a funtion which contains many values as arguments and return sum of of them only if all of them are either int or float
def my_sum(*args):
if all([type(i)== int or type(i)== float for i in args]):
total=0
for i in args:
total+=i
return total
else:
r... | true |
ea0f61c783a093d998866e3b7843daa2cbd01e4a | akshat12000/Python-Run-And-Learn-Series | /Codes/126) closure_practice.py | 399 | 4.125 | 4 | # Function returning function (closure or first class functions) practice
def to_power(x):
def calc_power(n):
return n**x
return calc_power
cube=to_power(3) # cube will be the calc_power function with x=3
square=to_power(2) # square will be the calc_power function with x=2
print(cube(int(input... | true |
7232967214c29480b14d437eba3a42e5a2b23a5f | akshat12000/Python-Run-And-Learn-Series | /Codes/52) greatest_among_three.py | 365 | 4.125 | 4 | # Write a function which takes three numbers as an argument and returns the greatest among them
def great3(a,b,c):
if a>b:
if a>c:
return a
return c
else:
if b>c:
return b
return c
x,y,z=input("Enter any three numbers: ").split()
print(f"Greates... | true |
ba1551611784af483ea8341a3fdbccc5a5d8b235 | akshat12000/Python-Run-And-Learn-Series | /Codes/135) first_generator.py | 932 | 4.5625 | 5 | # Create your first generator with generator function
# Method 1) --> generator function
# Method 2) --> generator comprehension
# Write a function which takes an integer as an argument and prints all the numbers from 1 to n
def nums(n):
for i in range(1,n+1):
print(i)
nums(5)
def nums1(n):
... | true |
fd70a0a0c399b7ea099ad0df2069b1b861f7ac6d | akshat12000/Python-Run-And-Learn-Series | /Codes/58) intro_to_lists.py | 702 | 4.3125 | 4 | # A list is a collection of data
numbers=[1,2,3,4,5] # list declaration syntax and it is list of integers
print(numbers)
words=["word1",'word2',"word3"] # list of strings as you can see we can use both '' and ""
print(words)
mixed=[1,2,3,4,"Five",'Six',7.0,None] # Here the list contains integers, strings, float... | true |
f6ff85bebf05c377052e30a8e7c7e7ea9a7ec1a9 | pedrohs86/Python_introduction | /hello.py | 908 | 4.1875 | 4 | #-*- coding: utf-8 -*-
# coment test
mensagem = "eae mano"
# print ("Hello world!")
# print ('Olá mundo!')
"""
comentario teste
"""
# print ( 2**2 ) #potência
# print ( 10%3 ) #Resto da divisão
# print (mensagem)
var1 = 1
var2 = 1.1
var3 = 'string'
var4 = True
x = 2
y = 10
s = x
# print (x == y)
# print (x < y... | false |
f803ca25ed0928e6c2786d99f26a2f69b5c69dd2 | indradevg/mypython | /cbt_practice/for1.py | 609 | 4.34375 | 4 | #!/usr/bin/python3.4
i=10
print("i value before : the loop: ", i)
for i in range(5):
print(i)
'''
The for loops work in such a way that leave's behind the i value
to the end of the loop and re-assigns the value to i which was initializd as 10 in our case
'''
print("i value after the loop: ", i)
'''
The below line ... | true |
b6ea51a48ca6e63a766de59acfcd8f7a9fe58245 | danamur/CursoPython | /Sentencias Condicionales/SentenciaCondicionalesSimples.py | 556 | 4.125 | 4 | print("Sistema para cualcular el promerdio de un alumno")
nombre = input("Para comenzar, ¿Cual es tu nombre?: ")
matematicas = float(input(nombre + " ¿Cual es tu calificacion en matematicas?: "))
quimica = float(input(nombre + " ¿Cual es tu calificacion en quimica?: "))
lenguaje = float(input(nombre + "¿Cual es t... | false |
e81d068021e2eb248346daf25096163191768be6 | danamur/CursoPython | /Bucles/BucleWhile - RaizCuadrada.py | 689 | 4.15625 | 4 | import math
print("-------------------------------------------")
print("| Programa de cálculo de la raíz cuadrada |")
print("-------------------------------------------\n")
numero = int(input("Introduce un número por favor: \n"))
intentos = 0
while numero < 0:
print("No se puede hallar la raíz de un ... | false |
0c28d1d950dbbdf74ec827583dd7c46c331bc4b0 | thanasissot/myPyFuncs | /fibonacci.py | 481 | 4.1875 | 4 | # cached fibonacci
cache = dict()
def memFib(n):
"""Stores result in cache dictionary to be used at function
definition time, making it faster than first caching then
using it again for faster results
"""
if n in cache:
return cache[n]
else:
if n == 0:
return 0
... | true |
d3d4fe44bb69702cae5869b55e61b71b77a75025 | Shivansh-Commits/Basic-Programming-Using-Python | /Program(3).py | 361 | 4.1875 | 4 | #Q) Print 'Hello' if the no. is only divisible by 3
#Print 'Python' if the no. is only divisible by 5
#print 'Hello Python' if the no. is divisible by both 3&5
for i in range(1,51):
if(i%3==0 and i%5==0):
print("Hello Python")
elif(i%3==0):
print("Hello")
elif(i%5==0):
print... | false |
0281e0caca322b8701acc8610b38a0bb8f4bd039 | JiaLee0707/2019-Python | /parking07-06.py | 1,075 | 4.125 | 4 | ## 변수 선언 부분
parking = []
top, carName, outCar=0, "A", ""
select = 9
## 메인(main) 코드 부분
while(select != 3) :
select=int(input("<1> 자동차 넣기 <2> 자동차 빼기 <3> 끝 : "))
if(select == 1):
if(top>=5):
print("주차장이 꽉 차서 못들어감")
else:
parking.append(carName)
print("%s 자동차 들어... | false |
e58f837ab1a161e23b8af68e15cb9095961ab52c | Moglten/Nanodegree-Data-structure-and-Algorithm-Udacity | /Data Structure/queue/reverse_queue.py | 329 | 4.21875 | 4 | def reverse_queue(queue):
"""
Given a Queue to reverse its elements
Args:
queue : queue gonna reversed
Returns:
queue : Reversed Queue
"""
stack = Stack()
while not queue.is_empty():
stack.push(queue.dequeue())
while not stack.is_empty():
queue.enqueue(stac... | true |
38b7b5030e6d39b2adaabe73e14b40e637a14e3b | feleck/edX6001x | /lec6_problem2.py | 623 | 4.1875 | 4 | test = ('I', 'am', 'a', 'test', 'tuple')
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
result = ()
i = 0
while i < len(aTup):
if i % 2 == 0:
result += (aTup[i:i+1])
i+= 1
#print result
return result
# ... | true |
8781f9f96a111b4edb2772afc5bee20e7861a881 | deadsquirrel/courseralessons | /test14.1mod.py | 1,059 | 4.15625 | 4 | ''' Extracting Data from JSON
In this assignment you will write a Python program somewhat similar to
http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL,
read the JSON data from that URL using urllib and then parse and extract
the comment counts from the JSON data, compute the sum of the number... | true |
97caae6c7fcaed2f8c0442dec8166a3c26b7caf5 | pduncan08/Python_Class | /Wk3_Sec4_Ex3a.py | 704 | 4.28125 | 4 | # Lists - Exercise 3
# Python indexing starts at 0. This will come up whenever you
# have items in a list format, so always remember to ask for
# 1 less than whatt you want!
John_Skills=["Python", "Communicateon", "Low Salary Request", 1000]
print(John_Skills)
Applicants=[["John", "Python"],["Geoff", "Doesn't Know P... | true |
5394d2d8237802a930e1c43b1fffc5fb1f2a1090 | non26/testing_buitIn_module | /superMethod/test1_superMethod.py | 603 | 4.53125 | 5 | """
this super method example here takes the argument of two,
first is the subClass and the second is the instance of that subClass
so that the the subClass' instance can use the superClass' attributes
STRUCTURE:
super(subclass, instance)
"""
class Rectangle(object):
def __init__(self, width... | true |
f31816fec154d08f18eaa849cbd8d8ca3920bb2e | SoyUnaFuente/c3e3 | /main.py | 571 | 4.21875 | 4 |
score = int(input("Enter your score: "))
# if score in range(1, 51):
# print (f"There is no prize for {score}")
if 1 <= score <=50:
print (f"There is no prize for {score}")
elif 51 <= score <=150:
medal = "Bronze"
print(f"Congratulations, you won the {medal} medal for having {score} points ")
elif 1... | true |
bcfbb2aeb996835a5d1d567c331b5a926b2c4fd9 | AllanRPereira/Simple-Color-Terminal | /cursor.py | 2,803 | 4.15625 | 4 | """
Função: Definir funções para realização de operações com o cursor, usando
o terminal
Autor: Állan Rocha
"""
import sys
ANSI = "\033["
def cursor_move(direction="UP", lines=1):
"""
Move o cursor de acordo com a direção e quantidade de linhas/colunas
desejadas
"""
directions = {"UP":"A", "DOWN":... | false |
3223ced97083d48d879451264165dc100c62d7d2 | Hugocorreaa/Python | /Curso em Vídeo/Desafios/Mundo 2/ex071 - Simulador de Caixa Eletrônico.py | 1,137 | 4.21875 | 4 | '''
Crie um programa que simule o funcionamento de um caixa eletrônico. No início,
pergunte ao usuário qual será o valor a ser sacado (número inteiro) e o programa
vai informar quantas cédulas de cada valor serão entregues.
OBS. Considere que o caixa possuí cédulas de R$50, R$20, R$10 e R$1.
'''
print('=' * 30)
pri... | false |
d0773128c4e95c086f4c21eb0e93bda36083cbac | Hugocorreaa/Python | /Curso em Vídeo/Desafios/Mundo 2/ex036 - Aprovando Empréstimo.py | 1,447 | 4.1875 | 4 | """ Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
O programa vai perguntar o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
Calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário ou então o empréstimo será negado.
"""
from time... | false |
c0c7f5440c3b9ca7a783ae2b21c479ae022d9b2b | Hugocorreaa/Python | /Curso em Vídeo/Desafios/Mundo 1/ex028.py | 695 | 4.1875 | 4 | # Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar desco
#brir qual foi o número escolhido pelo computador.
# O programa deverá escrever na tela se o usuário venceu ou perdeu.
from time import sleep
from random import randrange
random = randrange(6)
prin... | false |
5c133a38fdca5f32432dbe164820ed62e249615c | cosmos-sajal/python_design_patterns | /creational/factory_pattern.py | 1,035 | 4.21875 | 4 | # https://dzone.com/articles/strategy-vs-factory-design-pattern-in-java
# https://stackoverflow.com/questions/616796/what-is-the-difference-between-factory-and-strategy-patterns
# https://stackoverflow.com/questions/2386125/real-world-examples-of-factory-method-pattern
from abc import ABCMeta, abstractmethod
class D... | true |
dd5600b48a73fcc8118a305826d704766463260d | danielacevedo20/introprogramacion | /Clases/Excepciones/ejemplo.py | 1,029 | 4.15625 | 4 | isCorrectInfo = False
while(isCorrectInfo == False):
try:
edad = int (input("Ingrese su edad: "))
isCorrectInfo = True
except ValueError:
print("Ingresaste un dato erroneo")
nombreArchivo = input("Ingrese el nombre del archivo que desdea encontrar: ")
try:
archivo = open (nombreArc... | false |
92d46625f1bb1bfe6e6a2a359af18f50770d540b | potnik/sea_code_club | /code/python/rock-paper-scissors/rock-paper-scissors-commented.py | 2,585 | 4.5 | 4 | #!/bin/python3
# The previous line looks like a comment, but is known as a shebang
# it must be the first line of the file. It tells the computer that
# this is a python script and to use python3 found in the /bin folder
from random import randint
# From the python module called random, import the function randint
#... | true |
af908716f27a9ff46e623c883300cdcd7464d994 | pranaychandekar/dsa | /src/basic_maths/prime_or_no_prime.py | 1,199 | 4.3125 | 4 | import time
class PrimeOrNot:
"""
This class is a python implementation of the problem discussed in this
video by mycodeschool - https://www.youtube.com/watch?v=7VPA-HjjUmU
:Authors: pranaychandekar
"""
@staticmethod
def is_prime(number: int):
"""
This method tells whethe... | true |
db56d84911eac1cae9be782fd2ebb047c625fce2 | pranaychandekar/dsa | /src/sorting/bubble_sort.py | 1,488 | 4.46875 | 4 | import time
class BubbleSort:
"""
This class is a python implementation of the problem discussed in this
video by mycodeschool - https://www.youtube.com/watch?v=Jdtq5uKz-w4
:Authors: pranaychandekar
"""
@staticmethod
def bubble_sort(unsorted_list: list):
"""
This method s... | true |
7e2f82c44c8df1de42f1026dcc52ecef804d9506 | pranaychandekar/dsa | /src/basic_maths/prime_factors.py | 1,324 | 4.25 | 4 | import time
class PrimeFactors:
"""
This class is a python implementation of the problem discussed in this
video by mycodeschool - https://www.youtube.com/watch?v=6PDtgHhpCHo
:Authors: pranaychandekar
"""
@staticmethod
def get_all_prime_factors(number: int):
"""
This meth... | true |
a241a2db9e5561e428bfe0aa090059da338da4b9 | anastasia1002/practise1 | /21.py | 252 | 4.125 | 4 | #cosx+cos^2x+...cos^nx
import math
n = int(input("натуральне число"))
x = float(input("дійсне число"))
sum = 0
i = math.cos(x)
while i <= math.cos(x) ** n:
sum = i + math.cos(x)
else:
sum = math.cos(x) ** n
print(sum)
| false |
985ee849a95356776888f8b0ea7f2a69bfcd56be | karthikwebdev/oops-infytq-prep | /queue.py | 1,087 | 4.125 | 4 | class Queue:
def __init__(self,size):
self.list = []
self.front = -1
self.rear = -1
self.size = size
def enque(self,val):
if(self.size-1 == self.rear):
print("queue is full")
elif(self.rear == -1 and self.front == -1):
self.list.append(val)... | false |
2910d6bc150cfb5cfc60e5b31f9910d546027eda | karthikwebdev/oops-infytq-prep | /2-feb.py | 1,943 | 4.375 | 4 | #strings
# str = "karthi"
# print(str[0])
# print(str[-1])
# print(str[-2:-5:-1])
# print(str[-2:-5:-1]+str[1:4])
#str[2] = "p" -- we cannot update string it gives error
#del str[2] -- this also gives error we cannot delete string
#print("i'm \"karthik\"") --escape sequencing
# print("C:\\Python\\Geeks\\")
# print(r"I... | true |
f5869aaa4189761e68f83239aa7016ebef0b01b4 | Justin696/2020-21-c1-challenge-08 | /main.py | 800 | 4.15625 | 4 | print("you can do all chalenges in this challenge")
print("Please enter the Chalenge number from 1 to 7")
num = int(input("<: "))
if num < 1:
print("there are no challenges less than 1")
elif num > 7:
print("There are no challenges more than 1")
elif num == 1:
print("You have chosen to play chalenge 1 good ... | false |
24cd787fb713d2e489d59e4f698ec1fd233c8e93 | vigoroushui/python_lsy | /8.object_oriented_programming/instanceAndClass.py | 566 | 4.15625 | 4 | #区别,第一个是实例属性、第二个是类属性
def Student(object):
def __init__(self, name):
self.name = name
class Student1(object):
name = 'Student'
# 在编写程序的时候,千万不要对实例属性和类属性使用相同的名字
# 因为相同名称的实例属性将屏蔽掉类属性,
# 但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。
stu = Student1()
print(stu.name)
print(Student1.name)
stu.name = 'Jack'
print(stu.name)... | false |
29be4af3d652948430278ffe545f81c011643a1e | ronaka0411/Google-Python-Exercise | /sortedMethod.py | 222 | 4.125 | 4 | # use of sorted method for sorting elements of a list
strs = ['axa','byb','cdc','xyz']
def myFn(s):
return s[-1] #this will creat proxy values for sorting algorithm
print(strs)
print(sorted(strs,key=myFn))
| true |
d53ea1900d1bfc9ab6295430ac272616293cb09d | talebilling/hackerrank | /python/nested_list.py | 1,480 | 4.3125 | 4 | '''
Nested Lists
Given the names and grades for each student in a Physics class of students, store
them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade,
order their names alphabetically and print each name on a new line... | true |
9dd75d361e52c9c1e6169b6b3f47d1e202db1a76 | a-soliman/pythonData-structureAndAlgorithms | /sec-15-recursion/hw.py | 2,200 | 4.25 | 4 | '''
'''
#=======================================================================================
# recursive Sum
'''
Write a recursive function that returns the sum from 0 up to n
'''
def sum_down( n ):
if n == 1:
return 1
else:
return n + sum_down(n-1)
print('23- sum_down: '... | false |
401123e1362106e0268f2050533c15048ef5d767 | ruselll1705/home | /home_work3_3.py | 600 | 4.125 | 4 | while True:
print("Type 'quit' to exit")
phrase = input("Your message: ")
if phrase == "quit":
break
elif phrase == "Hello" or phrase == "Hi":
print("Hi! How‘s it going?")
elif phrase == "What is your name?":
print("I don't have name :(")
elif phrase=="я устал":
... | false |
cc2355c574130c4b5244b930cb6c5c3160af40e3 | KarimBertacche/Intro-Python-I | /src/14_cal.py | 2,289 | 4.65625 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
... | true |
1387e63d50e7170a0733e43c95da207acf0f5925 | kagekyaa/HackerRank | /Python/005-for_while_loop_in_range.py | 488 | 4.28125 | 4 | '''https://www.hackerrank.com/challenges/python-loops
Read an integer N. For all non-negative integers i<N, print i^2. See the sample for details.
Sample Input
5
Sample Output
0
1
4
9
16
'''
if __name__ == '__main__':
n = int(raw_input())
for i in range(0, n):
print i * i
'''
A for loop:
for i in ran... | true |
261a252acbfe4691fbee8166a699e3789f467e8b | franciscoguemes/python3_examples | /basic/64_exceptions_04.py | 1,328 | 4.28125 | 4 | #!/usr/bin/python3
# This example shows how to create your own user-defined exception hierarchy. Like any other class in Python,
# exceptions can inherit from other exceptions.
import math
class NumberException(Exception):
"""Base class for other exceptions"""
pass
class EvenNumberException(NumberExce... | true |
73cccc2cd1bbcea2da0015abc9ea0157be449844 | franciscoguemes/python3_examples | /projects/calculator/calculator.py | 1,434 | 4.3125 | 4 | #!/usr/bin/python3
# This example is the typical calculator application
# This is the calculator to build:
# #######
# 7 8 9 /
# 4 5 6 *
# 1 2 3 -
# 0 . + =
# Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s
import tkinter
window = tkinter.Tk()
#window.geometry("312x324")
window.resizable... | true |
7244b8b9da478b14c71c81b2ff299da0e4b18877 | franciscoguemes/python3_examples | /basic/06_division.py | 697 | 4.4375 | 4 | #!/usr/bin/python3
# Floor division // --> returns 3 because the operators are 2 integers
# and it rounds down the result to the closest integer
integer_result = 7//2
print(f"{integer_result}")
# Floor division // --> returns 3.0 because the first number is a float
# , so it rounds down to the closest integer and ret... | true |
e83ee865e27bc54b1c58fb9c220ef757d2df4de3 | franciscoguemes/python3_examples | /advanced/tkinter/03_click_me.py | 557 | 4.125 | 4 | #!/usr/bin/python3
# This example shows how to handle a basic event in a button.
# This basic example uses the command parameter to handle the click event
# with a function that do not have any parameters.
# Example inspired from: https://www.youtube.com/watch?v=VMP1oQOxfM0&t=1176s
import tkinter
window = tkinter.... | true |
776a51053306a024ab824003e63255c89cdbb6d4 | franciscoguemes/python3_examples | /basic/09_formatting_strings.py | 673 | 4.625 | 5 | #!/usr/bin/python3
# TODO: Continue the example from: https://pyformat.info/
# There are two ways of formatting strings in Python:
# With the "str.format()" function
# Using the Old Python way through the "%" operator
# Formatting strings that contain strings
old_str = "%s %s" % ("Hello", "World")
new_str = "{}... | true |
380ac40a79d2cea253904d211f33ec41ae9d99f0 | dallinsuggs/CS241 | /DSweek07.py | 273 | 4.125 | 4 | def fibonnaci(number):
if number <= 0:
return 0
elif number == 1:
return 1
elif number == 2:
return 2
return fibonnaci(number - 1) + fibonnaci(number - 2)
for i in range(0,20):
print("Fibonacci({}) = {}".format(i,fibonnaci(i))) | false |
b315f178386a8072670a9087e791c0f978cd2212 | stianbm/tdt4113 | /03_crypto/ciphers/cipher.py | 1,223 | 4.28125 | 4 | """The file contains the parent class for different ciphers"""
from abc import abstractmethod
class Cipher:
"""The parent class for the different ciphers holding common attributes and abstract methods"""
_alphabet_size = 95
_alphabet_start = 32
_type = ''
@abstractmethod
def encode(self, te... | true |
a84b2ca62ea2a64073f5a54f8ea19657079819ad | smh128/jtc_class_code | /challenges/04_NBA /nba3pts.py | 2,821 | 4.3125 | 4 |
print("Challenge 2.1:")
jamal_murray_3pts_made = 46
Vanvleet_3pts_made = 43
Harden_3pts_made = 39
print("Challenge 2.2:")
print("In the 2020 NBA playoffs Jamal Murray made this many 3 point shots:")
print(jamal_murray_3pts_made)
print("In the 2020 NBA playoffs Fred Vanvleet made this many 3 point shots:")
print(Van... | false |
9c20ceec0fdccd3bc2bb92815e56b7a99855058a | cindy859/COSC2658 | /W2 - 1.py | 721 | 4.15625 | 4 | def prime_checker(number):
assert number > 1, 'number needs to be greater than 1'
number_of_operations = 0
for i in range(2, number):
number_of_operations += 3 #increase of i, number mod i, comparision
if (number % i) == 0:
return False, number_of_operations # returning multip... | true |
bdc290072854219917fe8a24ef512b26d38e93f9 | TecProg-20181/02--matheusherique | /main.py | 1,779 | 4.25 | 4 | from classes.hangman import Hangman
from classes.word import Word
def main():
guesses = 8
hangman, word = Hangman(guesses), Word(guesses)
secret_word, letters_guessed = hangman.secret_word, hangman.letters_guessed
print'Welcome to the game, Hangman!'
print'I am thinking of a word that is', len(s... | true |
a836c740813a8a4b99f644d9a0b889c134f172af | panxiufeng/panxftest | /python-test/base_test/ch14_struct03_set.py | 574 | 4.15625 | 4 |
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # 删除重复的
print("orange" in basket)
# 两个集合间的运算
a = set('abracadabra')
b = set('alacazam')
print(a)
print(b)
print(a - b) # a和b的差集
print(a | b) # a和b的并集
print(a & b) # a和b的交集
print(a ^ b) # a和b中不同时存在的元素... | false |
0efc2e80426f7e553442765462dfec8f4415ea67 | panxiufeng/panxftest | /python-test/base_test/ch12_iter.py | 1,711 | 4.1875 | 4 | # 字符串,列表或元组对象都可用于创建迭代器:
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
print (next(it)) # 输出迭代器的下一个元素
print (next(it))
print ("---------")
# 迭代器对象可以使用常规for语句进行遍历
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in it:
print (x, end=" ")
print()
print ("---------")
# 也可以使用 next() 函数:
# import sys # 引入 sys... | false |
327d89760aca774d4cf1019eda5c88cadc469502 | arossbrian/my_short_scripts | /multiplier.py | 405 | 4.15625 | 4 | ##This is a multiply function
#takes two figures as inputs and multiples them together
def multiply(num1, num2):
multiplier = num1 * num2
return multiplier
input_num1 = input("Please enter the first value: ")
input_num2 = input("Enter the Second Value: ")
##input_num1 = int(input_num1)
##input_num2 = ... | true |
f8b914676da0c034a908c3e440313e6633264068 | arossbrian/my_short_scripts | /shoppingbasketDICTIONARIES.py | 492 | 4.15625 | 4 | print ("""
Shopping Basket OPtions
---------------------------
1: Add item
2: Remove item
3: View basket
0: Exit Program
""")
shopping_basket = {}
option = int(input("Enter an Option: "))
while option != 0:
if option == 1:
item = input("Add an Item :")
qnty = int(input("Enter the quan... | true |
36ec1104b30f90707920614405bc83cd5a2f7e40 | yeonsu100/PracFolder | /NewPackage01/LambdaExample.py | 601 | 4.5 | 4 | # Python program to test map, filter and lambda
# Function to test map
def cube(x):
return x ** 2
# Driver to test above function
# Program for working of map
print
"MAP EXAMPLES"
cubes = map(cube, range(10))
print
cubes
print
"LAMBDA EXAMPLES"
# first parentheses contains a lambda form, that is
# a squaring ... | true |
c30cd41b41234884aea693d3d0893f2889bd5f1d | deeptivenugopal/Python_Projects | /edabit/simple_oop_calculator.py | 605 | 4.125 | 4 | '''
Simple OOP Calculator
Create methods for the Calculator class that can do the following:
Add two numbers.
Subtract two numbers.
Multiply two numbers.
Divide two numbers.
https://edabit.com/challenge/ta8GBizBNbRGo5iC6
'''
class Calculator:
def add(self,a,b):
return a + b
def subtract(sel... | true |
6598f0f714711ea063ef0f160e65847cc9dfa295 | fiberBadger/portfolio | /python/collatzSequence.py | 564 | 4.15625 | 4 |
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
def app():
inputNumber = 0
print('Enter a number for the collatz functon!')
try:
inputNumber = int(input())
except (Val... | true |
f416c4993cfc11e8ca6105d48168d42952f55aa3 | fiberBadger/portfolio | /python/stringStuff.py | 813 | 4.125 | 4 | message = 'This is a very long message'
greeting = 'Hello'
print(message);
print('This is the same message missing every other word!');
print(message[0:5] + message[8:9] + ' ' + message[15:19]);
print('The length of this string is: ' + str(len(message)) + 'chars long');
print('This is the message in all lower case ' ... | true |
c4acbc2cc9cbbe534af749af6b6ceb44ee854b6f | kcthogiti/ThinkPython | /Dice.py | 352 | 4.1875 | 4 |
import random
loop_control = "Yes"
Min_num = int(raw_input("Enter the min number on the dice: "))
Max_num = int(raw_input("Enter the Max number on the dice: "))
def print_rand():
return random.randrange(Min_num, Max_num)
while loop_control == "Yes":
print print_rand()
loop_control = raw_input("Do you want to c... | true |
d8da2f3fe23acf33367543f0655f03b3dc71e9ce | yuukou3333/study-python | /55knock_py/knock_29.py | 852 | 4.21875 | 4 | # 辞書(キーの存在確認,get)
d = {'apple':10, 'grape':20, 'orange':30}
# if 'apple' in list(d.keys()):
# .get(キー)は辞書にキーが存在するかどうかを判断し、存在する場合はキーに対応する値、存在しない場合はNoneを返す
# .get(キー, 値)は辞書にキーが存在するかどうかを判断し、存在する場合はキーに対応する値、存在しない場合は第二引数で指定した値を返す
# 例
# d.get('pine')
# => None
# 辞書に指定した値を反映させたい時は、
# d['pineapple'] = d.get('pineappl... | false |
4fb1c11f72c165f881348a2145b6130346c15bcc | L200184134/Praktikum-Algopro | /Activity 4. Data Type (shell).py | 2,307 | 4.125 | 4 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> Nama = "Mahardhika Bathiarto Dim Zarita"
>>> NIM = 134
>>> Tinggi = 1.68
>>> Berat = 57
>>> TahunLahir = 2000
>>> Aku = (TahunLahir, Berat, Tinggi, NIM... | false |
6275eae9107c2d92a9df5f2c8749389434917a82 | SDrag/weekly-exercises | /exercise1and2.py | 1,450 | 4.375 | 4 | ###################
### Exercise 1: ###
###################
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# Test the function with the following value.
x = 18
ans = fib(x)
print("Fibonac... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.