blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
1111ea0b60ec6957d9c94b5da92d982b5b732cb4
UllasZ/Snakes-and-Ladders-Game
/snake.py
364
3.65625
4
# Create Snakes class Snakes: def __init__(self, name, head, tail): self.name = name self.head = head self.tail = tail def __repr__(self): return Snakes(self.name, self.head, self.tail) def __str__(self): return f"\nSnake Name : {self.name} \nSnake Head...
17a44a930eac09c72138ef302d1bdc3eaf5b5328
kocejam/decile_peak_locator
/make a cumulative curve.py
1,373
3.703125
4
import matplotlib as plt import numpy as np import pandas as pd import random # number of bins NUM_PERCENTILES = 10 # create a data frame of ones df = pd.DataFrame(np.ones(NUM_PERCENTILES + 1)) cumulative_value = 0 bin_value = 0 current_bin = 1 num_bins = len(df.index) - 1 # set the first bin's value to 0 df[0][0] ...
cacbfe635c86f98da468cd0a8747d63b750d37fd
rbassot/serprintine
/app/classes.py
5,495
4.3125
4
import math class Board(object): ''' CLASS DESCRIPTION: An object class to maintain the attributes of the Battlesnake game board. ---------- ATTRIBUTES: width - width of the game board. height - height of the game board. food - list of x & y tuples that describe the coo...
28794476702f40982f58b544a4e637119739f5cb
SteveBlackBird/c0dewars
/kui6/unique_in_order.py
384
3.515625
4
message = '' def unique_in_order(iterable): i = 1 j = 0 r = [] iterables = [letter for letter in iterable] if iterable != '': r.append(iterables[0]) else: pass while i < len(iterables): if r[j] != iterables[i]: r.append(iterables[i]) j += 1 ...
8a40a006b06bc514deed31a17c0d56fcc5afc1f5
rhysJD/CC1404_Practicals
/Prac_10/wiki.py
506
3.90625
4
""" CP1404 Practical 10 Rhys Donaldson 13581558 5/11/2020 """ import wikipedia choice = input("What would you like to search for?\n>>>") while choice is not "": try: choice = wikipedia.page(choice) print(choice.title + "\n" + choice.summary + "\n" + choice.url) choice = input("What would yo...
8263b10b5c958eb40ebc8c67a4aafecf5b18a6f8
rhysJD/CC1404_Practicals
/Prac 2/exceptions_demo.py
785
4.21875
4
""" CP1404 - Practical 2 Rhys Donaldson """ try: numerator = int(input("Enter the numerator: ")) denominator = int(input("Enter the denominator: ")) while denominator == 0: denominator = int(input("Denominator cannot be zero. PLease enter a new number: ")) fraction = numerator / denominator ...
b8309b925a0b5e61bd6cac214d56d285c38aa2c6
rhysJD/CC1404_Practicals
/prac_8/unreliable_car.py
499
3.609375
4
""" Practical 8 CP1404 Rhys Donaldson 13581558 """ from prac_8.car import Car import random class UnreliableCar(Car): def __init__(self, name, fuel, reliability): super().__init__(name, fuel) self.reliability = reliability def drive(self, distance): """Checks if the car will drive th...
7b09ff5004b60956acee11a467682545e6914880
Saagar3690/Sorting-Visualizer
/algorithms.py
11,893
4.1875
4
import random # Bubble Sort # Time Complexity: O(n^2) # Space Complexity: O(1) def bubblesort(window, tk, data): # iteration counter iterations = 0 # boolean for if swaps occurred swapped = True # end of traversal counter end = len(data)-1 # while there has been a swap while swapped: swapped = Fals...
816706d71b907d09c28d62a82a061f226df3ecae
JCWDFCS/Python-Handy-Programs-Checklist
/kms_per_liter.py
1,987
3.890625
4
#The kilometers Per Liter program #Display the title. def display_menu(): print("The Kilometers Per Liter Program") print("=============================================") #get input from the user. # refacting to type_based_dispatch. def get_entries(): while True: try: liters_used = floa...
aa6f7c8783ef99b8acf4019fef428a8df11ff8f3
JCWDFCS/Python-Handy-Programs-Checklist
/movie_list_txt.py
1,923
3.984375
4
filename = 'movie.txt' def add_movie(movies): movie = input('Movie: ') year = input('Year:') movie = [] movies.append(movie) movies.append(year) write_movies(movies) print(movie[0] + ' was added.\n') def write_movies(movies): with open(filename, 'w') as file: for movie in mov...
bbb01aaadacb26d3083a42e4b984d1579e725fe1
ninashenoy/pytest
/examples/types/strings.py
2,221
4.0625
4
############################################################################### def strings_example(): h = "Hello" w = "World" hw = h + w print("h:: %s" % h) print("w:: %s" % w) print("hw:: %s" % hw) #compare if( h == w ): print("h::%s == w::%s are equal" %(h, w)) else: ...
e2ba4414c884d5a46a536eb1a99c21bbb2cd69a1
rikardsaqe/Customer-Churn-Predictor
/built_ann.py
6,503
3.859375
4
# Building an ANN # Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') # Input matrix of features X = dataset.iloc[:, 3:13].values # Output data y = dataset.iloc[:, 13].values # En...
dec925566c3f288bc77eda6736c21db5f850a253
Seekcha/PythonCode
/C2Ex2.py
242
3.921875
4
""" Week 2 Cour 2 Ex 2 Seekcha Sungkur Q: Modifiez le programme (1) pour afficher seulement le chiffre pair. """ x = int(input("inserez un numero: ")) count = 1 while count <= x: if count % 2 == 0: print(count) count += 1
aa51be7d9058472949a08869c27f72d4fece505e
Seekcha/PythonCode
/C2Ex7.py
533
3.84375
4
""" Week 2 Cour 2 Ex 7 Seekcha Sungkur Q: Compter les nombres de voyelles dans un texte. """ text = input("Veuillez inserer un text: ") print("Votre text est: " +str(text)) count = 0 voyelle = 0 while count < len(text): if text[count].lower() == "a" or text[count].lower() == "e" or text[count].lower()...
173a2856b094305af9c1c4b645859969527ae652
ling910520/git_resources
/decorator.py
1,593
4
4
# importing libraries import time import math # decorator to calculate duration # taken by any function. def calculate_time(func): # added arguments inside the inner1, # if function takes any arguments, # can be added like this. def inner1(*args, **kwargs): # storing time before function execution ...
685f5b4ead65493c2689d479df91bbc9af93aa0c
kiwi-33/Programming_1_practicals
/p12-13/p12p3(+pseudo).py
639
4.28125
4
'''define function for getting approx square root prompt for input and convert to float check if greater than 0 call function with (input, self selected tolerance) else print message''' def sq(number, epsilon): root = 0.0 step = epsilon**2 while abs(number-root**2) >= epsilon and root <= number: ro...
ed23c85dfb2dcb73d0fe6095b250475d281d2f06
kiwi-33/Programming_1_practicals
/p8-9/p9p3.py
275
4.09375
4
'''pseudocode prompt for +ve int factorial=0 if int = 0 print 1 if int = 1 print 1 for x in range (1, int): factorial=x*int''' number = int(input('Enter a number: ')) factorial = 1 for x in range(1, number +1): factorial *= x print(factorial)
5b1987d6365009a6e1bd4ca6497639782530068d
kiwi-33/Programming_1_practicals
/p10-11/p11p2.py
981
4
4
''' here we are calculating (input) number of terms of fibonacci prompt for limit f_0=0 f_1=1 fib = 0 while number > 0: if limit == 1: print('Series is: ', f_0) if limit == 1: print('Series is: ', f_0, f_1, sep =', ') while limit >= 2: print('Series is f1, f2, serp ', ', ...
ddb2f13ed4d056934a51cdc65a58aa3c7eabe411
kiwi-33/Programming_1_practicals
/p14-15/p15p3.py
568
4.1875
4
'''define the function prompt for input enter while loop: enter for loop, limit = input: print statement that shows progression towards the base case and calls function prompt for input''' def series(x): if x == 0: return 13 elif x == 1: return 8 else: return((series...
3d379a34e3389fa8a3c0eb51491942d5c2956a17
kiwi-33/Programming_1_practicals
/p18-19/p18p5.py
552
3.859375
4
'''define function(): first of all check to see if the forst 3 characters are == xyz. (otherwise xyz. would return false by methodd below, because x[i-1] == . then enter for loop for range(0, length input -2): search for string of length 3 that == xyz and make sure it is not preceeded by ".": r...
e311281ccf2544bdfebd9e244516a7689d2cb681
kiwi-33/Programming_1_practicals
/p6-7/p7p2.py
301
4.09375
4
year = int(input('Enter a year: ')) print('Year entered is:', year) if year %4 != 0: print(year, 'is a common year') elif year %100 != 0: print(year, 'is a leap year') elif year %400 != 0: print(year, 'is a common year') else: print(year, 'is a leap year')
df62c503e28672228af20b6f6d6dcb42d8d69504
kiwi-33/Programming_1_practicals
/p12-13/p12p1(+pseudo).py
491
3.984375
4
'''define function for getting factorial prompt user for input check if greater than 0 call factorial function and print answer if < 0 print error message''' import time def fact(x): answer=1 for i in range(1, x+1): answer*=i return answer number = int(input('Enter a number: ')) if number >= 0: ...
001c7bfa77f2cd45f57e6e6eb5e450a79d91a9b2
kiwi-33/Programming_1_practicals
/p18-19/p18p6.py
1,906
3.859375
4
'''import os.path check if webpage is a file check if results is a file prompt for confirmation if it already exists open files for reading and writing initialise all counts to 0 for line in file: for char in file: check for characters: if so, incriment counter for character in range (0, le...
f5092fc08b817b320e79dbf79bbbfcc7062a854c
wootfish/cryptopals
/challenge_04.py
692
3.578125
4
from typing import Tuple, Optional from challenge_03 import crack_xor_cipher if __name__ == "__main__": with open("data/04.txt") as f: lines = [bytes.fromhex(line.strip()) for line in f] overall_best = (float('inf'), None, None, None) # type: Tuple[float, Optional[int], Optional[bytes], Optional[by...
680152fcd1e36f3e14834730828c28006c19eb6c
gmgressard/markove-chains
/markov.py
2,617
4
4
"""Generate Markov text from text files.""" from random import choice def open_and_read_file(file_path): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ txt = open(file_path).read() ...
156485298d969e555b69da958dcaa174935b2f5d
chinhtle/python_fun
/blackjack.py
12,519
3.71875
4
from __future__ import print_function import random BANK_DEFAULT_BUYIN = 100 def get_user_response(input_request): """ Prints the request and asks user for their y/n input. Returns True if user inputs 'y' and False if user inputs 'n'. """ while True: player_move = raw_input("{...
1b959624522e9bfb7d35d7e4d30199981b9c0ba4
chinhtle/python_fun
/hacker_rank/algorithms/implementation/catsandamouse.py
1,429
3.578125
4
# Two cats named A and B are standing at integral points on the x-axis. Cat A # is standing at point x and cat B is standing at point y. Both cats run at the # same speed, and they want to catch a mouse named C that's hiding at integral # point z on the x-axis. Can you determine who will catch the mouse? # # You are gi...
f36fe117ee1819347873d4dc0c9c6ab52f7da006
chinhtle/python_fun
/udemy/largestsum.py
387
3.953125
4
# Problem: # Given an array of integers (positive and negative) find the largest # continuous sum. def largest_sum(arr): if not arr: return 0 # Set to first element since it can be a negative number. max_sum = current_sum = arr[0] for num in arr[1:]: current_sum += num ...
54390a1c7270532c25eaa0d92cebf1b0a18b504a
Zpryakhin/bek_mek
/import_prime_check/prime_hard_function/phf.py
254
3.703125
4
import math def Is_Prime(a): ans = False b = math.factorial(a-1) #По теореме Вильсона, если p простое, то (p-1)! = -1 mod p или (p-1)! + 1 = 0 mod p if (b + 1) % a == 0: ans = True return ans
cc506a3faef0b00f1c517943ffe4b43d27dfb253
Zpryakhin/bek_mek
/fib.py
497
3.5625
4
import itertools class Fib: class _Fib_iter: def __init__(self): self.fib1 = 0 self.fib2 = 0 self.fib3 = 1 self.i = 1 def __next__(self): f = self.fib3 self.i += 1 self.fib1 = self.fib2 self.fib2 = self.f...
fca8d4a5317aa8753e6813ee2bd3bf45ce79a137
JoshChubi/Academic
/Spring2019/Intro to Python/Random Numbers/randomNumbers.py
587
3.578125
4
# Josh Ortiz CI 561 import random import math numberOfRandoms = 10 file_ranNum = open("randomNumbers.txt",'w') for itteration in range(numberOfRandoms): file_ranNum.write(str(random.randint(0,9))+' ') file_ranNum.close() numbers = [int(element) for element in ( open("randomNumbers.txt").read() ).split...
e3a2d43a1fcaf18a0e79c0583b9e36235ce6754b
JoshChubi/Academic
/Spring2019/Intro to Python/Test Practice/Five.py
688
3.796875
4
# Josh Ortiz cs561 # Question 5 class c1: def __init__(self,s,x,y): self.s = s self.x = x self.y = y def __str__(self): return ' '.join([self.s,str(self.x),str(self.y)]) def swap(self): self.x,self.y = self.y,self.x def add(self,other): return c1(self.s+'-'+other.s,self.x+other.x,self.y+ot...
d3ac6c4557a1031ac61457aa62f33260a6a880c6
ray3175/xy
/xy/cipher/symmetric/AES/pad.py
847
3.671875
4
from abc import ABC, abstractmethod class _Pad(ABC): __getitem__ = lambda self, item: getattr(self, item) if item and hasattr(self, item) else None @abstractmethod def default(self): pass @abstractmethod def PKCS5Padding(self): pass class Pad(_Pad): def default(self, _bytes...
a682d17b012dcd250966b25229d3ef88fdaeff97
umar7182000/UMAR-MF
/5.py
140
3.71875
4
a, b, c = input ().split() a = int (a) b = int (b) c = int (c) if ( a > b and a > c ): print(a) elif( b > c): print(b) else: print(c)
68390cc2272a00e24b578960ba52c76c1a3265e4
Kadus90/CS50
/pset6/mario/less/mario.py
899
4.21875
4
from cs50 import get_int def main(): # Get an integer between 1 - 8 height = get_positive_int("Height: ") # Print bricks print_bricks(height) def get_positive_int(prompt): # Use get_int to get an integer from the user n = get_int(prompt) # While not in the proper range while n < 1 or...
9854c1b0c2f7b85c982577450d4b7bb37fdd8648
doofusdavid/CSC506_Module5_Critical
/Heapsort.py
1,601
4.09375
4
from Heap import MaxHeap # Binary max heap percolate down def max_heap_percolate_down(node_index, heap_list, list_size): child_index = 2 * node_index + 1 value = heap_list[node_index] while child_index < list_size: # Find the max among the node and all the node's children max_value = valu...
cd280dcb66503d15916a66629c4d2d0611e7a415
prodigeni/minim
/minim.py
6,061
3.84375
4
# Interpreter for the Minim Programming Language # Version 1b # Josh Hartigan -- joshhartigan.github.io COLOR_RED = "\033[93m" COLOR_BLUE = "\033[94m" COLOR_RESET = "\033[0m" ERROR_NOT_UNDERSTOOD = COLOR_RED + "<minim> Instruction not understood." + COLOR_RESET ERROR_ARGUMENT = COLOR_RED + "<minim> Invalid arguments....
ccb9824ec5d7ffeeb123b86914383d174eb63e03
alcoccoque/Homeworks
/hw5/ylwrbxsn-python_online_task_5_exercise_2/task_5_ex_2.py
692
4.5625
5
""" Task05_2 Create function arithm_progression_product, which outputs the product of multiplying elements of arithmetic progression sequence. The function requires 3 parameters: 1. initial element of progression - a1 2. progression step - t 3. number of elements in arithmetic progression sequence - n Example, ...
a0716844aecf22b76731ae339ea52037ba170bb9
alcoccoque/Homeworks
/hw10/ylwrbxsn-python_online_task_10_exercise_3/task_10_ex_3.py
2,102
4.375
4
""" File `data/students.csv` stores information about students in CSV format. This file contains the student’s names, age and average mark. 1. Implement a function get_top_performers which receives file path and returns names of top performer students. Example: def get_top_performers(file_path, number_of_top_st...
28c998e30f41f350345d22934294b93fda8f3dc2
alcoccoque/Homeworks
/hw9/ylwrbxsn-python_online_task_9_exercise_4/task_9_ex_4.py
2,094
4.28125
4
""" Implement a bunch of functions which receive a changeable number of strings and return next parameters: 1) characters that appear in all strings 2) characters that appear in at least one string 3) characters that appear at least in two strings Note: raise ValueError if there are less than two strings 4) ch...
d5b3eb35448994bbe027230cf715f633e3bbef90
alcoccoque/Homeworks
/hw4/ylwrbxsn-python_online_task_4_exercise_8/task_4_ex_8.py
638
4.1875
4
""" Task 04-Task 1.8 Implement a function which takes a list of elements and returns a list of tuples containing pairs of this elements. Pairs should be formed as in the example. If there is only one element in the list return `None` instead. Using zip() is prohibited. Examples: >>> get_pairs([1, 2, 3, 8, 9]) ...
d19d5944d0599f8c69cc04052bc5582fe50778cc
aldld/algebra
/algebra.py
6,310
3.765625
4
import rules def dictionary(expression, pattern): """ Returns a dictionary of variables {'name': <name (from pattern)>, 'value': <value (from expression)>} Returns False if the expression does not match the pattern """ variables = {} if isinstance(pattern, list): # If pattern is a...
0039bfc1dae3f74a8116973fade7541d37435561
mandypepe/py_data
/spark_querin_dataset.py
1,071
4.1875
4
# First we need to import the following Row class from pyspark.sql import SQLContext, Row # Create a RDD peopleAge, # when this is done the RDD will # be partitioned into three partitions peopleAge = sc.textFile("examples/src/main/resources/people.txt") # Since name and age are separated by a comma let's split them par...
b629da343e17aeefc417075d760c1488d3ec1e3e
GeorgiTodorovDev/Python-Fundamental
/06.Exercise: Basic Syntax, Conditional Statements and Loops/MoreExercise/04.sum_of_a_beach.py
412
3.8125
4
my_string = input() case_my_string = my_string.lower() counter = 0 if case_my_string.find("sand") != -1: counter += case_my_string.count("sand") if case_my_string.find("water") != -1: counter += case_my_string.count("water") if case_my_string.find("fish") != -1: counter += case_my_string.count("fish") if c...
de18016bc603137d82dfd423beffa806499bcc4c
GeorgiTodorovDev/Python-Fundamental
/08.Exercise: Data Types and Variables/MoreExercise/05.balanced_brackets.py
459
3.75
4
n = int(input()) open_brackets = 0 closed_brackets = 0 unbalanced = False for i in range(1, n + 1): another_str = input() if another_str == "(": open_brackets += 1 elif another_str == ")": closed_brackets += 1 if not open_brackets - closed_brackets == 0: unbalanced = True...
bc20823f2e56795ba615a43e356df7f24c6c2f60
GeorgiTodorovDev/Python-Fundamental
/08.Exercise: Data Types and Variables/01.integer_operations.py
141
3.578125
4
one = int(input()) two = int(input()) three = int(input()) four = int(input()) result = (int((one + two) / three)) * four print(f'{result}')
7e51054164bb30716cad15edd0314012e85e88f4
GeorgiTodorovDev/Python-Fundamental
/06.Exercise: Basic Syntax, Conditional Statements and Loops/MoreExercise/05.how_much_coffe_you_need.py
363
3.9375
4
word = ["coding", "dog", "cat", "movie", "CODING", "DOG", "CAT", "MOVIE"] our_input = input() coffe = 0 while not our_input == "END": if word.count(our_input) == 1: if our_input.isupper() == True: coffe += 2 else: coffe += 1 our_input = input() if coffe > 5: print("Yo...
152646f7be377964f940458380bd9fde603f3789
sonicfrog-z/python_practice
/2_basic data sructures/word_file_demo_improved.py
978
4.03125
4
# step1: read words from words.txt and print all palindrome words # step2: find the longest palindrome word def is_palindrome(word): word = word.lower() return word == word[::-1] def is_abecedarian(word): word = word.lower() for index in range(len(word)-1): curr_letter = word[ind...
09ab1cb021146e768b98db8f387c24162798deb8
sonicfrog-z/python_practice
/5_random&recursion/random_demo.py
298
3.75
4
import random colors = ['red', 'blue', 'pink', 'yellow', 'green', "purple"] for _ in range(10): # print(random.randint(1, 6)) # print(random.random()) print(random.choice(colors)) numbers = [i for i in range(1, 51)] print(numbers) random.shuffle(numbers) print(numbers)
b03a499ee2e745b83f5710bd75f77bd1f1a23fd2
sonicfrog-z/python_practice
/8_exceptions/getter_setter_demo.py
806
3.9375
4
class Person: _minimum_age = 16 def __init__(self, name, age, ssn): self._name = name self._age = Person._minimum_age self.set_age(age) self.__ssn = ssn def __str__(self): return '{} is {} years old with SSN: {}'.format( self._name, ...
a037b8fd0be6a2cfc6a14de2c456aaab18d024e2
sonicfrog-z/python_practice
/10_decorator/descriptor_demo.py
479
3.65625
4
class NameDescriptor: def __get__(self, instance, owner): print('__get__ is called') return instance._name def __set__(self, instance, value): print('__set__ is called') instance._name = value class Person: def __init__(self, name): self._name = name ...
8a45d5b89eaec1edae2ebd3a22e9a562df590a3a
sonicfrog-z/python_practice
/3_list&dictionary/different_params.py
907
3.84375
4
# def sum_avg(*numbers): # sum_ = sum(numbers) # return sum_, sum_/len(numbers) # # # s, a = sum_avg(7, 4, 9, 8, 12, 4, 3) # print(s, a) # s, a = sum_avg(7, 4, 9) # print(s, a) # s, a = sum_avg(7, 4, 9, 8, 12, 4, 3, 10, 2, 3) # print(s, a) # # # def max_min(*numbers): # return max(numbers), mi...
5dc3b896a9777003e5120a2be0836842983a2323
sonicfrog-z/python_practice
/4_list comprehension/zip_demo.py
494
4.09375
4
names = ['Alice', 'Bob', 'Charles', 'David'] ages = [19, 18, 17, 19] schools = ['Stanford', 'Bekerley', 'UCSC', 'San Jose State'] result = list(zip(names, ages, schools)) print(result) result2 = dict(zip(names, zip(ages, schools))) print(result2) def hamming_distance(word1, word2): distance = 0 f...
83d5e40762a54a5c705db48edb8342305094ab16
sonicfrog-z/python_practice
/4_list comprehension/comprehension_demo.py
710
4.03125
4
numbers = [1, 4, 2, 3, 5] square_numbers = [number**2 for number in numbers] print(square_numbers) even_square_numbers = [number**2 for number in numbers if number % 2 == 0] print(even_square_numbers) even_square_numbers2 = [ number**2 if number % 2 == 0 else -1 for number in numbers ] print(even_squa...
5123ef73ee33d927855711053bd5a6b6bf814184
sonicfrog-z/python_practice
/8_exceptions/property_demo.py
1,088
3.75
4
class Person: _minimum_age = 16 def __init__(self, name, age, ssn): self._name = name self._age = Person._minimum_age self.age = age self.__ssn = ssn def __str__(self): return '{} is {} years old with SSN: {}'.format( self._name, ...
71978b2f81f7a073b18fc55bb62bdbd3ffcb77ec
baviamu/set5-7.py
/range.py
70
3.546875
4
jaan=int(input()) if 1<jaan<10: print("yes") else: print("no")
49a1f394d6c2cd0c4740c997a7134f6a18cc1f50
lunawarrior/python_book
/Exercises/8/12_remove_first.py
286
3.578125
4
''' Write a function that removes the first occurrence of a string from another string: ''' from test import test test(remove("an", "banana"), "bana") test(remove("cyc", "bicycle"), "bile") test(remove("iss", "Mississippi"), "Missippi") test(remove("eggs", "bicycle"), "bicycle")
990d5d2f9c666b6c0343f19362c3c082bf1b3508
lunawarrior/python_book
/Exercises/example.py
364
3.640625
4
# f_out = open("print_to_this.txt", "w") # f_out.write("Write this\n") # f_out.write("and this\n") # f_out.close() # cout << "this is a test" << endl def arrow_arrow(handle, to_write): open(handle, "a") handle.write(to_write) handle.close() return handle arrow_arrow( arrow_arrow("print_to_this.txt"...
2a51577b5291d2667e285d799a1cb47d0dec5c88
lunawarrior/python_book
/Exercises/6/1_turn_clockwise.py
721
4.28125
4
''' This is the first exercise in chapter 6: The four compass points can be abbreviated by single-letter strings as “N”, “E”, “S”, and “W”. Write a function turn_clockwise that takes one of these four compass points as its parameter, and returns the next compass point in the clockwise direction. Here are some tests...
01204d88268c19aa3d98fdd852ddfab9aecf3a6f
lunawarrior/python_book
/Exercises/7/1_odd_numbers.py
404
4.0625
4
''' This is the first exercise in chapter 7 Write a function to count how many odd numbers are in a list. Remember the definition of an odd number. When divided by 2, the remainder should be 1 ''' from test import test #Define your count_odd function here # Here are the tests test(count_odd([1, 2, 3, 4, 5, 6, 7, 8...
43a0b0175fcda09561805b785258148865fc8d8b
lunawarrior/python_book
/Exercises/14_list_algorithms/0_8_faster_serach.py
2,916
3.859375
4
def text_to_words(the_text): """ return a list of words with all punctuation removed, and all in lowercase. """ my_substitutions = the_text.maketrans( # If you find any of these "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\", # Replace them by these ...
09fab013a2aac4cb2c43ede423a95a5ee3ceedb8
lunawarrior/python_book
/Exercises/14_list_algorithms/0_1_linear_search_algorithm.py
762
3.96875
4
#Test Driven Development, write the tests, then write the code that will pass those tests. # We’d like to know the index where a specific item occurs within in a list of items. # Specifically, we’ll return the index of the item if it is found, or we’ll return -1 if # the item doesn’t occur in the list. # I have writ...
cce7669526bef8b9a9f8423ea3fd9e081c0e0d53
yanjianzao/Python_Study
/jlkjinterfce_mster/Study/get.py
954
3.734375
4
import os,sys sys.path.append(os.getcwd()) #os.getcwd() 方法用于返回当前工作目录 sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ''' os.path.dirname(path) 返回文件路径 ''' print(os.getcwd()) print(os.path.dirname(os.path.abspath(__file__))) print(os.path.abspath(__file__)) import os # 返回脚本绝对路径 print(os....
64a0bc8440fc1ed1b2984504b6dba6a9380f8bd4
Forestriver/Converters
/CurrencyConverter.py
360
4.03125
4
def currency_converter(rate_e, rate_d, euros, dollars): hryvnas = rate_e * euros + rate_d * dollars return hryvnas re = float(input("Enter rate for euro: \n")) rd = float(input("Enter rate for dollars: \n")) e = float(input("Enter euros: \n")) d = float(input("Enter dollars: \n")) print("The total amount UAH: ...
26bc4c40129472541b10bb0830632c0b975d5615
raz8153/PyChristmas
/Figures.py
965
3.78125
4
import turtle def box1 (turtle, color, x, y, width, height): turtle.penup() turtle.color(color) turtle.fillcolor(color) turtle.goto(x,y) turtle.pendown() turtle.begin_fill() for i in range(2): turtle.forward(width) turtle.left(90) turtle.forward(height) turtle...
263bbcbed3a5ada7e764051fb6dffb02d884b6ff
hyowon612/data-structure
/heap/heap.py
3,018
3.515625
4
class AdaptedHeap: # min_heap으로 정의함! def __init__(self): self.A = [] self.D = {} # dictionary D[key] = index def __str__(self): return str(self.A) def __len__(self): return len(self.A) def insert(self, key): self.A.append(key) self.D[key] = len(self.A)-1 self.heapify_up(len(self.A)-1) return sel...
a90f69c4c1c5f09acdd5898439d3063abc9cf603
BanjoMcBanjo/SlamDieProject
/MainClass.py
6,193
3.890625
4
import random class Die : def __init__( self, sides ) : self.thesides = 6 def __str__( self ) : return "This die has " + str(self.thesides) + " sides." def __roll__( self ) : return random.randrange(1, self.thesides+1, 1) class Player : def __init__ (self, name, score) ...
ab12696cbeaad3ea1414022cc5eec33d0fa26251
shabanskaya/Data-Structures-Algorithms-in-Python
/Part-1/19-09/1909H.py
115
3.84375
4
a = int(input()) m = a while a != 0: b = int(input()) if b > m and b != 0: m = b a = b print(m)
3cfd58fd82047be6930f853b34e851dd337687a8
shabanskaya/Data-Structures-Algorithms-in-Python
/Part-2/контесты/07D2.py
739
3.53125
4
def DFS(a, start, Color, stack): stack.append(start) Color[start] = 1 print(Color) for u in a[start]: print(u) print(stack) if Color[u] == 1: #print("nasheel") Color[u] = 2 #print(stack) print(*stack) return if C...
da3f7dca9f75f060f4c0ea6f96820d60f0ceee31
kernal1988/Netology
/Basic Python/10/Task1/main.py
759
3.515625
4
import requests heroes_list = ['Hulk', 'Captain America', 'Thanos'] def get_data(heroes_list): heroes_dict = dict.fromkeys(heroes_list) # print(heroes_dict) for hero in heroes_list: url = (f'https://www.superheroapi.com/api.php/2619421814940190/search/{hero}') heroes_dict[hero] = int(reque...
036e5c391449581183be7664ea2993998581314e
Kvazar78/Skillbox
/8_algoritm_for/task_83_1.py
467
4.09375
4
# Выведите третью степень каждого нечётного числа в диапазоне от # единицы до указанного пользователем числа включительно. # Для этого используйте шаг внутри функции range. n = int(input('Введи число: ')) for i in range(1, n +1, 2): print(f'Третья степень нечетного числа {i} - {i ** 3}')
26238ed48b766db895401493819457a183d22506
Kvazar78/Skillbox
/25_modules/return/task_253_3.py
2,022
3.78125
4
# Кастомные исключения # # Исключения в Python также являются классами, и все они берут свои истоки от самого главного класса — Exception. # И для создания своего собственного класса ошибки достаточно написать его дочерний класс. Например: # # class MyOwnException(Exception): # pass # # raise MyOwnException('Это мо...
2099499b2fb9fb27ed07f06026b259b744df3346
Kvazar78/Skillbox
/9_for_strings/task_94_1.py
120
3.671875
4
print('-' * 10) for i in range(4): print('|', end = '') print('O' * 8, end = '') print('|') print('-' * 10)
3753e2c5f8928ec49a37c0f38a83057767b636d2
Kvazar78/Skillbox
/8_algoritm_for/dz/task_11.py
338
4.0625
4
# Дано натуральное число N. Напишите программу для вычисления # следующей суммы ряда (начиная с единицы) degree = int(input('Введи степень: ')) summ = 1 for n in range(1, degree +1): s = ((-1) ** n) * (1 / 2 ** n) summ += s print(summ)
9f682db0dcc89ab6381271f077388845f204f8ed
Kvazar78/Skillbox
/8_algoritm_for/task_83_3.py
1,004
4.1875
4
# Саша просыпается когда угодно, но в 23 часа уже точно идёт спать. # Питается Саша следующим образом: каждые 3 часа он выпивает литр воды и # съедает N калорий. Пить и есть он, кстати, начинает сразу как только # проснётся. Напишите программу, которая считает сколько он выпьет литров # воды и сколько калорий он съест ...
01eb489797854f36c5c75fb08e018b6ec831b3ed
Kvazar78/Skillbox
/11_float_round/dz/task_12.py
1,032
3.984375
4
# Часы # # С начала суток прошло H часов, M минут, S секунд (0≤H<12, 0≤M<60, 0≤S<60). По данным числам # H, M, S определите угол (в градусах), на который повернулаcь часовая стрелка с начала суток и # выведите его в виде действительного числа. # # При решении этой задачи нельзя пользоваться условными операторами и цикл...
b4f2b525801f4a0a5467b45a1983da960594e619
Kvazar78/Skillbox
/24_classes/dz/task_9.py
1,112
3.625
4
from random import choice class Pole: lst = [i for i in range(1, 10)] def input(self, player, coord): self.lst[coord - 1] = player.symbol def print_pole(self): count_elem = 0 print("-" * 13) for i_elem in self.lst: count_elem += 1 print(f'| {i_elem...
974b3a37b49a7a41e9ed2b8e38459fe6a410a1a3
Kvazar78/Skillbox
/12_def/task_124_1.py
1,344
3.875
4
# Среднее арифметическое # Программа получает от пользователя 2 числа - a и b. Реализуйте функцию, которая принимает # на вход числа a и b, считает и выводит в консоль среднее арифметическое всех чисел из # отрезка [a; b]. Обеспечьте контроль ввода: не забывайте, что а всегда должно быть меньше, # чем b. # Прим...
dc9816c6de191b0e3a91ef3cbad3196476f55d31
Kvazar78/Skillbox
/8_algoritm_for/dz/task_8.py
1,811
3.703125
4
# В прошлый раз мы написали Саше программу, которая считает функцию # в каждой точке отрезка и выводит значение на экран. Но теперь ему # нужно, чтобы значения считались в обратном порядке. Плюс к этому в # программе ему нужно сделать так, чтобы можно было настраивать шаг, # с которым он скачет по точкам отрезка. # # Н...
b391144829bc43326c3a7be3eef5c7b6ad9e4166
Kvazar78/Skillbox
/float2/dz/task_9.py
1,087
4.4375
4
# Степень числа # # Дано вещественное положительное число a и целоe число n. # # Вычислите a в степени n, не используя циклы, возведение в степень через ** и функцию math.pow() # (да, такая тоже есть). Решение оформите в виде функции power(a, n). def power(a, n): if n < (-1): a *= a n +=1 po...
79034494c3418383b6baa8660d179503a55befc4
Kvazar78/Skillbox
/Hacking_on Python/pwgen.py
928
3.578125
4
# https://repl.it/@Levashov/hack import random def good_password_generator(length=10): letters = 'abcdefgihjklmnopqrstuvwxyz' upper_letters = 'ABCDEFGIHJKLMNOPQRSTUVWXYZ' digits = '0123456789' symbols = '!@#$%^&*()_+-=\'\\"' alphabet = letters + upper_letters + digits + symbols password = ''...
f80ce4e6e9ee62ba388c93cb127214033b86b16f
Kvazar78/Skillbox
/20_tuples/task_202_2.py
387
3.90625
4
import math def s_side_full(r, h): side = 2 * math.pi * r * h full = side + 2 * (2 * math.pi * r ** 2) return side, full r = int(input('Введи радиус: ')) h = int(input('Введи высоту: ')) side, full = s_side_full(r, h) print('Площадь боковой поверхности', round(side, 2)) print('Полная площадь', round(ful...
d77058dc12856ad93390c6485de970a21e76160c
Kvazar78/Skillbox
/15_list1/task_153_2.py
1,497
4.1875
4
# Соседи # # Дана строка S и номер позиции символа в строке. Напишите программу, которая выводит соседей этого символа и сообщение # о количестве таких же символов среди этих соседей: их нет, есть ровно один или есть два таких же. # # Пример 1: # # Введите строку: abbc # Номер символа: 3 # # Символ слева: b # Символ сп...
b166ccaf15c0c25884747827a8cf8000e21c02e5
Kvazar78/Skillbox
/16_list2/dz/task_4.py
800
3.921875
4
guests = ['Петя', 'Ваня', 'Саша', 'Лиза', 'Катя'] action = '' while True: print() print(f'Сейчас на вечеринке {len(guests)} человек:', guests) action = input('Гость пришёл или ушёл? ') if action == 'Пора спать': break else: name = input('Имя гостя: ') if action == 'пришёл': ...
831dbb7890b4562b8ed7f53c9ac326cf447158b9
Kvazar78/Skillbox
/12_def/dz/task_6.py
1,490
3.84375
4
# Текстовый редактор # Мы продолжаем разрабатывать новый текстовый редактор, и в этот раз нам поручили написать # для него код, который считает количество любой буквы и любой цифры в тексте (а не только # буквы Ы как раньше). # Напишите функцию count_letters, которая принимает на вход текст и подсчитывает, какое #...
b37f4a912d4a2e89742d28a84e6ce29619eaef8d
Kvazar78/Skillbox
/11_float_round/dz/task_4.py
1,978
3.546875
4
# Кодирование сообщений # # В компьютерах символы представляются в виде двоичного кода - это нолики и # единицы. Память компьютера состоит из бит - это один разряд двоичного кода. # Сообщение состоит из N символов. При кодировании этого сообщения для каждого # символа выделяется минимально возможное количество бит. С п...
bc799c08a481763510aaa17ef54168892738ff1c
Kvazar78/Skillbox
/18_format_f-strings/task_182_1.py
963
4.21875
4
# Заказ # # После того, как человек сделал заказ в интернет-магазине, ему на почту приходит оповещение # с его именем и номером заказа. # # Напишите программу, которая получает на вход имя и код заказа, а затем выводит на экран # соответствующее сообщение. Для решения используйте строковый метод format. # # Пример: # #...
c28108530768774a9e6656da5c4d958bc57c45c3
Kvazar78/Skillbox
/11_float_round/task_114_4.py
3,161
3.515625
4
# Мега-калькулятор # # Кеша учится в третьем классе, и уже умеет программировать на питоне. Как и # многие его одноклассники, он очень любит сразу применять все полученные # знания на практике. Вчера Кеша узнал про модуль math и его основные # возможности, поэтому решил написать мега-калькулятор, который бы применял # ...
8972ce6fcf663435611ff17ecf65bbd40c79a6c3
Kvazar78/Skillbox
/24_classes/dz/task_3.py
2,501
4.125
4
# Окружность # # На координатной плоскости рисуются окружности, у каждой окружности следующие параметры: координаты X и Y центра окружности и значение R ― это радиус окружности. По умолчанию центр находится в (0, 0), а радиус равен 1. # # Реализуйте класс «Окружность», который инициализируется по этим параметрам. Круг ...
9f9cfe0f194c28c96ad834bbc23493b93a17d713
Kvazar78/Skillbox
/18_format_f-strings/dz/task_4.py
655
3.734375
4
# Заглавные буквы # # Пользователь вводит строку. Напишите программу, которая изменяет регистр символов # в этой строке так, чтобы первая буква каждого слова была заглавной, а остальные # буквы - строчными. # # Пример: # # Введите строку: Кажется, я забыл выключить утюг # # Результат: Кажется, Я Забыл Выключить Утюг st...
5cd6b42215512fd27cc989d662e58057a02ee112
Kvazar78/Skillbox
/float2/dz/task_2.py
1,419
4.125
4
# Генеалогическое древо # # Сэм создаёт генеалогические деревья разных семей. Ему постоянно приходится рассчитывать количество # места, занимаемое именами родителей на экране. # # Пользователь вводит имена и фамилии двух родителей. Создайте функцию get_parent_names_total_length # для Сэма, которая возвращает количество...
fbb1c19cdef0dd3c5bd5e1e811affae5ead75d1b
Kvazar78/Skillbox
/12_def/task_122_3.py
1,264
3.84375
4
# Василий пришёл получать посылку на почту. Разумеется, в почтовом извещении ему нужно было # написать свои фамилию, имя и адрес проживания, чтобы кто-нибудь не получил посылку за него, # например члены его семьи (а им бы хотелось!). # # Напишите функцию для вывода фамилии, имени и адреса для конкретного члена семьи. ...
daf822d911b62894b775b26a322be393f83163f8
Kvazar78/Skillbox
/9_for_strings/task_93_2.py
870
4.4375
4
# Ваня экспериментирует с различного рода компьютерными вирусами, # которые портят жизнь людям. На просторах Интернета он нашёл код довольно # необычного вируса, который “поворачивает” весь текст в документе и # повторяет каждый символ 3 раза. # # Пользователь вводит текст. Напишите программу, которая выводит каждый # ...
6850b68b7ce9c4faed6eb5ecbc45a812468df483
Kvazar78/Skillbox
/20_tuples/task_202_1.py
328
3.84375
4
import random first_tuple = tuple(random.randint(0, 5) for _ in range(5)) second_tuple = tuple(random.randint(-5, 0) for _ in range(5)) triple_tuple = first_tuple + second_tuple print(first_tuple) print(second_tuple) print(triple_tuple) print('Количество нулей в 3ем кортеже:', triple_tuple.count(0))
f45571bb86756d0dee2cf15152112f7507f19af7
Kvazar78/Skillbox
/19_dict/task_194_1.py
757
3.9375
4
# Пунктуация # # Напишите программу, которая считает количество знаков пунктуации в символьной строке. # К знакам пунктуации относятся символы из набора ".,;:!?". Набор должен храниться # в виде множества. # # Пример: # # Введите строку: Я! Есть. Грут?! Я, Грут и Есть. # # Количество знаков пунктуации: 6 znak = {'.'...
924c2c8b4e6ac9437a4cb864e03ff1848e692c7b
Kvazar78/Skillbox
/16_list2/dz/task_3.py
454
3.5625
4
shop = [['каретка', 1200], ['шатун', 1000], ['седло', 300], ['педаль', 100], ['седло', 1500], ['рама', 12000], ['обод', 2000], ['шатун', 200], ['седло', 2700]] name = input('Название детали: ') count = 0 summ = 0 for item in shop: if item[0] == name: summ += item[1] count += 1 print('\nКол-во дет...
fcf5eed2b21c090872b9b2cdbfa890d23d2d4047
Kvazar78/Skillbox
/9_for_strings/task_92_1.py
1,016
4.03125
4
# К уроку литературы нужно было прочитать “Евгения Онегина”. # Учитель задаёт вопрос пяти случайным детям. Она задаёт вопрос # “Кто написал произведение?” и если ученик не угадывает, то учитель # ставит двойку и спрашивает следующего. Если хоть кто-то угадает, # то вопросы больше не задаются. Напишите программу, котора...
03087895d8c786bb0137805423872e7d26ed1642
Kvazar78/Skillbox
/7_for/dz/task_15.py
877
3.828125
4
# Для настольной игры используются карточки с номерами от 1 до N. # Одна карточка потерялась. Найдите ее, зная номера оставшихся карточек. # # Вводится число N, далее еще N − 1 чисел: номера оставшихся карточек # (различные числа от 1 до N). Программа должна вывести номер потерянной карточки. value = int(input('Введи к...
2ec46c396f8a8968ac9ba99c06d6845dcb40bc33
Kvazar78/Skillbox
/10_vlojennie_cikly/task_104_1.py
1,087
3.96875
4
# Нам дали заказ написать программу для электронной очереди. У каждого # человека в очереди есть номер: нулевой, первый, второй, третий и так далее. # Каждый час очередь уменьшается на одного человека, то есть уходит сначала # нулевой номер, затем первый, второй и так далее. Наша программа получает # на вход одно число...
2ade3194e71fa9dc2ae37377c7aba4f69c98e050
Kvazar78/Skillbox
/6.3_while_break/dz/task_1.py
720
4.21875
4
# Любителю математики Паше снова стало мало распечатанных табличек, # включая последнюю со степенями двойки. Теперь он хочет взять третью # степень чисел от 1 до абсолютно любого! # Напишите программу, которая возводит в третью степень каждое число # от 1 до N и выводит результат на экран. num = int(input('По какое чис...