blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8f216d33db488c5474fb36a0e7afb396ee2e9b1f
eganjam/MOOCs
/Coursera_UniversityOfMichigan_PythonForInfomatics/02b_OpenFileAndCountMostFrequentWords.py
851
4.375
4
# script to open a file and extract the most frequent word name = raw_input("Enter file: ") # upon prompt press enter to use the mbox file if len(name) == 0: name = "mbox-short.txt" # use try and except as a failsafe try: handle = open(name) except: print "This file cannot be opened" exit() # read t...
4a8af3fe96c8284c7d079c001f7fddcf544687e1
Atomice/PSU
/CS350/HashTable.py
1,355
3.8125
4
#! /usr/bin/env python class HashTable(): def __init__(self,length): self.table = [] self.length = length for i in xrange(self.length): self.table.append([]) def modhash(self,string): """string input is len(9), this is the basic op""" sum = 0 for i i...
6764dea00746f72d04326b643b1ea01952f6ca1e
Gilles00/Secured-WhatsApp
/socket_client.py
1,519
3.828125
4
import socket def Mai(): host='Enter the host ip here'#enter the host ip here port=9090 s=socket.socket() s.connect((host,port)) print('connecting...........') while True: name=input("Enter your name : ") name=name.encode() s.send(name) name=name.decode() if name: ...
6a895cd69931291f371803b6ed23b998785a291a
HeatherMurphy/pythonTests
/turtleDesign_2.py
727
3.75
4
import turtle x=5 #distance defined t=0 #tilt defined c= 0 #cursor position defined lateral c2= 0 #cursor position defined vertical t=0 #defining tilt turtle.hideturtle() turtle.penup () turtle.speed (20) turtle.pencolor('red') turtle.pensize(3) turtle.bgcolor('gray') while (x < 400): turtle.fillcolor('orange') ...
580d33979d6fcd8fcf05b17fa4c27c2910e7fa0b
ohadzr/SetGame
/Logic/Deck.py
677
3.515625
4
from Card import Card, CARD_FEATURES import random class Deck(object): """ A Deck class - create, shuffle and draw cards """ def __init__(self): self.reset_deck() def reset_deck(self): self.cards_array = [] for color in CARD_FEATURES["colors"]: for shape in CA...
7558d5e832000ad734167cdbbc9340cc261bc52f
ALMR94/Practicas-python-6
/1 - Lista de cierto número de palabras.py
512
4.28125
4
# -*- coding: cp1252 -*- """Antonio Li Manzaneque- 1 DAW - Prctica 6 - Ejercicio 1 - Escribe un programa que permita crear una lista de palabras. Para ello, el programa tiene que pedir un nmero y luego solicitar ese nmero de palabras para crear la lista. Por ltimo, el programa tiene que escribir la lista.""" a=(int...
2648c1c162fc6634c95501eaf08bfc2cdd5d1cc8
Ticonderoga/CoursInfoL2
/Factorielle.py
258
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 29 17:00:18 2020 @author: phil """ def factorielle(n): if n==1 : return 1 else : return n*factorielle(n-1) if __name__ == "__main__": print(factorielle(10))
6c55f0f2599edde63674ac79d0d745e2fa3979da
nim118/bioinformatics-python
/algorithmic-heights/majority_element.py
675
3.984375
4
#Problem Url http://rosalind.info/problems/maj/ def findMajorityElement(arr): n = len(arr) maxCount = 0 index = -1 for i in range(n): count = 0 for j in range(n): if(arr[i] == arr[j]): count += 1 if (count > maxCount): maxCount = count index = i if (maxCount > n//2): return (arr[index]) el...
ea4b329b4b631c6f6ebb86f1de8177f41f392f58
nim118/bioinformatics-python
/python-village/variables_and_some_arithmetic.py
700
3.75
4
# Problem Url : http://rosalind.info/problems/ini2/ # Code to print Addition of square root of 2 numbers. import sys class Variable: #Function for addition of square root of 2 numbers. def addition(self, a, b): return a**2 + b**2 #Driver Code. if __name__ == "__main__": # Code to read data from t...
4d71f5bcc86c4fce21642109e7d609ce64ea828c
junior1407/PythonCodes
/macaco safado.py
1,059
3.578125
4
def busca1(lista, start, end, altura): if start > end: return "X" if start == end: if lista[start] >= altura: return "X" return lista[start] mid = (start + end) // 2 if end - start == 1: mid += 1 if lista[mid] >= altura: return busca1(lista, start,...
75ac2db4f29d3a851071fb90a536e07f76e0de56
kwondohun0308/Beakjoon
/2439.py
192
3.578125
4
a=int(input()) for i in range(a): b = a - (i+1) for j in range(a): if b > 0: print(' ',end='') else: print('*',end='') b-=1 print()
2ea5540d5b879ecdc8dd11ebf514ed6a086850a0
kwondohun0308/Beakjoon
/2.py
328
3.734375
4
count = 0 def my_len(): while True: try: if a[count]: count += 1 except: break a = input("단어 길이를 알고싶은 단어를 입력하시오: ") print(len(a)) print(my_len()) print(arr[::-1]) for i in range(len(a)): print(a[len(a)-i-1],end = '')
636bef53c8d2a5edacb039b4afd218370ae0ac45
kwondohun0308/Beakjoon
/2292.py
116
3.53125
4
N = int(input()) bee_nums = 1 count = 1 while N > bee_nums: bee_nums += 6 * count count += 1 print(count)
c28427131c3b261ae3b76320fcfe89d3234d550f
RobertMoralesO/clase_python_ia_2021_2
/clase_dos.py
2,739
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 6 19:02:43 2021 @author: robertomorales """ # Condicionales # Tabla de Verdad # Tabla del and # v and v = v # v and f = f # f and v = f # f and f = f print(True and True) # True print(True and False) # False print(False and True) # False prin...
55dd2adb461018939fa03daa45bdf17b66ef4b7c
cckuqui/budget-elections-exercise
/election_results.py
1,550
3.78125
4
# Modules import os import csv # Set path for file csvpath = os.path.join ("Resources/election_data.csv") # Open file with open(csvpath, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") next(csvreader) # Empty dictionary to save values from csv file candidates = {} # Save values of...
a067999911fbcc931bd3ceae170c159b19c98684
romi37/dtc-academy
/ifelse.py
489
3.921875
4
condition = True # operator pembanding # < > <= >= == != # and or not if condition: pass else: pass if condition: pass elif condition: pass else: pass while (0<1): pass while (0<1): pass else: pass lists = ["python", "java", "golang", "html", "php", "javascript"] for data in lists:...
a6ecf05cfe550fd9f48ea7c8a41986df317b5dd7
bhaskarv/LearnPython
/loops1.py
512
4.21875
4
courses=['Hist','Comp','Math','Social'] #itereate over the list for item in courses: print(item) #get index while iterating use enumerate function for index,course in enumerate(courses): print('{} : {}'.format(index, course)) #default index is 0, we can specify explicit value for index to start at print("Same lis...
5fa30bdc896aea2b927487541e253b582c892c52
bhaskarv/LearnPython
/tuples.py
555
4.40625
4
#tuples are like immutable lists they can't be modified list_1=['History','Maths','Physics','CompSci'] list_2=list_1 print(list_1) print(list_2) list_1[0]='Arts' #As can be seen below, adding to list_1 changed list_2 as well print(list_1) print(list_2) #now take a look at a tuple touple_1=('History','Maths','Phisi...
eb2aa177db75604c5f1cff2c872add0e873b009d
czchuang/hackbright_intro
/quiz_functions.py
504
4.125
4
#function that converts hours, minutes, and seconds into seconds and returns the answer in seconds def convert_to_seconds(hours, minutes, seconds): hours_to_seconds = hours / 120 minutes_to_seconds = minutes/60 time_seconds = hours_to_seconds + minutes + seconds return time_seconds #function that converts feet an...
372ddb2dbe33a56b8bafb30ca35c0f6857f8b985
RnoldR/gym-grid2D
/gym-grid2D/tests/test-app.py
1,347
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 21 21:03:29 2019 @author: arnold """ import numpy as np import random class Test(): def __init__(self): self.MAZE_H = 10 self.MAZE_W = 5 self.maze_size = (self.MAZE_W, self.MAZE_H) self.STATUS = {'Wall': 1} ...
17f591411f4c301cb53ba80b7e3209f49380cbe2
liguohua-bigdata/learn_python
/course01/c003.py
127
3.625
4
a = 10000 # 当语句以冒号“:”结尾时,缩进的语句视为代码块。 if a >= 0: print(a) else: print(-a)
dce84a1fc00b971df8aa428b451b4fe2586d4f1a
liguohua-bigdata/learn_python
/course01/c006.py
502
4.3125
4
# 可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量 a = 123 # a是整数 print(a) a = 'ABC' # a变为字符串 print(a) # Python提供了ord()和chr()函数,可以把字母和对应的数字相互转换: print(ord('A')) print(chr(65)) # Python在后来添加了对Unicode的支持,以Unicode表示的字符串用u'...'表示 print(u'中文') # 字符串转码 print(u'ABC'.encode('utf-8')) print(u'中文'.encode('utf-8'))
d8fed2edd6f3219dc80b28cdff1c48b8376f8d88
liguohua-bigdata/learn_python
/course01/c020.py
1,276
4.0625
4
# 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。 import os print("*******************") l = list(range(1, 11)) print(l) # 如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做? print("*******************") L = [] for x in range(1, 11): L.append(x * x) print(L) print("*******************") L = [x * x for x in range(1, ...
d89ae792503990493c9788ce0ac948c0fe5e2d66
parshuramsail/PYTHON_LEARN
/paresh25/a4.py
155
4.15625
4
#WRITE A PROGRAM THAT PRINTS ALL THE NMBERS FROM 0 TO 6 EXCEPT 3 AND 6 for x in range(6): if (x==3 or x==6): continue print(x) print("\n")
6bce60ed95085c3b77389accb52de3922445c8df
parshuramsail/PYTHON_LEARN
/paresh40/s-t-r-r-i-g-s.py
172
3.9375
4
#x='hello world' #y=x.upper() #print(y) #x='hello world' #y=x.lower() #print(y) #x='hello world' #y=x.split() #print(y) #x='this is a string' #y=x.split('i') #print(y)
0d69ac2499a10408c26aa71c372eee4039856722
parshuramsail/PYTHON_LEARN
/paresh23/a1.py
223
3.75
4
#def function1(a,b): # print('hello') c=int(input("enter a number:")) d=int(input("enter a number:")) def function2(a,b): average=(a+b)/2 # print(average) return average v=function2(c,d) print(v)
dbecf486419618aa4bc2983d16aa414a7b9a5bf3
parshuramsail/PYTHON_LEARN
/paresh26/a11.py
150
4.15625
4
#ZIP mylist1=[1,2,3] mylist2=['a','b','c'] mylist3=[100,200,300] for item in zip(mylist1,mylist2,mylist3): print(item) list(zip(mylist1,mylist2))
c705ff0a6eee00c79eadd7d2b45933e2d99e049d
parshuramsail/PYTHON_LEARN
/paresh34/a3.py
107
3.5
4
def add_sub(x,y): c=x+y d=x-y return c,d result1,result2=add_sub(10,5) print(result1,result2)
88fc34858e3e5604a94b017ea318b532c1afac9b
parshuramsail/PYTHON_LEARN
/paresh27/a3.py
159
4.3125
4
#USE A LIST COMPREHENSION TO CREATE A LIST OF ALL NUMBERS BETWEEN 1 TO 50 THAT ARE DIVISIBLE BY 3. for num in range(0,51): if num%3==0: print(num)
0bab30fe82fbe3e0ac7fa147726635295557f2fd
parshuramsail/PYTHON_LEARN
/paresh25/a10.py
108
3.953125
4
def mul(numbers): total=1 for x in numbers: total*=x return total print(mul((8,2,-1,)))
63024a9d98b9cbbba3fd4eae3104d560d01e9760
moneypi/python_study
/python_study/pandas_csv/test.py
292
3.5
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Feb 17 09:28:51 2019 @author: luke """ import pandas as pd data = [{'a,"': 1, 'b': 2},{'a,"': 5, 'b': 10, 'c': 20}] df = pd.DataFrame(data) print df df.to_csv('out.csv') df2 = pd.read_csv('out.csv',index_col = 0) print(df2)
5ae96e39a423be6aefdd660a988c1cccd9286d3c
peterkabai/python
/algorithm_problems/hackerrank_kattis/campus_walk.py
787
3.875
4
#! /usr/bin/python3 import fileinput import sys from simple_graph import * line_num = 0 places = [] edge_pairs = [] num_places = None from_place = None to_place = None for line in fileinput.input(["campus_walk_in_2.txt"]): line = line.rstrip("\n") if line_num == 0: from_place = line e...
0c3b77a21f3f509c3d6cff5ae689b0227bdefe5b
peterkabai/python
/algorithm_problems/helpers/min_span_tree.py
2,751
3.53125
4
def count_v(edges): seen = [] v = 0 for edge in edges: if edge[0][0] not in seen: seen.append(edge[0][0]) v += 1 if edge[0][1] not in seen: seen.append(edge[0][1]) v += 1 return v def edges_to_dict(edges, directed=True): graph = {} ...
63a8687367e5869d8aa04d1697266233231b9403
peterkabai/python
/algorithm_problems/sorts/radix.py
738
4.03125
4
def radix(arr): for place in range(len(str(max(arr)))): temp = []; for i in radix_util(arr, place+1, [[],[],[],[],[],[],[],[],[],[]]): for j in i: temp.append(j); [print(x, end=" ") for x in temp]; print() arr = temp return arr def radix...
befbba68faba85ecbf477f3b118e8776471a9920
peterkabai/python
/algorithm_problems/helpers/grids.py
4,512
3.765625
4
import dijkstra class Point(object): def __init__(self, r, c): self.r = r self.c = c def __str__(self): return str(self.r) + " " + str(self.c) class Pair(object): def __init__(self, f, t): self.f = f self.t = t def read_grid(d): grid = [] for r in range(d)...
7ba5530907754ded0708a609161e0d72651f93b2
peterkabai/python
/algorithm_problems/hackerrank_kattis/guess_the_number.py
409
3.875
4
#! /usr/bin/python3 # https://csumb.kattis.com/problems/guess guess_num = 1 guess = 500 low = 1 high = 1000 while guess_num <= 10: print(guess) response = input() if response == "lower": high = guess-1 guess = round((high + low) / 2) elif response == "higher": low = guess+1 ...
e8f21d2809c1f68461c57675d10720399389f569
peterkabai/python
/algorithm_problems/hackerrank_kattis/min_max_heaps.py
2,886
3.65625
4
#! /usr/bin/python3 class max_heap(): data = [] def size(self): return len(self.data) def max_lookup(self): return self.data[0] def insert(self, value): self.data.append(int(value)) length = len(self.data) for index in range(length, -1, -1): self.h...
e5fee46b9edd013216bbddfeee54e10f07c1a28c
peterkabai/python
/algorithm_problems/sorts/merge_sort.py
1,512
3.65625
4
#! /usr/bin/python3 import fileinput from collections import deque line_num = 0 input_list = [] for line in fileinput.input(["input_output/merge_sort_in_0.txt"]): line = line.rstrip("\n") if line_num != 0: input_list.append(line) line_num += 1 def mergeSort(arr): size = 1 while size <...
de1267f8745567fb2a08c77cc4ecb79cd8d00c1f
rolinawu/Small-Projects-PPfromATBSWP
/practice17Nov.py
1,257
3.890625
4
import pprint message = 'It was a bright cold day in ldhjfjkhdajflwkjfkl' count={} for char in message: count.setdefault(char, 0) # ensure the key is in the count dictionary count[char] = count[char] +1 pprint.pprint(count) # prints prettily pprint.pformat(count) # prints it into a string #objective orientati...
a897eb6dfbaef9c9b8c730ade99dbeb0441a3d63
nakulcr7/algorithms
/sorting/countingsort.py
528
3.703125
4
def counting_sort(nums): bookkeeping_array = [0] * (max(nums) + 1) sorted_nums = [] for num in nums: bookkeeping_array[num] += 1 for num, freq in enumerate(bookkeeping_array): sorted_nums.extend([num] * freq) return sorted_nums def main(): try: assert counting_sort([1, ...
631e422ddfa1e7ff2f9df49d731815214bdd1dee
ryndovaira/leveluppythonlevel1_300321
/topic_07_oop/examples/1_my_class.py
1,398
4.0625
4
# Синтаксис: # class <Person>(<Persons>): # statements class Person: # количество созданных людей count = 0 # поле класса # вызов функции print на класса print('Привет! Этот класс уже определен!') # Конструктор (фабрика, которая создаёт экземпляры) def __init__(self, n, a): #...
d6f107c40390e8cdcaff09172a13a3a7e8d32608
ryndovaira/leveluppythonlevel1_300321
/topic_02_syntax/examples/11_for_else.py
303
3.78125
4
for i in 'hello world': # if i == 'a': if i == 'o': print(f'Буква {i} в строке есть') break else: # попадем в else если не было break print('Буквы a в строке нет') # Буквы a в строке нет print("I'm here!")
dd85748c946b1c08da893e5ec607a4424414f7e1
ryndovaira/leveluppythonlevel1_300321
/topic_07_oop/practice/class_1_3_book_aggregation.py
2,920
4.125
4
from topic_07_oop.practice.class_1_1_page import MyPage class Book: """ Класс Книга Поля: страницы, название (каждое слово с большой буквы, остальные маленькие), автор, год издания Методы: добавить страницу в конец, добавить несколько страниц в конец, ...
7862fb289b4e50f586e495231d4d314c1d749837
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/practice/list_2_magic_parts.py
1,542
3.921875
4
""" Функция magic_parts. Принимает 1 аргумент: список my_list. Возвращает список, который состоит из [первые 2 элемента my_list] + [последний элемент my_list] + [количество элементов в списке my_list]. Пример: входной список [1, 2, 'aa', 'mm'], результат [1, 2, 'mm', 4]. (Порядок проверки именно такой:) Если вмест...
a21a9cf05a906696c9b602c26f2c7674289ce9a9
ryndovaira/leveluppythonlevel1_300321
/topic_02_syntax/practice/tests/loop_3_count_even_num_test.py
620
3.625
4
import pytest from topic_02_syntax.practice.loop_3_count_even_num import count_even_num params = [ (1.23, "Must be int!"), (-1.34, "Must be int!"), ("5", "Must be int!"), (True, "Must be int!"), (-5, "Must be > 0!"), (0, "Must be > 0!"), (1, 0), (2, 1), (4, 1), (10, 1), (11...
acc54f3db16788ca4762a8a70d984d890095d85e
ryndovaira/leveluppythonlevel1_300321
/topic_08_functions/examples/19_args_default_concat.py
206
3.734375
4
def concat(*args, sep="/"): return sep.join(args) ex1 = concat("earth", "mars", "venus") print(ex1) # earth/mars/venus ex2 = concat("earth", "mars", "venus", sep=".") print(ex2) # earth.mars.venus
3a7565fc3139c0c52dc08e9324bef867375c0853
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/practice/dict_1_get_numbers_by_name.py
1,697
3.984375
4
""" Функция get_numbers_by_name. Принимает 2 аргумента: словарь содержащий {имя: [телефон1, телефон2], ...}, слово (имя) для поиска в словаре. (Порядок проверки именно такой:) Если вместо словаря передано что-то другое, то возвращать строку "Dictionary must be dict!". Если вместо строки для поиска передано ч...
857e667e6edf1acfc6cecf7b86aeb482cf74027c
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/hw/generator_2_dict_pow2_start_stop_step_if_div3.py
836
3.703125
4
""" Функция dict_pow2_start_stop_step_if_div3. Принимает 3 аргумента: числа start, stop, step. Возвращает генератор-выражение состоящий из кортежа (аналог dict): (значение, значение в квадрате) при этом значения перебираются от start до stop (не включая) с шагом step только для чисел, которые делятся на 3 без остатка...
3e9bbb8280eced0d2803212f1245cf67f34f41dc
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/examples/4_dict.py
1,582
4
4
print('\n--------------------------------------- Introduction --------------------------------------------------------') # Создание пустого словаря empty_1 = {} empty_2 = dict() # Синтаксис описания словаря: список пар ключ: значения в фигурных скобках через запятую d = {1: 'one', 2: 'two', 3: 'three'} print(d) # {1:...
519521fdedbf24a360676ba5fe557c483b1b9a54
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/examples/9_generator_expression.py
1,857
3.53125
4
# Генератор нельзя писать без скобок — это синтаксическая ошибка import itertools gen_exp = (f'{key}: {value}' for key, value in zip(range(100), 'abcdefghijklmno')) print(list(gen_exp)) # ['0: a', '1: b', '2: c', '3: d', '4: e', '5: f', '6: g', ...] # Нельзя распечатать элементы функцией print() print(gen_...
2606ab19b89d9e7b0d49d7f20072a087d933a1b5
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/practice/zip_2_name_mark.py
1,561
4.03125
4
""" Функция zip_name_mark. Принимает 2 аргумента: список с именами и список с баллами. Возвращает список (list) с парами значений из каждого аргумента, если один список больше другого, то заполнить недостающие элементы строкой "!!!". Подсказка: zip_longest. (Порядок проверки именно такой:) Если вместо списков пере...
0f0f77e3e2d98cc1cbadcafe306e7ca57028851e
ryndovaira/leveluppythonlevel1_300321
/topic_09_enum/examples/5_enum_with_auto_methods.py
802
4.09375
4
from enum import Enum, auto # класс Animal - это перечисление class Animal(Enum): # элементы перечисления, константы (не изменяются) # элементы имеют имена и значения # функция auto() автоматически присваивает элементу значение от 1 до N-1 с шагом 1 cat = auto() # 1 dog = auto() # 1 + 1 = 2 ...
ad8d349ee0ed04a229cb55d818c87183dc55843f
ryndovaira/leveluppythonlevel1_300321
/topic_05_data_structure/examples/3_set.py
2,537
3.953125
4
print('\n--------------------------------------- Introduction --------------------------------------------------------') # Синтаксис описания множества: список значений в фигурных скобках через запятую ex1 = {1, 2, 3} print(ex1) # {1, 2, 3} # Для определения пустого множества необходимо явно вызвать конструктор # Это...
57b8ebc2c19acae87e166d22b13c0c055a1eeff6
shivam-2003/python_tutorials
/exercises/basics/atm_emulator/atm.py
8,774
3.78125
4
# Flow author's name: S. Maladkar # Flow author's github: https://github.com/srushti-maladkar # # Flow of the code: # ----------------- # # Welcome message # Enter the card # Language selection - English, Hindi, Marathi # Enter Pin # Verify Pin # Show Menu - Withdraw, Change Pin, Check balance # Withdraw - Saving, Cu...
d8b10c57d65cc7539c2b7d4a0c39c112c1313d10
deepti2200/LovePython
/ex2.py
463
3.96875
4
print "I will not count my chickens." print "Hens", 25 + 30/ 6 print "Roosters", 100 - 25 * 3%4 print "Now I will count the eggs" print 3 + 2 +1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 -7 ? " print 3 + 2 < 5 - 7 print " what is 3 + 2?", 3+2 print "what is 5 - 7?", 5 - 7 print "oh, taht's wjy it's Fals...
e0d02513886328fb4590e94d5df4e21432bc2a6e
maryoohhh/leetcodelearn
/Array/even-digits.gyp
949
4.21875
4
# Find numbers with even number of digits # Example 1: # Input: nums = [12,345,2,6,7896] # Output: 2 # Explanation: # 12 contains 2 digits (even number of digits). # 345 contains 3 digits (odd number of digits). # 2 contains 1 digit (odd number of digits). # 6 contains 1 digit (odd number of digits). # 7896 conta...
32351a34e380379c1118e7d1031e49a969ba2327
Himnish/Google-Foobar-Challenge
/solution2.py
213
3.5
4
def solution(s): # Your code here right=0 salutes=0 for l in s: if(l=='>'): right+=1 if(l=='<' and right>0): salutes += 2 * right return salutes
15634309d5edbf6683f57d8204ec9985e1b60875
leanton/6.00x
/Midterm2/P7-1.py
503
3.53125
4
import random def sampleQuizzes(): grade = [] gradepass = [] mid1 = range(50, 81) mid2 = range(60, 91) final = range(55, 96) for i in range(10000): pm1 = random.choice(mid1) pm2 = random.choice(mid2) pf = random.choice(final) grade.append(pm1 * 0.25 + pm2 * 0.25 ...
ab3c4024517c0fd9f11efe59749b806e10b4ce80
leanton/6.00x
/Week 9/Psets/L15P3.py
427
3.765625
4
def stdDevOfLengths(L): if len(L) == 0: return float('nan') sdev = 0.0 s = [] for word in L: s.append(len(word)) mean = sum(s)/len(s) for num in s: sdev += (num - mean)**2 return (sdev/len(s)) print stdDevOfLengths(['a', 'z', 'p']) print stdDevOfLengths(['apples', 'oranges', 'kiwis', 'pineapples']) print ...
512212bb98670da1bed44110397dee74f01bd7e9
leanton/6.00x
/Week 5/ProblemSet5/recursion.py
491
4.40625
4
def reverseString(aStr): """ Given a string, recursively returns a reversed copy of the string. For example, if the string is 'abc', the function returns 'cba'. The only string operations you are allowed to use are indexing, slicing, and concatenation. aStr: a string returns: a reversed...
5769adfaccef2277aa896717a6d765a0158b2202
leanton/6.00x
/Week 8/Psets/L14.py
1,008
4.09375
4
import random def noReplacementSimulation(numTrials): ''' Runs numTrials trials of a Monte Carlo simulation of drawing 3 balls out of a bucket containing 3 red and 3 green balls. Balls are not replaced once drawn. Returns the a decimal - the fraction of times 3 balls of the same color were dra...
1e98f28ad68d538c1e0ff2b6bf270c28d3875af2
cowboybebophan/LeetCode
/Solutions/049. Group Anagrams.py
1,013
4.0625
4
""" First, we creat a empty dictionary to store the answers: keys are the elements of the strings, values are the anagrams. The tuple function gets the strings' components: tuple("aab") = ("a","a","b"); We used the sorted function to make sure that anagrams like "aab" and "baa" are sorted into the same key ("a","a","...
60a3dcbe06051353c5359c6940b91d9dbebcc7ec
cowboybebophan/LeetCode
/Solutions/200. Number of Islands.py
1,849
3.71875
4
""" Using recursive DFS: We use two for-loop to iterate all the elements in grid If the element is '1', we mark it as '#'(any other symbol will be fine) so we know that we have already visited here. Then we explore the four neighbor elements: up/down/left/right to see if they are '1's. Return when we reach the edges ...
e94ab260bb5a2f3f59b148f51e6ba55c552ae0f4
cowboybebophan/LeetCode
/Solutions/240. Search a 2D Matrix II.py
970
4.25
4
""" We start search the matrix from top right(or bottom left) corner, initialize the current position to top right(or bottom left) corner, if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than t...
a4aba456e8989a8a3b52ae047bc9dc39115271b7
cowboybebophan/LeetCode
/Solutions/872. Leaf-Similar Trees.py
940
3.78125
4
# Iteratively class Solution: def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool: return self.findLeaf(root1) == self.findLeaf(root2) def findLeaf(self, root): if not root: return [] res = [] stack = [root] while stack: node = sta...
c77d72e75eddc708fddb586182e23d13aabb3b8f
cowboybebophan/LeetCode
/Solutions/126. Word Ladder II.py
934
3.65625
4
""" https://leetcode.com/problems/word-ladder-ii/discuss/40482/Python-simple-BFS-layer-by-layer """ class Solution: def findLadders(self, beginWord, endWord, wordList) -> List[List[str]]: res = [] wordList = set(wordList) alpha = string.ascii_lowercase layer = {beginWord:[[beginWord]...
5605dae0dbc4abebe4f9d7ad27e64b6abf3d397c
cowboybebophan/LeetCode
/Solutions/022. Generate Parentheses.py
1,346
3.9375
4
# DFS + Recursion class Solution: def generateParenthesis(self, n: int) -> List[str]: res = [] self.dfs(n, n, res, '') return res def dfs(self, left, right, res, path): if left: self.dfs(left - 1, right, res, path + '(') if left < right: self...
3d7be1ce3f34a58bec65e79fa7c12520b9c33dd8
cowboybebophan/LeetCode
/Solutions/~1019. Next Greater Node In Linked List.py
548
3.53125
4
# similar to 503 and 739 class Solution: def nextLargerNodes(self, head): res, stack = [], [] # Be carefule here, do Not initialize like this: res = stack = [] # because res and stack points to the same reference and they will change together as [] changes. while...
ab2d15179d5c327e6b36b9405bcab72039a2363a
cowboybebophan/LeetCode
/Solutions/648. Replace Words.py
1,552
3.75
4
# Brute Force class Solution: def replaceWords(self, dict: List[str], sentence: str) -> str: dict = set(dict) def replace(word): for i in range(1, len(word)): if word[:i] in dict: return word[:i] return word retur...
a50f958e0d3707a40c9087a0814ccd5b0fd18974
juhyun0/python_except
/multiple_except2.py
428
3.515625
4
my_list=[1,2,3] try: #문제가 없을 경우 실행할 코드 print("첨자를 입력하세요:") index=int(input()) print(my_list[index]/0) except ZeroDivisionError as err: #문제가 생겼을 때 실행할 코드 print("0으로 나눌 수 없습니다, ({0})".format(err)) except IndentationError as err: #문제가 생겼을 때 실행할 코드 print("잘못된 첨자입니다. ({0})".format(err))
c44f20e7f1afcbae11ae68bfcd1a53267568595c
evargashe/EDA-Laboratorio-B-
/Python/bubbleSort.py
202
3.734375
4
def bubbleSort(a): for i in range(0,len(a)-1): for j in range(len(a)-1): if(a[j]>=a[j+1]): aux=a[j] a[j]=a[j+1] a[j+1]=aux
5bb7a7b9c30afb945f045ff4b17f3bd1bd6a0fda
JehyeonHeo/learn_machine_learning
/outliers/outlier_cleaner.py
958
3.765625
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
392d22242f3fcb982a9163687b394cfb9b29568c
AndreySperansky/TUITION
/TIME/time_exe_code.py
1,390
3.78125
4
# Разворот строк рекурсивным методом from sys import argv from time import time nontrivial_rev1_call = 0 # counts number of calls involving concatentation, indexing and slicing nontrivial_rev2_call = 0 # counts number of calls involving concatentation, len-call, division and sclicing length = int(argv[1]) def r...
5aff92d27fe78a6b6f1e25b9f290a1f4fbeda11a
AndreySperansky/TUITION
/IO_/Byte/byte_actions.py
257
3.859375
4
s = 'Hello, World!' sb = b'Hello, World!' print(s[1]) print(sb[1]) # Полуаем код буквы е # e # 101 print(s[1:3]) print(sb[1:3]) for item in sb: print( item) # 72 # 101 # 108 # 108 # 111 # 44 # 32 # 87 # 111 # 114 # 108 # 100 # 33
f2f741a0bc26850c6c8af0f53b7486f03ca641fb
AndreySperansky/TUITION
/SORTING/Insertion/insert_sorting.py
1,054
3.96875
4
"""СОРТИРОВКА ВСТАВКАМИ""" from random import randint def insertion_sort(nums): # Сортировку начинаем со второго элемента, т.к. считается, что первый элемент уже отсортирован for i in range(1, len(nums)): item_to_insert = nums[i] # Сохраняем ссылку на индекс предыдущего элемента j = i ...
080743db9f70fa17742dc507dc9d499590adf162
AndreySperansky/TUITION
/EXCEPTION/Try_Except_Else_Finally/try_exept_2.py
474
3.875
4
try: x = int(input("Введите целое число x (для вычисления 1/x): ")) res = 1 / x print("1/{} = {:.2f}".format(x, res)) except: print("Произошла ошибка!") # -------------- # Примеры вывода: # Введите целое число x (для вычисления 1/x): 3 # 1/3 = 0.33 # Введите целое число x (для вычисления 1/x): qwert...
753fd59377e0678ad9bed8c6f26a28e0e132c61a
AndreySperansky/TUITION
/_STRUCTURES/DICT/Dict_Gen/dict_value_sum.py
390
4.0625
4
incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00} # Это - list comprehension total_income = sum([value for value in incomes.values()]) print(total_income) #14100.0 #Это выражение-генератор (generator expression) total_income = sum(value for value in incomes.values()) print(total_income) total_inco...
48d67a316cfaf0fadfcf57c0c2c477b95c20325f
AndreySperansky/TUITION
/COMPREHENSION/List_Comprehension/IF_comprehension/if_gen_1.py
486
3.96875
4
""" hw_4_3 """ """Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку. Подсказка: использовать функцию range() и генератор.""" my_list = [x for x in range(20, 240) if x % 21 == 0 or x % 20 == 0] print(my_list) # [20, 21, 40, 42, 60, 63, 80, 84, 100, 105, 120, 1...
d295d21695ba030dfe258deb851916f4a1dd2091
AndreySperansky/TUITION
/SORTING/SORT( )/sort_6.py
567
3.546875
4
from collections import Counter, deque def foo(s): # Считаем уникальные символы. # Counter({'e': 4, 'b': 3, 'p': 2, ' ': 2, 'o': 2, 'r': 1, '!': 1}) count = Counter(s) # Сортируем по возрастанию количества повторений. # deque([('r', 1), ('!', 1), ('p', 2), (' ', 2), ('o', 2), ('b', 3), ('e', 4)]) ...
f3d49fdcbc7209999bce8c973d785e9ccb5970db
AndreySperansky/TUITION
/SORTING/Bubble/bubble_sorting2.py
536
3.625
4
"""Сортировка массива метдом пузырька -2 """ """Реализация спомощью цикла for""" from random import randint n = int(input("Введите длинну массива: ")) mas = [] for i in range(n): mas.append(randint(1,100)) print(mas) print(" ") for i in range(n - 1): for j in range(n - i - 1): if mas[j] > mas[j ...
443c7b2cc689fe067c028913a1bc61cb1456a401
AndreySperansky/TUITION
/SORTING/Bubble/bubble_sorting_4.py
560
3.890625
4
"""Сортировка массива метдом пузырька -4 """ """Реализация спомощью функции""" from random import randint def bubble(array): for i in range(n - 1): for j in range(n - i - 1): if array[j] > array[j + 1]: buff = array[j] array[j] = array[j + 1] a...
04b6f45ccdceb05e3409a7a109051f3b7025a7c3
AndreySperansky/TUITION
/ITERATOR_GENERATOR/ITERATOR/Itertools_module/Repeat/repeat_samp.py
236
3.984375
4
import itertools """Функция repeat() строит итератор, повторяющий некоторый объект заданное количество раз:""" for i in itertools.repeat(1, 4): print(i) # 1 1 1 1
050cba8e23f9da24e5101a32c33fe2e037a6de62
AndreySperansky/TUITION
/SORTING/Eratosfen/eratosfen_compact.py
984
3.984375
4
from math import sqrt, ceil # def primes(num): # *a, = range(num) # a[4::2] = [0] * (num // 2 - 2) # for i in range(3, ceil(sqrt(num)), 2): # # начиная i^2 с шагом i зануляем элементы # a[i * i::i] = [0] * len(a[i * i::i]) # # схлопываем нули и выдаем числа начиная с 2 # retu...
799eb7cf13c1be1b643fe417c1887b3248228a77
AndreySperansky/TUITION
/_STRUCTURES/LIST/TRIVIAL/Copy_list/copy_list.py
405
4.1875
4
lst = [1,2,3] ls = lst ls[1] = 200 # Список изменится print(lst) # [1, 200, 3] a = [1,2,3] # Копия с помощью среза b = a[:] b[1] = 200 # Список не изменится print(a) # [1, 2, 3] b = a.copy() b[1] = 200 # # Список a не изменится # Эти способы не будут работать если есть вложенные списки
df9069fa1e9dde827bc713ee83d978a54855b856
AndreySperansky/TUITION
/_STRUCTURES/NUMBER/SUM/MySum/my_sum_1.py
315
3.921875
4
"""Функция суммирует все что будет передано в качестве аргументов""" def mysum(L= None): L=[] or L return 0 if not L else L[0] + mysum(L[1:]) # Трехместный оператор print(mysum([1])) # 1 print(mysum([1, 2, 3, 4, 5, 'a'])) # 15
121f2f911197aee88c67bdc945ff19d5b51f22d0
AndreySperansky/TUITION
/_STRUCTURES/DICT/Trivial/Dict_Iterate/iterate_dict.py
155
4.0625
4
my_dict = {'title': 'Samsung Galaxy', 'price': 20000, 'country': 'China', 'year': '2016'} for key, value in my_dict.items(): print(f"{key} - {value}")
51a8c3cfe40c57eafa52ef52b8520ad570d9df0e
AndreySperansky/TUITION
/_STRUCTURES/DICT/Trivial/Sort/dict_sort_value.py
397
3.875
4
"""Сортировка по значениям""" incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00} def by_value(item): return item[1] for k, v in sorted(incomes.items(), key=by_value): print(k, '->', v) #('orange', '->', 3500.0) #('banana', '->', 5000.0) #('apple', '->', 5600.0) # можно совсем коротко for value in s...
3eef925a5fed0e380b847735820200c9cae07a33
AndreySperansky/TUITION
/COMPREHENSION/Num_comprehension/unique_num.py
3,194
3.921875
4
"""Представлен список чисел. Определить элементы списка, не имеющие повторений. Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования в исходном списке. Для выполнения задания обязательно использовать генератор.""" lst = [1, 2, 7, 4, 9, 5, 6, 2, 5, 2, 9, 3, 3,] print...
c5b466d98e40f9164b51b64a9d04d811bccc3bba
AndreySperansky/TUITION
/_STRUCTURES/NUMBER/SUM/sum_n_mult_of_num.py
414
4.03125
4
""" Сумма и произведение цифр числа c else continue""" a = abs(int(input("Введите целое число: "))) sum = 0 mult = 1 while a > 0: digit = a % 10 sum = sum + digit if digit != 0: mult = mult * digit else: continue a = a // 10 print("Сумма цифр: ", sum) print("Произведение цифр: ", mu...
58bc0439443cdf84763b245ad443b455d1794b94
AndreySperansky/TUITION
/_STRUCTURES/Modul_Collection/Counter/ex_1.py
1,594
3.953125
4
"""collections - Высокопроизводительный контейнер типов данных""" """Collections — это встроенный модуль Python, реализующий специализированный контейнер типов данных. Является альтернативой встроенным контейнерам общего назначения Python, таким как dict, list, set и tuple.""" """Класс collections.Counter()""" from...
c70291b6c4687b7c25574e2c244e966f935f8530
AndreySperansky/TUITION
/RECURSION/Super_Recursion/task_7/task_7_1_1.py
338
3.78125
4
# Второй вариант def cycle_method(num): m = 0 s = 0 for i in range(1, num + 1): s += i m = num * (num + 1) // 2 print(f'Равенство {s == m}') try: NUMB = int(input("Введите число: ")) cycle_method(NUMB) except ValueError: print('Ошибка, нужно ввести целое число!')
6ed53345f6cf4ae4247acf6cbdbb91c63dbafa60
AndreySperansky/TUITION
/EXCEPTION/RAISE/raise_mid_num.py
1,098
4.09375
4
""" Задание 9. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого). Подсказка: можно добавить проверку, что введены равные числа """ NUM_A = None NUM_B = None NUM_C = None while not isinstance(NUM_A, float) or not isinstance(NUM_B, float) or not isinstance(NUM_C, float...
9007016c392c3661650e7451df5bf3840f539394
AndreySperansky/TUITION
/RECURSION/Super_Recursion/task_8/task_8_1.py
1,195
3.9375
4
""" 8. Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры. Пример: Сколько будет чисел? - 2 Какую цифру считать? - 3 Число 1: 223 Число 2: 21 Было введено 1 цифр '3' ЗДЕСЬ ДОЛЖНА БЫ...
9fec272a43eabcd09c75923055c3734079d2d7fb
AndreySperansky/TUITION
/_STRUCTURES/DICT/Trivial/Find/find_item_upon_item.py
470
3.625
4
x = [ {'Car': 'Honda', 'id': 12}, {'Car': 'Mazda', 'id': 45}, {'Car': 'Toyota', 'id': 20} ] # Вариант1 desired_val = None for item in x: if item['id'] == 20: desired_val = item break print(desired_val) # {'Car': 'Toyota', 'id': 20} # Вариант2 foo = lambda x: next(i for i in x if i['id'] == 20) print(foo(x)) #...
4c57b51bf5f2f096c532bdd00b641e78201559d2
AndreySperansky/TUITION
/EXCEPTION/RAISE/raise_letter.py
1,317
3.796875
4
""" Задание 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. Пример: Введите номер буквы: 4 Введёному номеру соответствует буква: d Подсказка: используйте ф-ции chr() и ord() """ MIN = 1 MAX = 26 # try: # NUM_A = int(input(f"Введите целое число от {MIN} до {MAX}: ")) # if not MIN <= NUM_...
6f71dcc1069b207e8490667501ac491cc3f24db7
AndreySperansky/TUITION
/Types/Type_CheckUp/type_checkup.py
355
3.78125
4
my_str = 'Ура!' if isinstance(my_str, str): print('Да, это строка') num = 1.3 if isinstance(num, (int, float)): print('Да, это число') else: print('Вы ыыели не число!') num = 'c' if isinstance(num, (int, float)): print('Да, это число') else: print('Вы ввели не число!')
35f4fd18cda4d804d11e415704db9a5f3da4c501
AndreySperansky/TUITION
/MATRIX/snowflake.py
1,023
4.0625
4
"""Дано нечетное число n. Создайте двумерный массив из n×n элементов, заполнив его символами "."(каждый элемент массива является строкой из одного символа). Затем заполните символами "*" среднюю строку массива, средний столбец массива, главную диагональ и побочную диагональ. В результате единицы в массиве должны образо...
af94c27ce63f32d6f8b5fbff1fefc677f1809333
AndreySperansky/TUITION
/COMPREHENSION/List_Comprehension/inner_list_gen.py
597
3.53125
4
my_lst =[[0 for j in range(4)] for i in range(4)] print(my_lst) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] """Но если число 0 заменить на некоторое выражение, зависящее от i (номер строки) и j (номер столбца), то можно получить список, заполненный по некоторой формуле.""" my_lst1 =[[i * j for j in ra...
96383585ce73b9cdcd6c00d746475bc407289c08
AndreySperansky/TUITION
/SORTING/SORT( )/sort_2.py
408
3.734375
4
# 2. Сортировка с помощью собственной функции a = [4, 10, 43, 300, 54, 289, 34, 8, 749,] def f(x): return x%10 print(sorted(a, key = f)) # [10, 300, 43, 4, 54, 34, 8, 289, 749] def f(x): return -(x%10) print(sorted(a, key = f)) # [289, 749, 8, 4, 54, 34, 43, 10, 300] def f(x): return x%10, x//10%10 print(sorted(...
0b016bc0ad167c9551c8d2d16ec45bfe20797c50
AndreySperansky/TUITION
/_STRUCTURES/SORT/sorting_up_n_down.py
689
4.0625
4
import random #подключаем модуль генератора n1 = int(input('Введите нижнюю границу массива=')) n2 = int(input('Введите верхнюю границу массива=')) kolvo = int(input('Введите количество элементов массива= ')) if kolvo < 2: print ('Задано мало элементов') else: a = [random.randrange(n1, n2) for i in range(kol...