blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
64b12083a5121e2cb38fa233f3e068a678834922
monkrobot/test_project
/JuniorLab/IP_Validation.py
719
3.78125
4
''' Напишите алгоритм, который будет проверять, являются ли IPv4 адреса валидными. IP-адреса валидны, если они состоят из 4 октетов со значениями между 0..255 (включительно) Входной аргумент является строкой с IP адресом. ''' str = " 1.2.3.4" def isvaliip(str): try: ip = [int(x) for x in str.split('.') if...
3fd479e2027cada3d67fe0891e98db330a6d3a80
monkrobot/test_project
/JuniorLab/Find_the_parity_outlier.py
661
3.984375
4
''' Вам задан массив, который содержит целые числа. Массив полностью состоит из целых четных или нечетных чисел, за исключением одного числа N. Напишите метод, который принимаем массив, как аргумент и возвращает число N. ''' N = [2,4,0,0,0,3,98,-22] A = [0, 3, 1719, 19, 11, 13, -21] def func(n): answer = [x for x...
56613784c62b3d925e359c6cef619ae883fc2597
monkrobot/test_project
/Tasks_from_acm.timus.ru/01HelloWorld.py
534
3.546875
4
import math import matplotlib.pyplot as plt x = [] y = [] def func123(yo, xo, x1): x0 = 0 y0 = 0 error = 0 deltax = abs(x1 - x0) deltay = abs(x1 * math.tan(yo/xo) - y0) deltaerr = deltay ys = y0 for x_point in range(x0, x1): x.append(x_point) print('ys', x_point, ys) ...
e2906f6c4e1bb856066a4fe95d339faa607a863e
monkrobot/test_project
/JuniorLab/Find_the_odd_int.py
621
3.96875
4
''' Вам дан массив с числами. Нужно найти целое число, которое встречается нечетное число раз. Такое число всегда будет только одно. ''' N = [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5, 20, 20, 20, 20 ] def func(n): counter = {} for elem in n: counter[elem] = counter.get(elem, 0) + 1 ...
5a6e7abec33e64dd73735746966de538e62efb94
monkrobot/test_project
/Project_Euler/3_LargestPrimeFactor.py
1,616
3.640625
4
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? ''' from math import sqrt n = 600851475143 factors = [] #Находим все делители без остатка для числа n и записываем их в factors for i in range(2, int(sqrt(n))): if n%i == 0: factors.extend([i,...
e78256ce6e43dee23c34378ffa7480dd58568748
monkrobot/test_project
/Project_Euler/6_Sum_square_difference.py
295
3.828125
4
''' Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. ''' N = 100 summa = 0 sum_of_sqrs = 0 for i in range(1, 101): summa += i sum_of_sqrs += i**2 sqr_of_summa = summa**2 print("answer", sum_of_sqrs - sqr_of_summa)
5b2865208d44d88aa11b3c41096406bbcf563e77
tnakaicode/python-cfd
/lessons_src/00_Quick_Python_Intro.py
8,286
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # Python Crash Course # Hello! This is a quick intro to programming in Python to help you hit the ground running with the _12 Steps to Navier–Stokes_. # # There are two ways to enjoy these lessons with Python: # # 1. You can download and install a Python distribution on you...
3cd847dacd5122fd314a2aea85c5a2bfaf50ba9f
tnakaicode/python-cfd
/lessons_src/07_Step_5.py
7,634
3.703125
4
#!/usr/bin/env python # coding: utf-8 # Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved BSD-3 license. (c) Lorena A. Barba, Gilbert F. Forsyth 2017. Thanks to NSF for support via CAREER award #1149784. # [@LorenaABarba](https://twitter.com/LorenaABa...
6d846da0bfa705602ae15a021db89eeaa5293a03
MarcoVinn/Projetos-Python
/transaçoes.py
385
3.84375
4
tran = int(input("Informe a quantidade de transações realizadas: ")) cont = 1 soma = 0 while tran >= cont: valor = float(input("Informe o valor da {}° transação: ".format(cont))) cont = cont + 1 soma = soma + valor print("O valor total das suas transações foram de R${}".format(soma)) print("O valor médio de...
4472c1ba6c824fb9021d05ef985d4394cc6a61f9
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/practise/pr_3.py
1,452
4.59375
5
# # # Buffet: A buffet-style restaurant offers only five basic foods. Think of five simple foods, and store them in a tuple. # # Use a for loop to print each food the restaurant offers. # Try to modify one of the items, and make sure that Python rejects the change. # The restaurant changes its menu, replaci...
2345f8475ac63b2d4b585322f4795310abad4337
YuriiKhomych/ITEA-BC
/Yurii_Khomych/5_functions/examples.py
1,175
4
4
# def my_function(first_name): # print(f"Hello {first_name}") # # my_function("World") # my_function("Bob") # my_function("Jonny") # my_function("Vasya") # # # def get_banana_index(foods): # banana_index = 0 # for num, food in enumerate(foods): # if food == "banana": # banana_index = num...
1944dfdcadc11363e212ae18c4703f0fdf0e6e85
YuriiKhomych/ITEA-BC
/Vlad_Hytun/8_files/HW/HW81_Hytun.py
1,509
4.59375
5
# 1. According to Wikipedia, a semordnilap is a word or phrase that spells # a different word or phrase backwards. ("Semordnilap" is itself # "palindromes" spelled backwards.) # Write a semordnilap recogniser that accepts a file name (pointing to a list of words) # from the program arguments and finds # and prints all ...
3b90644874792f29761b671f98bac7961db881aa
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/10_classes/HW/hw_1.py
3,064
4
4
# Add for each class (Dog, Cat, etc.) attribute `is_hungry = True` # Done # Then add a method called eat() which changes the value of `is_hungry` to `False` when called. # Create three instance of each class and call `eat` method. # Create a Pets class that holds instances of dogs, cats; this class is completely separ...
0d5c313729151e7a85b242ac9c962fde609e3ddf
YuriiKhomych/ITEA-BC
/Vlad_Hytun/5_functions/practise/P52-Hytun_Vlad.py
330
4.1875
4
# 2. Define a function that computes the length of a # given list or string. (It is true that Python has # the len() function built in, but writing it yourself # is nevertheless a good exercise.) def my_len(str): count_symbol = 0 for i in str: count_symbol += 1 return count_symbol print(my_len('d...
7182a3fc269c6e81fff77f6a66921c7469c6746b
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/HW/hw_6.py
726
4.34375
4
# # # Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. # # In each dictionary, include the kind of animal and the owner’s name. # Store these dictionaries in a list called pets. # Next, loop through your list and as you do print everything you know about each pet. # #...
71c997605a5578583cd9de46f7bdbe283dd99ff4
YuriiKhomych/ITEA-BC
/Sergey_Naumchick/5_functions/05_PR_03.py
411
4.1875
4
'''3. Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.''' VOLVED = 'aeiouy' my_input = "" while len(my_input) != 1: my_input = input("please input only one symbol: ") def my_func(func): if func in VOLVED: return True else: ...
fdce28c8eb106cdcc1f205ac12a2f813a893aaeb
YuriiKhomych/ITEA-BC
/Patenko_Victoria/3_conditions/homework3.1.py
2,979
4.25
4
my_fav_brand = ["toyota", "audi", "land rover"] my_fav_model = ["camry", "r8", "range rover"] my_fav_color = ["blue", "black", "gray"] price = 3000 brand: "str" = input("Brand of your car is: ") if brand not in my_fav_brand: print("Got it!") else: print("Good choice!") price_1 = price + 100 model = input("Mod...
45943b99ae8b5ae3323f871930ca3ad7ce13740e
YuriiKhomych/ITEA-BC
/Andrii_Ravlyk/9_functional_programming/practise/pr9_4.py
318
3.9375
4
'''Write decorator that collect result of each function into list''' def my_decorator(my_function): def my_wrapped(x,y): result_list = [] result_list.append(my_function(x,y)) print(result_list) return my_wrapped @my_decorator def my_function(x,y): return x+y #Test my_function(2,3)
80ef3072710719831cc6968b4d049e964b94faa4
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/HW/hw_2.py
1,823
4.375
4
# # # My Pizzas, Your Pizzas: Make a copy of the list of pizzas, and call it friend_pizzas. # Then, do the following: # # Add a new pizza to the original list. ########## Done # Add a different pizza to the list friend_pizzas. ######### Done # Prove that you have two separate lists. # # Print the messag...
14e5cd2b86f8e1df5ac05d69416b2a2455e3b47b
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/7_collections/practise/pr_1.py
1,296
4.65625
5
# # # Pizzas: Think of at least three kinds of your favorite pizza. Store these pizza # names in a list, and then use a for loop to print the name of each pizza. # # Modify your for loop to print a sentence using the name of the pizza # instead of printing just the name of the pizza. For each pizza you should #...
2e6fe0e1de69caccd003f1de0d9e2d43562d254b
YuriiKhomych/ITEA-BC
/Oksana_Yeroshenko/6_strings/6_strings_practise_yeroshenko_4.py
628
4.21875
4
my_string = "AV is largest Analytics community of India" # 4. Return first word from string. # result: `AV` my_string.split(' ')[0] # 5. Return last word from string. # result: `India` my_string.split(' ')[-1] # 6. Get two symbols of each word in string # result: `['AV', 'is', 'la', 'An', 'co', 'of', 'In']` my_st...
85f79e9a11264fbecf65e7c7e41e7cf36bfdc7bc
YuriiKhomych/ITEA-BC
/Nemchynov_Artur/5_functions/Practise#5.1.py
475
4.125
4
# . Define a function `max()` that takes two numbers as arguments # and returns the largest of them. Use the if-then-else construct # available in Python. (It is true that Python has the `max()` function # built in, but writing it yourself is nevertheless a good exercise.)""" def max_in_list(lst): max = 0 for n in ...
598d6b24b64826bff334de88948e23abe3e01762
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/9_functional_programming/HW9/hw_1.py
1,292
4.46875
4
# The third person singular verb form in English is distinguished by the suffix # -s, which is added to the stem of the infinitive form: run -> runs. A simple # set of rules can be given as follows: # If the verb ends in y, remove it and add ies If the verb ends in o, ch, s, sh, # x or z, add es By default just add s Y...
29b9026eeaf7d582b512ded6d6deb8ee3cf4da6d
YuriiKhomych/ITEA-BC
/Andrii_Bakhmach/4_iterations/4_3_exercise.py
303
4.15625
4
#Write a Python program that accepts a sequence of lines (blank line to terminate) as input #and prints the lines as output (all characters in lower case). our_line = input("please, input you text: ") if our_line is None: print("input your text once more") else: print(our_line.lower())
a3d0bef46700b4471601bc766aaf75d7e1c64cf7
YuriiKhomych/ITEA-BC
/Vlad_Hytun/7_collections/practise/P75_Hytun.py
804
4.90625
5
# 5. Rivers: # Make a dictionary containing three major rivers and the country each river runs through. # One key-value pair might be `'nile': 'egypt'`. # * Use a loop to print a sentence about each river, such as The Nile runs through Egypt. # * Use a loop to print the name of each river included in the dictio...
76cdeb563c3329f18ce11051aa902ca2a18f6bf7
YuriiKhomych/ITEA-BC
/Oksana_Yeroshenko/6_strings/6_strings_practise_yeroshenko_3.py
585
4.28125
4
# 3. Define a function `overlapping()` that takes two lists and # returns True if they have at least one member in common, # False otherwise. You may use your `is_member()` function, # or the in operator, but for the sake of the exercise, # you should (also) write it using two nested for-loops. a = (1, "a", "b", "c", ...
fb85dfcc07245c05844294fc7bd12ff25175d642
YuriiKhomych/ITEA-BC
/Andrii_Bakhmach/5_functions/HW/5_5_exercise.py
488
4.15625
4
#Write a function `is_member()` that takes a value #i.e. a number, string, etc) x and a list of values a, #and returns True if x is a member of a, False otherwise. #(Note that this is exactly what the `in` operator does, but #for the sake of the exercise you should pretend Python #id not have this operator.) def is_me...
d0def804e35c21164e7072c7a8eef2654d1a9bfa
YuriiKhomych/ITEA-BC
/Sergey_Naumchick/7_Collections/PR/PR_07_03.py
493
4.03125
4
menu = ("pizza", "apple", "burger", "soup", "pancake") new_dishes = ["fish", "dog"] def new_menu(old_menu, new_dish_list): new_menu = [] for dish in old_menu: if dish != "pizza" and dish != "soup": new_menu.append(dish) for dish in new_dish_list: new_menu.append(dish) prin...
26673a4cb7762f89c06e0bb5dab3387415aabb75
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/4_iterations/practise2.py
338
4.25
4
# Write a Python program to count the number of even # and odd numbers from a series of numbers. number = int(input('Make your choice number: ')) even = 0 odd = 0 for i in range(number): if i % 2 == 0: even += 1 elif i % 2 != 0: odd += 1 print(f'The odd numbers is {odd}') print(f'The even nu...
803f35a58aeb998610ec62bbba168b73b74439d6
YuriiKhomych/ITEA-BC
/Andrii_Ravlyk/6_strings/practise/pr6_4.py
347
4.09375
4
""" `string = AV is largest Analytics community of India` 4. Return first word from string. result: `AV`""" def find_first_word(i_str="AV is largest Analytics community of India"): import re match = re.search(r'\w+', i_str) print(match[0] if match else 'Not found') return match[0] if match else 'Not...
b891b864502638ebe5bd0ef4b302f62aaf8edb42
YuriiKhomych/ITEA-BC
/Vlad_Hytun/4_iterations-Hytun_Vlad/practise/P_41_iterations_Hytun-Vlad.py
384
4
4
# 1. Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. # Note : Use 'continue' statement. # Expected Output : 0 1 2 4 5 var = 0 while var < 7: if var in [3,6]: var += 1 continue else: print(var) var += 1 for i in range(7): if i in [3,6]: i ...
94cfe965059c1be0c455f78f4dd83c2b8df387f7
YuriiKhomych/ITEA-BC
/Vlad_Hytun/7_collections/hw/HW74_Hytun.py
632
4.1875
4
# # Dictionary # 4. Favorite Numbers: # * Use a dictionary to store people’s favorite numbers. # * Think of five names, and use them as keys in your dictionary. # * Think of a favorite number for each person, and store each as a value in your dictionary. # * Print each person’s name and their favori...
84c50cc665fa7f67d2bbe261ce6c657a6adf8da1
YuriiKhomych/ITEA-BC
/Andrii_Ravlyk/7_collections/practise/pr4_person.py
440
4.21875
4
'''4. Person: * Use a dictionary to store information about a person you know. * Store their first name, last name, age, and the city in which they live. * You should have keys such as first_name, last_name, age, and city. * Print each piece of information stored in your dictionary.''' my_dict = {"firs...
b4cdc62ebd3b100c5749c0592562a302e67305d5
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/6_strings/Pw/Pw_4.py
173
3.578125
4
# `string = AV is largest Analytics community of India` # 4. Return first word from string. # result: `AV` # Done string = input('Enter something: ') print(string[:2])
73bb85c2b0ddb1b71fd7d9495dee92ff2afa1a22
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/9_functional_programming/HW9/hw_2.py
1,325
4.375
4
# In English, the present participle is formed by adding the suffix -ing # to the infinite form: go -> going. A simple set of heuristic rules can # be given as follows: If the verb ends in e, drop the e and add ing # (if not exception: be, see, flee, knee, etc.) # If the verb ends in ie, change ie to y and add ing For...
d3742a6a3c4b0c3488e9a933ae3ed0e67e4cb538
YuriiKhomych/ITEA-BC
/Andrii_Ravlyk/8_files/practise/pr_1.py
1,287
3.9375
4
# Practise ''' 1. Write a version of a palindrome recogniser that accepts a file name from the sys.argv, reads each line, and prints the line to the screen if it is a palindrome and write results to file like {source_name}/{result}.''' import sys sys.path.append("E:/Python/ITEA/ITEA-BC/Andrii_Ravlyk/8_files/practise/"...
3f2566abf3dc5144058177b9ed8ec52799b9fd87
YuriiKhomych/ITEA-BC
/Sergii_Davydenko/4_iterations/practise1.py
224
4.1875
4
# Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. # Note : Use 'continue' statement. # Expected Output : 0 1 2 4 5 for i in range(0, 6): if i == 3: continue print(i, end=", ")
2edb0b06caf01ff2ec134e1f8589b12ecc867fe6
YuriiKhomych/ITEA-BC
/Sergey_Naumchick/7_Collections/PR/PR_07_05.py
710
4.90625
5
'''5. Rivers: Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be `'nile': 'egypt'`. * Use a loop to print a sentence about each river, such as The Nile runs through Egypt. * Use a loop to print the name of each river included in the dictionary. ...
1e5219c1cecf48ea3ca21ebb58ca03930146fb30
YuriiKhomych/ITEA-BC
/Andrii_Ravlyk/5_functions/practise/find_vowel.py
181
3.84375
4
# Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, # False otherwise. def fvowel (s): if s in 'aeyio': return True
651366bcb1dcb9531561fb98c6b288dbbd613960
YuriiKhomych/ITEA-BC
/Vlad_Hytun/3_conditions/hw/HW31_condition-Hytun_Vlad.py
2,614
4.0625
4
# 1. Create car: # # * Use input for get: # * Brand # * Model # * Color # * Year # * Engine volume # * Odometer # * Phone number # * Create rating value for car and increase or decrease at each step # * Check that brand (model, color) not in your favou...
4668c597765daa5ea59e7931bd3ef639c54c5348
YogeshGheu/Mini_Library_Project
/main_code.py
8,335
3.984375
4
from os import system from time import sleep myLibrary_name = input("Enter a Name for Your Library ") system('cls') # the program will start from here print("Before Starting The Library Let's add Some Books, Enter the Book Nmae to add: \ntype 'Done' when you're Done: ") list_books = [] #this is the main list of...
fd4618a6cbfc2fbbbcfce34d3e69adf7a36939ae
kvswim/kjv_cg_da
/pset2/problem_set2/Exercise3/3_1.py
1,811
3.53125
4
#Kyle Verdeyen #Problem set 2, exercise 3, problem 1 #Computational Genomics: Data Analysis #usage: python 3_1.py counts.txt cov.txt import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import sys from sklearn.decomposition import PCA from scipy.stats import pearsonr #load counts.t...
dbdde92e03af346302dfdcb5f1348775bc4185be
scmsqhn/WeixinBot
/wxbot_project_py2.7/test/testqrcode.py
670
3.625
4
# coding=UTF-8 # get all the kind of phone num which is divided as 3-4-4 # check with 3-4 to get the phone's msg from net # with this we can serve the customer better # 17-05-02 haining.qin changhong # ENVIRONMENT: python2.7 # get provider information by phoneNumber import sys import os def run_example(data="http:...
68ce494ba45b514411e892e578d0dafb87a2c927
balogunb/Konane_Game_AI
/game.py
1,748
3.890625
4
class Board: def __init__(self): rows, cols = (8,8) self.grid = [[0]*cols]*rows def print(self): print(self.grid) class Piece: #Color 1 represents black and -1 represents white #position holds the position on the grid def __init__(self, color, position): ...
f74f345a39f001ae90c7535ac61b056903de0c20
AVasK/PyStuff
/func1.py
1,801
3.671875
4
""" Playing with functions. """ """ Each function can have: __annotations__ : dict of annotations (Ex. {'a' : <class 'int'>}) __call__ : implementation of the () operator - callable object protocol __closure__ : tuple containing the closure of function __code__ : byte-code <class 'code'> of func body __defaults__ :...
d63300e59e8140dd180f3d24a31227f19fae14f4
AVasK/PyStuff
/arrays.py
598
3.703125
4
# Arrays: from array import array from random import random f_arr = array('d', (random() for i in range(100))) # 100 floats (d = double) i_arr = array('i', (int(random()*10) for i in range(10))) # 10 ints with open('floats.bin', 'wb') as file: f_arr.tofile(file) # writes to binary file f_arr_2 = array('d'...
31ba2d81d5e61811081fb6b25418fb25ea8e1323
AVasK/PyStuff
/partialApplication.py
1,127
3.765625
4
### If you're willing to partially apply some function ### if you hanker to do some functional programming ### ... from functools import partial, wraps ### Henceforth you can do so ### time to Roll Out Some Haskell examples? from operator import mul mul_2 = partial(mul, 2) print(list(map(mul_2, [1,2,3,4,5]))) list_sq...
94acf49d3c30bd7d8b993b8e33f08141abc7dbc1
Pro1ooEgor/stone-task
/stone_task.py
1,088
3.859375
4
from random import randint from statistics import mean class ImpossibleDivideStones(Exception): pass def stones(n: int): """ :param n: number of stones :return: tuple of two lists (two heaps with divided stones) """ list_of_stones = [] for i in range(n): list_of_stones.append(ra...
2a5cfd2375f9dde72c1051bd1ef71460d7d55dbd
roy-basmacier/LeetCode
/Solutions/70. Climbing Stairs.py
429
3.546875
4
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ # 1 -> 1 # 2 -> 2 # 3 -> 3 # 4 -> 5 1 1 1 1 / 2 1 1 / 1 2 1 / 1 1 2 / 2 2 # 5 -> 8 if n < 3: return n prv = 1 nxt = 2 ...
b709ee4382d78efb6b1165f9cd2614bfb351a58a
roy-basmacier/LeetCode
/Solutions/297. Serialize and Deserialize Binary Tree.py
1,828
3.703125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str ...
2d90b102d9b29ef8bb217c1a770f5d1f04b1a92f
roy-basmacier/LeetCode
/Solutions/725. Split Linked List in Parts.py
1,547
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getSize(self, root): size = 0 ptr = root while ptr: size += 1 ptr = ptr.next return size ...
77e0fcf653069245444d7265922da4eec21d388f
roy-basmacier/LeetCode
/Solutions/1008. Construct Binary Search Tree from Preorder Traversal.py
808
3.921875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ ...
282b753a734bd12c81b23d1da90a64c495f3bfb6
poliwal/DSA-Practice
/Linked List/Reverse Linked List.py
193
3.53125
4
# O(n) time | O(1) space def reverseLinkedList(head): prev, curr = None,head while curr is not None: nextNode = curr.next curr.next = prev prev = curr curr = nextNode return prev
d6aa556b9f9172d4629d5e47d2eab5bb908ac541
poliwal/DSA-Practice
/Recursion/Product Sum.py
309
3.796875
4
# O(N) time ;N is total elements| O(D) space ;D is depth def productSum(array, multiplier = 1): sum = 0 for element in array: if type(element) is list: sum += productSum(element, multiplier + 1) else: sum += element return sum * multiplier print(productSum([5, 2, [7, -1], 3, [6, [-13, 8], 4]]))
8741975241dfbcf3169bc8504b80a6f8cc597be9
poliwal/DSA-Practice
/Strings/Longest Substring Without Duplication.py
489
3.53125
4
# O(n) time | O(min(n,a)) space ;a is number of unique char in string def longestSubstringWithoutDuplication(string): startIndex = 0 longest = [0, 1] lastSeen = {} for i,char in enumerate(string): if char in lastSeen: startIndex = max(startIndex, lastSeen[char] + 1) if longest[1] - longest[0] < i + 1 ...
2520a33b23b8818be0b7e6b6338033f573491a2c
poliwal/DSA-Practice
/Strings/Underscorify Substring.py
1,514
3.578125
4
# O(n + m) time | O(n) space ; m is length of substring def underscorifySubstring(string, subString): locations = collapse(getLocations(string, subString)) return underscorify(string, locations) def getLocations(string, subString): locations = [] startIdx = 0 while startIdx < len(string): nextIdx = string....
41236fb9d1daab0b86640cd5ae076403ae39b6e0
246k/algorithms
/manachersAlgorithm.py
1,092
3.75
4
def manachersAlgorithm(word): maxLength = 0 left = 0 right = 0 start = 0 newWord = "" outputString = "" for i in word[: len(word) - 1]: newWord += i + "|" newWord += word[-1] n = len(newWord) longestPalindromeArray = [0] * n for i in range(n): if(i > right...
e6bc0f5408a6c4bcccf6c5ab27cf8539c595d08a
shailesh/angle_btwn_hrs_min
/angle_btw_hrs_min.py
713
4.15625
4
def calcAngle(hour,minute): # validating the inputs here if (hour < 0 or minute < 0 or hour > 12 or minute > 60): print('Wrong input') if (hour == 12): hour = 0 if (minute == 60): minute = 0 # Calculating the angles moved by hour and minute hands with reference to 12:00 hour_angle, minute_ang...
dea14b7e6b6952774c2df63f8c5a90b635496444
wmak/Notes
/CSC/D84/Assignments/a1/AI_search.py
20,269
3.53125
4
# This is the script that implements the different search algorithms # that you will try with the mouse. # # The algorithms you are responsible for are: # # BFS # DFS # A* search # A* search with cat heuristic # # Read the comments at the head of each function carefully and be # sure to return exactly what is requeste...
d6ed7b9e4e8aaa2061607222168f27c9c1a82a19
ertugrulsagdic/15puzzle
/node.py
452
3.625
4
class Node: def __init__(self, parent=None, state=None, path=None, g=0, h=0): self.parent = parent self.state = state self.path = path self.g = g self.h = h self.f = g + h def __eq__(self, obj): try: if(self.parent == obj.parent and self.stat...
944ce32166b290486a552689218c565ef9a0893e
ertugrulsagdic/15puzzle
/astar_heuristic_bonus.py
2,695
3.5625
4
from node import * import math # the number of steps to take with without diagonal move - the number of steps saved using diagonal move def heuristic_diagonal_distance(puzzle): diagonal_distance = 0 d1 = 1 d2 = 3 for x in range(0, puzzle.number_of_rows): for y in range(0, puzzle.number_of_col...
a179660b294bdd3b9c64d83185e4fdbd7ac32b68
roman322/algorithm
/lab3/gamesrv.py
2,037
3.546875
4
import heapq # створюється граф class Graph(object): def __init__(self, vertices=None, client_vertices=None): self.vertices = vertices or [] self.client_vertices = client_vertices or set() # зчитування def read_graph(fl): vertex_count, edge_count = [int(tok) for tok in fl.readlin...
0c0e8160198d922e0be5d80d207258bdb091bbdf
Sharatgm/neural-network-implementation
/neuralNetwork.py
18,633
3.53125
4
import random import math from csv import reader import numpy as np from random import randrange import matplotlib.pylab as plt # global variable to store the errors/loss for visualisation __errors__ = [] # Load a CSV file def load_csv(filename): dataset = list() with open(filename, 'r') as file: csv...
0021e305037992731bdc891d8d6bf4bd35d227bd
vwang0/causal_inference
/misc/pi_MC_simulation.py
737
4.15625
4
''' Monte Carlo Simulation: pi N: total number of darts random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where roun...
f391340953675e637a74ca5ac0473961f4e69b38
yukikokurashima/Python-Practice
/Python3.2.py
542
4.1875
4
def calc_average(scores): return sum(scores) / 5 def determine_grade(score): if 90 <= score <= 100: result = "A" elif 80 <= score <= 89: result = "B" elif 70 <= score <= 79: result = "C" elif 60 <= score <= 69: result = "D" else: result = "F" return result scores = [] for _ in range(5): score = int...
487bf483dd975fd2fd590aca8145779c8b118ac2
luisjimenez6245/escom
/teoría/practicas/automata-grapher/Panel.py
1,727
3.65625
4
from tkinter import Tk, Canvas, Frame, BOTH import math class Panel(Frame): canvas = None width_stroke = 1 fill = "#ffffff" outline = "#000000" def __init__(self, title = ""): super().__init__() self.canvas = Canvas(self) self.pack(fill=BOTH, expand=1) self.canvas....
2838f9c31f1b93456e419be6abdcef11ef3d6933
skidmarker/Lamborghini
/programmers_고득점_Kit/정렬/가장큰수.py
699
3.65625
4
def solution(numbers): numbers = list(map(list, map(str, numbers))) for number in numbers: if len(number) == 1: number.append(int(number[0])) number.append(int(number[0])) number.append(int(number[0])) elif len(number) == 2: number.append(int(numbe...
e81978e2d5a9cd562e79a0b19ce76388f4515db8
skidmarker/Lamborghini
/programmers_고득점_Kit/스택_큐/프린터.py
636
3.640625
4
def solution(priorities, location): sorted_priorities = sorted(priorities, reverse=True) queue = [] for i in range(len(priorities)): temp = [priorities[i], False] # 우선순위, 요청 여부 if i == location: temp[1] = True queue.append(temp) order = 1 while queue: now_...
af450facf6de92adfd674b7472a69e9120a4ff0d
dnivra26/advent_of_code_2018
/Day2/main.py
504
3.640625
4
from collections import Counter file = open("input.txt", "r") count2 = 0 count3 = 0 def two_three(counter): two = False three = False for _, obj in enumerate(counter): if counter[obj] == 2: two = True if counter[obj] == 3: three = True return two,three for line...
84bb39bd27c78e84cc63fe7109607d80ad9b312a
Pooja-Kush/Python-Training
/training.py
215
4.09375
4
"""print('Hi') thislist = ["apple", "banana", "cherry"] for x in thislist: print(x)""" """x = 5 for i in range(1, 11): result = x * i output = '{} * {} = {}' print(output.format(x, i, result))"""
bfa2b53ea2e91a6a6988fb5d1f571bfd956cf8cb
EstevamPonte/Python-Basico
/PythonExercicios/mundo1/ex008.py
114
3.5625
4
n1 = int(input('Digite uma medida: ')) print('Metro {}, centimetro {}, milimetro {}'.format(n1, n1*100, n1*1000))
89bbd5a5b7c05eaa471954f562d33d8bf04024ba
EstevamPonte/Python-Basico
/PythonExercicios/mundo2/ex038.py
332
4.125
4
primeiro = int(input('digite um valor: ')) segundo = int(input('digite um valor: ')) if segundo > primeiro: print('o numero {} é maior que o numero {}'.format(segundo, primeiro)) elif primeiro > segundo: print('o numero {} é maior que o numero {}'.format(primeiro, segundo)) else: print('Os dois numeros sao...
8361b34d8fa36143caded5f301a1507fdad003c5
EstevamPonte/Python-Basico
/PythonExercicios/mundo1/ex027.py
240
3.703125
4
nome = str(input('Digite seu nome completo: ')).strip() lista = nome.split() print('Prazer em te conhecer!!!') print('Seu primeiro nome é {}'.format(lista[0])) tamanho = len(lista) - 1 print('Seu ultimo nome é {}'.format(lista[tamanho]))
b284c3081026da619eb9f634ecb9d3df723e9e01
kNosek1618/if_-_while
/boolean_check.py
300
4.0625
4
while 1<2: if bool == 1: bool == False else: bool == True if bool == True: print("Jeżeli prawda, to znaczy, że program widzi zmienna") bool = int(input()) else: print("W takim razie skoro fałsz (0) to znaczy, że tak jak by zmiennej nie było") bool = int(input())
9dd87e60d9a5a1093b056f91bcbad14fa87c0a76
saathvik2006/learning_python
/Functions/len_of_word.py
147
4
4
def length_of_word(word): len_word=len(word) print (len_word) return len_word input_word=input("What is your word? ") length_of_word(input_word)
214bb8c674f63fbb0f18582fc991a0f869e7e084
adityaalifn/CSH3L3-Machine-Learning
/Linear Regression/Quiz/Univariate/new_linier.py
280
3.625
4
import pandas as pd import matplotlib.pyplot as plt import numpy as np from math import sqrt def mean(val): return sum(val) / float(len(val)) def covariance(x, x_mean, y, y_mean): covar = 0.0 for i in range(len(x)): covar += (x[i] - x_mean) * (y[i] - mean_y)
435b42c6946277df30947069bdf071ff21c60448
yaksas443/SimplyPython
/days.py
415
4.34375
4
# Source: Understanding Computer Applications with BlueJ - X # Accept number of days and display the result after converting it into number of years, number of months and the remaining number of days days = int(raw_input("Enter number of days : ")) years = days / 365 rem = days % 365 months = rem / 30 rem = rem % ...
84de10dc2d5e896f46cb6733d06c0f3cccc49ad5
yaksas443/SimplyPython
/SPSE/listfiles.py
399
3.9375
4
#!/usr/bin/env python # Program to recursively list files and directories from a given path import os import sys path = sys.argv[1] def lsfile(dir,path,level): dr = '' if level==0: print "-"*level + dir dr = dir else: dr = path+'/'+dir for item in os.listdir(dr): print "--" * (level+1) + " " + item ...
b659ec2d05bbcc676a3a9eed647941edddb48601
yaksas443/SimplyPython
/sumfactorial.py
443
4.21875
4
# Source: https://adriann.github.io/programming_problems.html # Write a program that asks the user for a number n and prints the sum of the numbers 1 to n # To convert str to int use int() # to concatenate int to str, first convert it to str def sumFactorial(number): count = 0 sum=0 for count in range(0,number): ...
e776357808c77e059dd7293781cb445472b85fb0
Marlon-Poddalgoda/ICS3U-Unit6-01-Python
/random_average.py
742
4.03125
4
#!/usr/bin/env python3 # Created by Marlon Poddalgoda # Created on January 2021 # This program prints 10 random integers and finds the average import random def main(): # This function prints 10 random integers and finds the average print("This program prints 10 random integers and finds the average.") ...
c7f18555c75c076f7d6f56aae3dec35f3a871a53
mariavarley/PythonExercises
/pyweek4.py
210
3.9375
4
#!/usr/bin/python num = int(input("Please Enter a number\n")) a = range(1, num+1) b = [] for i in a: if num%i == 0: b.append(i) print("{0} is a list of all numbers divisors of {1}".format(b, num))
87fd6a86c8de17dbbcdedc073a6c5c7c4b19d396
mariavarley/PythonExercises
/pyweek2.py
428
4.15625
4
#!/usr/bin/python num = int(input("Please Enter a number\n")) check = int(input("Please Enter a number to divide with\n")) if num%4 == 0: print("The number is divisible by 4") elif num%2 == 0: print("The number is an even number") else: print("The number is an odd number") if num%check == 0: print("The nu...
bca3a78b6ee4b68f4efc0ca71186e9299121bd90
Sav1ors/labs
/Bubble_Sort.py
384
4.15625
4
def bubbleSort(list): for passnum in range(len(list)-1,0,-1): for i in range(passnum): if list[i]>list[i+1]: temp = list[i] list[i] = list[i+1] list[i+1] = temp list = [] for i in range(int(input('Enter the number of list items\n'))): list.app...
5583f207692b634c29e29c61594356f79c969eeb
balram-github/Data-structures-and-algorithms
/algorithms/recursion/Josephus problem.py
530
3.65625
4
#!/usr/bin/python3 a = [1,2,3,4,5,6,7] b = [i for i in range(len(a))] print('a => {0}'.format(a)) print('b => {0}'.format(b)) i = 0 while len(b) !=1: print('Starting iteration') print('b => {0}, length => [{1}], i => [{2}]'.format(b, len(b), i)) j = (i+2)%len(a) print('j => [{0}]'.format(j)) prin...
69f9f3b5397d4cb06c3c116c3b9d4849e98ef95a
balram-github/Data-structures-and-algorithms
/algorithms/introduction/modInverse.py
177
3.734375
4
#!/usr/bin/python3 def modInverse(a,m): ##Your code here for i in range(1, m+1): mi = -1 if (i*a)%m ==1: return i%m return mi
374aa317355cf6ddc6316324ba03e394f9355aba
houhailun/data_struct_alrhorithm
/demo/algo_demo.py
8,098
3.828125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Time: 2020/9/17 13:35 # Author: Hou hailun class Search: def __init__(self, nums): self.nums = nums self.found = False def sequence_search(self, key): for ix, num in enumerate(self.nums): if key == num: self.fou...
4c685a4f1eea894289594dfd0c65f1e85946d29d
houhailun/data_struct_alrhorithm
/demo/algo_code.py
9,801
4.21875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Time: 2021/3/11 10:22 # Author: Hou hailun # 算法之排序 class Sort: # 排序类 def __init__(self): self.data = [10, 6, 12, 7, 9, -1, 20, 45] def bubble_sort(self): # 冒泡排序 # 思想:两两对比,把小的放到前面 # O(N*N) 稳定排序 原址排序 arr = self.data.cop...
50a79abfe8edfd39098e630e8f4bcc20297ee973
houhailun/data_struct_alrhorithm
/data_struct/linklist.py
2,496
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Time : 2019/6/27 17:27 @Author : Hou hailun @File : linklist.py """ print(__doc__) class Node: """节点类""" def __init__(self, data): self.data = data # 数据域 self.next = None # 指针域 def get_next(self): return self.next d...
3236d85a8d9be174c004830efb8812848dd4dc0e
TejeshReddy25/py
/tt.py
166
3.546875
4
n=int(input()) a=bin(n) print(a) for i in range(2,len(a)): if str(i)==0: a.replace('0','1') else: a.replace('1','0') print(a)
20afa8841d87b6833b8cf9b671ae2d4c8c8dc49c
juliokn/cs50_solutions
/lab6_tournament.py
2,520
3.921875
4
# Simulate a sports tournament import csv import sys import random # Number of simluations to run N = 1000 def main(): # Ensure correct usage if len(sys.argv) != 2: sys.exit("Usage: python tournament.py FILENAME") teams = [] with open(sys.argv[1]) as file: # we read each row of the...
a8281b00b34d4c2f3d5f888641cefa79976d9a39
agnese-tagliavini/agneselibrary
/mymath.py
576
3.703125
4
#This module implement some simple math operations: import numpy as np #-------MYCEIL_DIV2 -> take an integer number and return the ceiling of its division by 2 def myceil_div2(i): return i/2 + i % 2 #-------MYFLOOR_DIV2 -> take an integer number and return the floor of its division by 2 def myfloor_div2(i): ...
17b504c56f12ebf99f55f944c16cb4b05c5adbf3
mraligorithm/Python_AliGorithm
/Linked_Lists/SIngly_linked_list/singly_linked_list.py
1,381
4
4
""" What are singly linked lists? In this tutorial, we will learn about what singly linked lists are and some very basic operations that can be performed on them. Before we get into the details of what singly lists are, we must learn what nodes are. This is because nodes are the building blocks of a linked list. A nod...
98972ef0c9d53086cb8ea770022e885d8818f691
mraligorithm/Python_AliGorithm
/Data_type_based_tasks/Array/py_files/anagram/array_sequence_anagram.py
1,656
4.09375
4
""" Anagram Check Problem Given two strings, check to see if they are anagrams. An anagram is when the two strings can be written using the exact same letters (so you can just rearrange the letters to get a different phrase or word). For example: "public relations" is an anagram of "crap built on lies." "clint east...
10adb1d374723b220b4c0acd3a86a4e1970d3e18
mraligorithm/Python_AliGorithm
/Data_type_based_tasks/String/py_files/unique_characters.py
1,047
3.984375
4
""" Problem Given a string,determine if it is compreised of all unique characters. For example, the string 'abcde' has all unique characters and should return True. The string 'aabcde' contains duplicate characters and should return false. Solution We'll show two possible solutions, one using a built-in data structure...
a6f184a06ee68bd80ca668cece2de32a1aecda13
nitinb/Codes
/wuforums/modulo.py
434
3.796875
4
def calculate_modulo(base, exponent, modulo): result = 1 while exponent != 0: if exponent % 2 == 1: result *= base % modulo exponent /= 2 base *= base % modulo return result % modulo print calculate_modulo(2004, 2005, 10) print calculate_modulo(17, calculate_modulo(17...
14463192bc5cfae7c64b1a2b51f70936baa358e0
OverDEdge/Dungeon-Keep
/monster.py
1,503
4.09375
4
""" This file defines the Monster class. Each Monster object has: Health, Attack, Defence and Agility stats which help in monster encounters """ # The stats are defined in the dictionary STATS where: # - MONSTER_STATS[0] = Health # - MONSTER_STATS[1] = Attack # - MONSTER_STATS[2] = Defence MONSTER_STATS = ...
498ee8a0fd8f8341b060b8b8ed124a40c87bbf2d
OverDEdge/Dungeon-Keep
/maproom.py
831
3.828125
4
"""Map Room class""" from room import * class MapRoom(Room): def __init__(self, doors): super(MapRoom, self).__init__(doors) self.chest = True self.chest_open = True self.chest_item = 'map' def enter(self, player): # Do special stuff for MapRoom in case of ...
002f1664870e65b7af04a5acff31a80cee466c9d
OverDEdge/Dungeon-Keep
/bossroom.py
3,096
3.6875
4
"""Boss Room class""" from room import * from sys import exit class BossRoom(Room): def __init__(self, doors): super(BossRoom, self).__init__(doors) self.boss_door = True self.monster = Dragon(random.choice(list(BOSS_STATS.keys()))) def enter(self, player): # Do ...
6288a20ab83e0aad77bec51609da5ebf4219f570
heejung-gjt/Blackjack
/blackjak.py
3,869
3.765625
4
# -*- coding: utf-8 -*- import random FACES = list(range(2, 11)) + ['Jack', 'Queen', 'King', 'Ace'] SUITS = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] class Card: def __init__(self, face, suit): assert face in FACES and suit in SUITS self.face = face self.suit = suit def __str__(sel...
7db900dc028400fb0d3537ac6269dec0f47c3732
kate-brushkova/first_project
/my_module.py
1,531
3.75
4
class Test: @staticmethod def show(): print('Hello') def oleh(age=30): return age def get_age_oleh(age_oleh): return oleh(age=age_oleh) print(get_age_oleh(31)) class Person: def __init__(self, name, surname): self._name = name self._surname = surname @property ...