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
79624bb3e51c62c90e355eab0e29591bd1cbdf22
AshaS1999/ASHA_S_rmca_s1_A
/ASHA_PYTHON/17-02-2021/CO1Q3a.py
181
3.828125
4
list1=[1,-4,2,-8,8,-2,-43,87,-378,-756,244,-667] pos=list() for i in list1: if i>0: pos.append(i) print('Original list:',list1) print('Positive integer list:',pos)
d7f536b5654e29a431238f19f3b8efcc93c35440
AshaS1999/ASHA_S_rmca_s1_A
/ASHA_PYTHON/3-2-2021/q3sum of list.py
224
4.125
4
sum = 0 input_string = input("Enter a list element separated by space ") list = input_string.split() print("Calculating sum of element of input list") sum = 0 for num in list: sum += int (num) print("Sum = ",sum)
48dcf7ecbe7d8761756704c15b08f729520ffdb4
joshuastay/Basic-Login-Code
/login.py
2,942
4.3125
4
import re class LoginCredentials: """ Simple login authentication program includes a method to create a new user stores values in a dictionary """ def __init__(self): self.login_dict = dict() self.status = 1 # method to check if the password meets parameters...
94ad8a32977dd2f3bb3bf2355538f2f0f08e70fd
Joshua-Igoni/Budget-app
/main.py
14,311
3.5625
4
import random Food_budget = globals() Entertainment_budget = globals() Clothing_budget = globals() Business_budget = globals() Food_budget = 1000000 Entertainment_budget = 1000000 Clothing_budget = 1000000 Business_budget = 1000000 SelectionOptions = ["1. Food budget", "2. Entertainment budget", ...
05cdb85f116d2d9e8f11e0073c658bd30ff26dc8
Minhwa-Shin/Data-analysis-and-visualization-for-machine-learning
/pandasMappingEx.py
486
3.59375
4
import pandas as pd data=pd.DataFrame({'food':['bacon','pulled pork','bacon','Pastrami','corned beef', 'Bacon','pastrami','honey ham','nova lox'], 'ounces':[4,3,12,6,7.5,8,3,5,6]}) print(data,'\n') meat_to_animal={ 'bacon':'pig', 'pulled pork':'pig', 'pastrami...
6bac9aa6ff85a2b1f259cfb3b848b2ac3bece73a
vikcui/roman_integer_conversion
/integer_to_roman.py
2,186
4
4
# author : YANG CUI """ Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 """ def integer_to_roman(num): """ :param num: the input intege...
fcadc4bf5c706994b3e516b3754e443ebbb5fe88
Benson1198/Practice-Problems
/Hash Map(Dictionary)/Non-repeated Elements.py
292
3.578125
4
def printNonRepeated(arr,n): dict1 = {} res = [] for i in arr: dict1[str(i)] = 0 for i in arr: if str(i) in dict1: dict1[str(i)] += 1 for i in arr: if dict1[str(i)] == 1: res.append(i) return res
df30cf6b0af198562b8096708e89b58388030922
Benson1198/Practice-Problems
/Linked Lists/Detect loop in LL(GFG).py
254
3.59375
4
def detectLoop(head): marker1 = head marker2 = head while marker1 != None and marker2.next != None: marker1 = head.next marker2 = head.next.next if marker1 == marker2: return True return False
ca3b76ac439ff4d8c434ca4a4b237437d0967b3e
Benson1198/Practice-Problems
/Trees/Lowest Common Ancestor.py
331
3.53125
4
def lca(root, n1, n2): if (not root): return if root.data == n1: return root elif root.data == n2: return root left = lca(root.left, n1, n2) right = lca(root.right, n1, n2) if left and right: return root return left if left is not None...
f909b83ceaacf1b9aecd6d177078807e755ea3f0
Benson1198/Practice-Problems
/Linked Lists/Reverse LL.py
242
3.859375
4
def reverseList(self): if self.head is None: return None prev = None curr = self.head while curr is not None: nxt = curr.next curr.next = prev prev = curr curr = nxt self.head = prev
e54b1ffa6eae7cd93f6a974bfb9d7a4cfce1ef0a
Benson1198/Practice-Problems
/Trees/Binary Tree and Methods.py
3,764
4.1875
4
# Simple Binary Tree Implementation class Node: def __init__(self,key): self.left = None self.right = None self.val = key root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) # 1 # / \ # 2 3 # / \ / \ # ...
37da947c1f62fc992678a42e71226de7656ad31e
siyagowda/Music-Quiz
/Main Code.py
5,164
3.890625
4
#importing libraries import csv import random import time #logging in global name name = input("Enter name: ") password = input("Enter password: ") if name.lower() == "siya" and password.lower() == "watermelon": print("Login successful") login = True #if name and password match, then user can play ...
264ec10f279ad449b24767e8bbd729acd2db9144
Dostoievski/projet-algo-num-5
/src/integration.py
3,246
3.53125
4
# -*- coding:utf-8 -*- import numpy as np import scipy as sp import pylab as mp #------------------------------------------------# # FUNCTIONS WITH NUMBER OF POINTS : # #------------------------------------------------# def rectangle_method_left(f, a, b, n): """returns the integral values of f be...
ddb298c36cea5550ebc3b1132f52b556d97000a9
renecruz/prog_ii
/python/2.2 Algoritmos de Ordenamiento/burbuja/BurbujaMejorada.py
414
3.671875
4
import numpy as np datos = np.array([8,5,3,9,1]) print ("Arreglo original: " + str(datos)) for recorrido in range(0, datos.size - 1, 1): # range(inicio, fin, incremento) for indice in range(0, datos.size - 1, 1): if (datos[indice] > datos[indice + 1]): # Intercambio buffer = datos[indice] datos[indice] ...
7d2bb2021573b869f232f1fe365aaa1c42dc6705
renecruz/prog_ii
/python/1.1 Herencia Simple y Modificadores de acceso protegidos/1.1.2 Modificadores/PersonaV4Test.py
1,355
3.875
4
class PersonaV4: # atributos privados (su nombre inicia con dos guiones bajos) __nombre = "" __edad = 0 __estatura = 0.0 def getNombre(self): return self.__nombre def setNombre(self, nombre): if not nombre: self.__nombre = "Indefinido" print("Nombre vacio, verifique") els...
122addb28d5f13854eca172d0be609d3369bea70
Combatd/Intro_to_Algorithms_CS215
/social_network_magic_trick/stepsfornaive.py
470
4.1875
4
# counting steps in naive as a function of a def naive(a, b): x = a y = b z = 0 while x > 0: z = z + y x = x - 1 return z ''' until x (based on value of a) gets to 0, it runs 2 things in loop. 2a we have to assign the values of 3 variables 3 ''' def time(a): # ...
94361c77c55bcc618bb53a56b56fb32b2be0d5a5
Ankuraxz/Python_lessons
/Class2.py
1,406
3.96875
4
"Hello World!" print(" Hello world") 10 10.09 09.89 # Single Line Comment """ Multi Line Comment abcdefgh kk kkk """ # spacing and stuff print("Hello \nWorld") print("Hello \tWorld") print("Hello \aWorld") # Audio in C/Cpp #print() # Print FXN print("Hello World") a =9.0 b =9 print(a) print(type(a)) print...
302d53c14cee430b52efce2b91ca2fad0755052f
luoyaodong/wetlandDataProcess
/indi/src/relationship/plantsRelationDaoImpl.py
2,560
3.546875
4
#coding=utf-8 import mysqlConnector #创建数据表 #cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") #插入一条数据 #cur.execute("insert into student values('2','Tom','3 year 2 class','9')") #修改查询条件的数据 #cur.execute("update student set class='3 year 1 class' where name = 'Tom'") #删除查...
7fcf77ee6651bb69fd40ade5f29fc1f4d26aa5f0
jpisano99/ta_adoption_r5
/my_app/func_lib/create_customer_order_dict.py
667
3.90625
4
def create_customer_order_dict(my_rows): # # Takes an unordered list of rows (order_rows) # Returns an order_dict: {customer_name:[[order1],[order2],[orderN]]} # If we wanted to sort on customer name my_rows.sort(key=lambda x: x[0]) # order_dict = {} for my_row in my_rows: customer =...
c34531fab11142ceea6a4ec8cfbe91689bc6571f
Isaac-Muscat/Programming-Experience-and-Resources
/CV_Soduko_Solver/soduko_solver.py
1,145
3.703125
4
from math import floor def valid(board, x, y, digit): #target number at x, y num = digit #check horizontal for j in range(len(board[x])): if(board[x][j] == num): return False #check vertical for i in range(len(board)): if(board[i][y] == num): return False #check box box_x = floor(x/3) box_y = flo...
ad652984c8e5d95f326d27bb029038ea8dfdbd4d
DanilWH/Python
/python_learning/chapter_07/09_counting.py
707
4.03125
4
current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number) # Вместо того чтобы полностю прерывать выполнение цикла без выполнения оставшеёся части кода, можно воспользоватся командой continue. # Команда continue приказывает Python проигнориро...
59a9cf71935a635e7f37e718f27125d96762c6c6
DanilWH/Python
/python_learning/chapter_09/b_homework_restaurant.py
2,435
3.765625
4
class Restaurant(): """Выводит информацию о ресторане""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): """Выводит два атрибута""" print(self.restaurant_name.title() + " will treat you " + self...
260744768b1c302eec33ad2c3e43067d58e5b925
DanilWH/Python
/python_learning/chapter_08/05_formated_name.py
1,577
3.875
4
def get_formatted_name(first_name, last_name): """Возвращает аккуратно отформатированное полное имя.""" full_name = first_name + " " + last_name return full_name.title() musician = get_formatted_name('danil', 'lomakin') print(musician) # Команда return передаёт значение из функции в строку, в которой эта функц...
c37f4b3c3f89b20df2ccd18e7440957b966e8564
DanilWH/Python
/python_practice/my_projects/welcome_to_rectorant.py
7,722
3.875
4
main_menu = ['pasta', 'buckwheat porridge', 'rice', 'cabbage', 'tea', 'coffee', 'compote', 'salad', 'sandwich', 'meat'] available_toppings = ['meat', 'salad', 'tea', 'rice', 'cabbage', 'pasta'] requested_toppings = {} admin_password = '3410' def cancel_actions(): while True: cancel = input('Cencel all entere...
9aa087aa6908d34984bbd2d677d7d79714bc6a21
DanilWH/Python
/python_learning/chapter_07/01_parrot.py
319
3.8125
4
message = input("Tell me something, and i will repeat it back to you:")# Скажи мне что-нибудь, и я повторю это тебе print(message) # input()приостонавливает программу и ждёт пока пользоватеь не введёт входные данные.
8cc1714a8dc9eec441fd09b4c2d4ea6a1d09c95e
DanilWH/Python
/python_practice/my_projects/game.py
897
3.796875
4
from random import randint while True: first = randint(1, 100) number = input("Я згадал число от 1 до 100, попробуй отгадать его: ") if number == 'выход': break while True: if number != 'выход': number = int(number) if number < first: number = input("Слишком ма...
3decdd658967d2b09143b1c2f533c859768d1047
DanilWH/Python
/python_learning/chapter_04/7_players.py
2,255
3.640625
4
playels = ['danil', 'sasha', 'tony', 'dasha', 'galya'] print(playels[0:3]) # Чтобы вывести первые три элемента списка, нужно запросить индексы с 0 по 3. playels = ['danil', 'sasha', 'tony', 'dasha', 'galya'] print(playels[1:4]) # ^ второй индекс идёт по порядку, я так понимаю, о сдвиге беспокоиться...
ede4a22d12ac5bbe8344eb3efae08540b55eb6be
DanilWH/Python
/python_learning/chapter_10/10_number_reades.py
547
3.6875
4
import json filename = 'numbers.json' with open(filename) as file_object: numbers = json.load(file_object) print(numbers) # Функция json.load() используется для загрузки информации из numbers.json; эта информация сохраняется в переменной numbers. # Модуль json позволяет органицовать простейший обмен данными ...
c48bb022b2cb1601304e9ab2620ca73c4e7bd9b7
DanilWH/Python
/python_practice/my_python_studies/format_str.py
3,110
4.09375
4
text = 'Hello, {name}!'.format(name='Danil') print(text) text = "Name: {name}\t Age: {name}'у '{age} лет\n".format(name='Danil', age=16) print(text) # Примеры форматирования именованных параметров. info = "Name: {0}\t Age: {1}\n".format('Danil', 16) print(info) # Пример форматирования параметров по позиции. ...
79f604e3630dfbd6c44de96b19af190da3cf89de
DanilWH/Python
/python_practice/my_projects/registration_v2.py
1,199
3.9375
4
def registration(users): while True: name = input("Your name: ") if name in users.keys(): print("This name is exists! Try again!") continue else: break while True: password = input("Your password: ") password_one = input("Enter passwor...
d1f6df40d9b9e98c30e9249b734f55ae661bd83d
DanilWH/Python
/python_practice/my_projects/registration.py
2,657
4
4
# В дальнейшем заного, с самого начала сделать программу для регистрации. import json def registration(users): f_n = False f_p = False while not f_n: name = input("What is your name:") # Проверка выхода. if name == 'q': break elif name in users.keys():...
3e2eb4ccff52c80dc375ab15319ef06f4956147d
DanilWH/Python
/python_practice/tutorial_projects/easy_game.py/bullet.py
1,258
3.671875
4
import pygame class Bullet(): def __init__(self, screen, settings, character): self.screen = screen self.direction = character.direction # Инициализация направления пули. self.circle = pygame.Rect(0, 0, settings.radius * 2, settings.radius * 2) # Назначение к...
dc2548a01ffe00712f061bacc07beed65894f07f
DanilWH/Python
/python_learning/chapter_05/8_homework_colors(amusement_park.py
3,043
4
4
alen_color = 'green' if alen_color == 'green': print('You have earned 5 points!') # Работающая версия программы. # Первое задание упражнения 5-3. alen_color = 'yellow' if alen_color == 'red': print('You have earned 5 points') # Не работающая программа. # Второе задание упражнения 5-3. alen_color = 're...
d1395fbe39aeb7d9ef547e7a1f4fb08b1bc16fce
DanilWH/Python
/python_learning/chapter_05/9_homework_hello_anmin.py
2,372
3.890625
4
users = ['danil', 'galya', 'admin', 'dasha', 'anya'] for user in users: if user == 'admin': print("Hello " + user.title() + ", would you like to see a status report?") else: print("Hello " + user.title() + ", thank you for loggin in again.") # Упражнение 5-8. print(' ') users = [] if users: for u...
9cbe09bff9c3914bc61f4124895ca10e25f15374
DanilWH/Python
/python_practice/my_projects/analisys_data/random_walk/random_walk_anim_matplotlib/random_walk.py
528
3.796875
4
from random import choice class RandomWalk(): def __init__(self, num_points=1000): self.num_points = num_points self.last_x = 0 self.last_y = 0 def get_step(self): direction = choice([-1, 1]) distance = choice(list(range(5))) step = direction * distance return step def take_a_step(...
98054bd42409f4590843a25eeaaa10dd18a8e68c
Jester697090/Exc
/exc1.py
212
3.875
4
isNameGot = 0 name = input("Jak się nazywasz?") while isNameGot == 0: if name == "": name = input("Przedstaw się, proszę.") else: print("Witaj, " + name + "!") isNameGot = 1
b896a796ea172a50137208a7f0adefa10194bfd0
javierlopeza/IIC2233-2015-2
/Tareas/T02/clases/ListaLigada.py
2,804
4.15625
4
class ListaLigada: """ Clase que construye una estructura simulando una lista ligada. """ def __init__(self): """ Se inicializa sin elementos. """ self.e0 = None self.largo = 0 def append(self, valor): """ Agrega el valor en un nuevo atributo de la lista. ...
1cdd6d3fcf2260c0a6db28c17f6a59a4fd47e51d
javierlopeza/IIC2233-2015-2
/Actividades/AC03/14632128_14638002_AC03.py
3,729
3.625
4
class Rational(): def __init__(self, numerador, denominador): self.numerador = (self.simplificar(numerador,denominador))[0] self.denominador = (self.simplificar(numerador,denominador))[1] if self.denominador<0: self.denominador *= -1 self.numerador *= -1 def ...
0d4774bacf76419bfb854b6fc529c482cfed2121
javierlopeza/IIC2233-2015-2
/Actividades/AC08/main.py
3,809
3.59375
4
# coding=utf-8 #ESTE DECORADOR FUNCIONA, PERO LA PARTE 2 ME FALLA :( def tipar(*tipos): def revisar(funcion): def revisar_args(*args, **kwargs): cantidad_revisiones = len(tipos) todo_ok = True for i in range(cantidad_revisiones): if not isinstance(args[i...
b13cbcfeb4bf0fad228d0efa9960642c17f8c803
nooneischgl/learning
/netcook/1_1_local_machine_info.py
321
3.625
4
#!/usr/bin/env python3 import socket def print_machine_info(): """Print host_name and IP address""" host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) print("Host Name: %s" %host_name) print("IP Address: %s" %ip_address) if __name__ == '__main__': print_machine_info(...
cbc6636173e39d9738da484e0e051f61676467d7
Fabianexe/Superbubble
/LSD/topological_sorting/__init__.py
1,375
3.84375
4
from LSD.hashed_list import HashedList from math import inf def check_pre(v, g, order): """Check if all predecessors have already been placed.""" if order.index(v) > -2: return False for v2 in g.predecessors(v): if order.index(v2) == -2: return False return True def toposo...
b3c7dc2010decb2da8fa9ac154baf5041a71cc9b
Fabianexe/Superbubble
/LSD/RMQ/__init__.py
1,278
3.59375
4
""" Thise source code is from https://codereview.stackexchange.com/questions/154047/dynamic-programming-based-range-minimum-query And stands so under Creative Commons Licensing """ from itertools import product class RangeQuery(object): """Data structure providing efficient range queries.""" def __init__(se...
c6d4da18d7d7f3a91f53a761ae2dfecfd3851b02
pharaohivan/superhero-team-dueler
/superheroes.py
9,545
4.0625
4
import random from random import choice def divide(): print("----------------------------------------") class Ability: def __init__(self, name, attack_strength): self.name = name self.max_damage = attack_strength def attack(self): '''Calculate the total damage from all ability at...
adf33e80c27c172d589a6c4a6620629590418283
Indre101/code_code
/Pythonprojects/questionM/6.py
165
4.1875
4
while True: n = int(input("Positive number: ")) if n >0: break for j in range(n): for i in range(n): print("#", end="!" ) print()
4c68084467f697ea33315916a854e26d42ca49fb
lucas-dcm/projeto-python
/Projeto Python/ex_02.py
117
3.9375
4
'''Programa para mostrar números digitados''' a = input('Digite um número: ') print ('O número informado é', a)
71ecc3df2bbde3dcae93f5b3eb25e8b40c976a7a
oyvikjo/RushHour
/src/main/python/Solver.py
1,651
3.546875
4
from Board import * import collections from copy import copy import math def solve(board): return level([Solution(board, [])], {board.prettify()}, 500) Solution = collections.namedtuple('Solution', ['board', 'moves']) Move = collections.namedtuple('Move', ['label', 'amount']) def level(to_expl...
fb75df649aa74aa4d578d24ecec2c13394483922
alisonjwong/rosemary.py
/Apple_pie.py
2,991
3.78125
4
from kitchen import Rosemary from kitchen.utensils import Pan, Plate, Bowl, Oven, Fridge, PieDish from kitchen.ingredients import Water, Flour, Salt, Butter, Apple, Sugar, Lemon, Cornstarch, Cinnamon, Egg # Instructions for chocolate chip cookies # Ingredients: Chilled water, 300 grams of flour, a teaspoon salt, 250 ...
b4d6d7e699e58a6f75b1c5e681bc16edb3a2c0c7
raghav4bhasin/Assignment5
/Question8.py
217
4.09375
4
li = [] li2 = [] for i in range (10): num = int(input("Enter a number: ")) li.append(num) num2 = num**2 li2.append(num2) print("List 1: ",li) print("List with squared elements: ",li2)
d890fa2d95cef5d8de081dc2997af2b20a67ed2e
raghav4bhasin/Assignment5
/Question9.py
435
3.828125
4
list1 =[12, 560, "Hello", 111.2, "Gym", 522, 77000, "Food", 3.14, 55.2, 55.5] list_int=[] list_str=[] list_float=[] for i in list1: if(isinstance(i, int)): list_int.append(i) elif(isinstance(i, str)): list_str.append(i) elif(isinstance(i, float)): list_floa...
b11a58dddd58be1b017a148316f277070a71622d
iliucaisi/ProgrammingInPython
/modules/click/demo_1.py
536
3.6875
4
#!/usr/bin/python import click import math import colorama @click.command() @click.argument('x1') @click.argument('y1') @click.argument('x2') @click.argument('y2') def distance(x1, y1, x2, y2): """Calculate the distance between (x1, y1) and (x2, y2)""" click.secho('The distance between (%s, %s) and (%s, %s) is: ' % ...
a7bfed46e9e8d9b9a921abef1c15eeca256428d0
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 3/Problem Set 3/is_letter_available.py
434
3.921875
4
def isLetterAvailable(lettersGuessed, user_letter): ''' lettersGuessed: list, what letters have been guessed so far user_letter: letter guessed by user returns: boolean, True if the letter isn't in lettersGuessed; False otherwise ''' if user_letter not in lettersGuessed: return Tru...
5c3ff785d5fe122e97fe146ba170d1021f8ddb4d
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 3 Estruturas Compostas/Desafios/desafio082.py
556
4.15625
4
number_list = [] even_list = [] odd_list = [] while True: number = int(input('Input a number: ')) number_list.append(number) if number % 2 == 0: even_list.append(number) else: odd_list.append(number) answer = '' while answer != 'Y' and answer != 'N': answer = input('Do yo...
45da33d67b7987d71aa87f486c7b08ba8f52208a
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 2/Problem Set 2/Problem 2 - Paying Debt Off in a Year.py
431
3.796875
4
balance = 4773 annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate/12 initial_balance = balance payment = balance/12 // 10 * 10 while balance > 0: balance = initial_balance payment += 10 for month in range(1, 13): monthly_unpaid_balance = balance - payment balance = monthly_un...
3b2bc129df72b14461452960cf0fff1233a1ff2f
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 1 Fundamentos/Desafios/desafio029.py
387
3.578125
4
velocidade = float(input('\033[4;34;40mQual é a velocidade atual do carro?\033[m ')) if velocidade > 80: multa = (velocidade - 80)*7 print('\033[1;31mMULTADO!\033[m Você excedeu o limite permitido que é de 80Km/h') print('Você deve pagar uma multa de \033[1;4;32mR${:.0f}.00\033[m!'.format(multa)) else: ...
4fa3e7641ca3dcafafd18293a0ad5ec4c0a2a5d7
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 3 Estruturas Compostas/Desafios/desafio079.py
542
3.984375
4
number_list = [] while True: number = int(input('Input a number: ')) if number in number_list: print(f'Number {number} is already on the list. Value not inserted!') else: number_list.append(number) print(f'Number {number} successfully inserted on the list.') answer = '' while...
4a38e180aabadcdb26f7ec2814ae2ae876f9e7a6
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 3/Tuples and Lists/odd_tuples.py
319
4.21875
4
def oddTuples(aTup): ''' aTup: a tuple returns: tuple, every other element of aTup. ''' odd_tuple = () for number, element in enumerate(aTup): if number % 2 == 0: odd_tuple += (element, ) return odd_tuple aTup = ('I', 'am', 'a', 'test', 'tuple') print(oddTuples(aTup))
0027bfd41581f432ea46e506330d446108e0d102
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 2/4. Functions/towers_of_hanoi_b.py
250
3.828125
4
def Tower(n, fr, to, spare): if n == 1: print("Move disk 1 from", fr, "to", to) return Tower(n - 1, fr, spare, to) print("Move disk", n, "from", fr, "to", to) Tower(n - 1, spare, to, fr) n = 3 Tower(n, 'A', 'B', 'C')
53767973f03e32057e984f082335fd30ef731bd8
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 2 Estruturas de Controle/Desafios/desafio062.py
541
3.828125
4
print('Gerador de PA') print('-=' * 10) primeiro_termo = int(input('Primeiro termo: ')) razao = int(input('Razão: ')) termo = primeiro_termo contador = 0 novos_termos = 10 while novos_termos != 0: total_termos = contador + novos_termos while contador < total_termos: print('{} -> '.format(termo), end=''...
cfded39d8cfef98e33350568b14b3b21f51774e0
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 5/Classes and Inheritance/class_variables.py
1,768
4.0625
4
class Animal(object): def __init__(self, age): self.age = age self.name = None def get_age(self): return self.age def get_name(self): return self.name def set_age(self, newage): self.age = newage def set_name(self, newname=""): self.name = newname ...
6e250b29eeaa3e60bc9ff2a64eaf5d088ffdb3ea
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 1 Fundamentos/Desafios/desafio017.py
380
3.984375
4
import math catetoOposto = float(input('Comprimento do cateto oposto: ')) catetoAdjacente = float(input('Comprimento do cateto adjacente: ')) hipotenusa = (catetoOposto ** 2 + catetoAdjacente ** 2) ** (1/2) hipotenusa = math.sqrt(catetoOposto**2 + catetoAdjacente**2) hipotenusa = math.hypot(catetoOposto, catetoAdjacent...
b9b9befaedbf60761a7004bfabcc155047c5ffae
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 1 Fundamentos/Desafios/desafio035.py
527
3.984375
4
print('\033[33m-=' * 13) print('Analisador de Triângulos') print('-=' * 13 + '\033[m') primeiroSegmento = float(input('Primeiro segmento: ')) segundoSegmento = float(input('Segundo segmento: ')) terceiroSegmento = float(input('Terceiro segmento: ')) lados = [primeiroSegmento, segundoSegmento, terceiroSegmento] lados....
67d0d48c9688ebcff85266b756303dffbf3f232a
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 3 Estruturas Compostas/Desafios/desafio089.py
1,134
3.84375
4
students = list() individual = list() while True: individual.append(input('Name: ')) individual.append(float(input('First grade: '))) individual.append(float(input('Second grade: '))) students.append(individual[:]) individual.clear() answer = '' while answer != 'Y' and answer != 'N': ...
1cd17b0d8bfb6c9f9cecf69695371bdcda1bf693
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 4/Problem Set 4/calculate_hand_len.py
348
4.09375
4
def calculateHandlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string int) returns: integer """ hand_len = 0 for frequency in hand.values(): hand_len += frequency return hand_len hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1} pr...
67d998e77b7f0a0df213733f8e9014dac80acaa6
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 3 Estruturas Compostas/Aulas/file033.py
158
3.921875
4
def print_sum(*values): s = 0 for number in values: s += number print(f'The sum of {values} is {s}') print_sum(5, 2) print_sum(2, 9, 4)
3b727b4d52189fab6c6df85c2273ddf05d760322
henriqueumeda/-Python-study
/MIT/600.1x - Introduction to Computer Science and Programming Using Python/Unit 2/Problem Set 2/Problem 1 - Paying Debt off in a Year.py
394
3.8125
4
balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 monthlyInterestRate = annualInterestRate/12 for month in range(1, 13): minimum_monthly_payment = monthlyPaymentRate*balance monthly_unpaid_balance = balance - minimum_monthly_payment balance = monthly_unpaid_balance + (monthlyInterestRate * mo...
11a086b6a3e88b9977e2d573d17e1d410dbf5019
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 3 Estruturas Compostas/Desafios/desafio091.py
587
3.625
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 22:48:38 2021 @author: Issamu Umeda """ from random import randint from time import sleep player = {} print('Values:') for counter in range(1, 5): player['Player' + str(counter)] = randint(1, 6) print('Player{} got {} in the die'.format(counter, player.get('P...
ee4d53dea746dcd5fa062ca840c6e5717c202333
henriqueumeda/-Python-study
/Curso em Vídeo/Mundo 2 Estruturas de Controle/Desafios/desafio042.py
641
4
4
primeiro_segmento = float(input('Primeiro segmento: ')) segundo_segmento = float(input('Segundo segmento: ')) terceiro_segmento = float(input('Terceiro segmento: ')) lados = [primeiro_segmento, segundo_segmento, terceiro_segmento] lados.sort() if lados[2] >= lados[0] + lados[1]: print('Os segmentos acima NÃO PODEM...
09857245736f9319706c8c9f5bb8f5c6c61caf6d
shubhamchandak94/dna_storage
/count_possible_strings.py
682
3.578125
4
import math counts = [3,12]; for i in range(120): counts.append(3*counts[-1]+3*counts[-2]) print 'Number of bases: ' + str(i+3) print 'Number of valid strings: ' + str(counts[-1]) print 'Max number of bits: ' + str(math.floor(math.log(counts[-1],2))) print 'Rate in bits/base: ' + str(math.floor(math.log(counts[-1...
24178b1dac0f2d2fa47f26342eafc58bbd01df20
Gayathri95/Marcel-Language
/src/evaluator.py
21,882
3.578125
4
''' This code can be used by Arizona State University for Grading Purposes This codebase, takes in Abstract Syntax tree and evaluates the codebase. ''' import nltk import nltk.tree from nltk import * from nltk.tree import * #from _future_ import * #import random class evaluate_prefix: def __init__(self...
8aa98823897b622fd09af7da792f091928ca41a0
sabbirdewan/Codingbat-problems-solution
/List-1/sum3.py
196
4.15625
4
''' Given an array of ints length 3, return the sum of all the elements. ''' def sum3(nums): result=0 for i in range(len(nums)): result+=nums[i] return result print(sum3([5, 11, 2]))
fbde1608b79562fb284b6ac07e82d66c838437d0
sabbirdewan/Codingbat-problems-solution
/String 2/cat_dog.py
269
3.703125
4
def cat_dog(str): dog_count=0 cat_count=0 for i in range(len(str)-2): if str[i:i+3]=="dog": dog_count+=1 if str[i:i+3]=="cat": cat_count+=1 if dog_count==cat_count: return True else: return False print(cat_dog('catxdogxdogxcat'))
054ad9476dddfe86e47f3bf38756d98b1f02e1a4
sabbirdewan/Codingbat-problems-solution
/List-1/make_ends.py
265
4.0625
4
''' Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more. ''' def make_ends(nums): temp=nums[0:1]+nums[-1:] return temp print(make_ends([1, 2, 3, 4]))
1d7cc67e80d3d94b89e6160ea0bd7ff9db26500a
RedZord/geekbrains
/HW_1/HW_1_4.py
267
3.578125
4
user_number = int(input('Введите любое число: ')) max_number = 0 while True: tmp = user_number % 10 user_number //= 10 if tmp > max_number: max_number = tmp if user_number < 10: print(f'{max_number}') break
74727e13c4324a4693fdfc8f1d16e5ff357aa544
DtjiSoftwareDeveloper/Attack-The-Enemy-RPG
/code/attack_the_enemy_rpg.py
4,929
3.890625
4
""" This file contains source code of the game "Attack The Enemy RPG". Author: DtjiSoftwareDeveloper """ # Importing necessary libraries import sys import random from mpmath import * mp.pretty = True # Creating necessary classes class Player: """ This class contains attributes of the...
ce1a001e3dde4aa6bb413ad884cea077d526ecfc
StephTech1/Palindrome
/main.py
341
4.28125
4
#Add title to code print ("Is your word a Palindrome?") #Ask user for word input = str(input("What is your word?")) palin = input #create a function to check if a string is reversed #end to beginning counting down by 1 if palin == palin [::-1] : #print answers based on input print("Yes!") else: print("No!") print("...
fa4afb64250bf233f818df2f77fac50d4f80516b
AlexHettle/Random-Wikipedia-Article-Finder
/main.py
1,886
3.765625
4
import requests, webbrowser from bs4 import BeautifulSoup from tkinter import * #A function that takes a link and opens it in the users preferred browser def callback(url): webbrowser.open_new(url) #A function called when the GENERATE NEW ARTICLE button is pressed. #The function gets a random Wikipedia article and ...
3a22028c076cbf5cf2b252688fa4c947a10d7e91
shreeviknesh/ScratchML
/scratchml/utils/ScratchMLExceptions.py
826
3.890625
4
class InvalidValueException(ValueError): """InvalidValueException is raised when a value passed as parameter is invalid. """ def __init__(self, message): if type(message) == dict: self.expected = message['expected'] self.recieved = message['recieved'] self.messag...
1020591484bded444ab2fcdde1de3df2aed86fa0
olasaja/B8IT105
/Calculator2/Calculator2.py
2,777
4.0625
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 19 13:45:10 2020 @author: 10540429 Assignment 3: Create a Calculator class and CalculatorTest class that will implement functionality from a calculator using lists. Each function should use the lessons learned in the map, reduce, filter, and generator lecture. """...
ecacdeb6cd2c390e04e834191197100135c3d374
convex1/data-science-commons
/Python/filter_operations.py
2,074
4.1875
4
import pandas as pd import numpy as np """ create dummy dataframe about dragon ball z characters earth location and other information """ data = {"name": ["goku", "gohan"], "power": [200, 400], city": ["NY", "SEA"]} dragon_ball_on_earth = pd.DataFrame(data=data) """ ~~ABOUT~~ Use vectorization instead of using for ...
7ea6faa286baee7803c11ab67acabfb9c33b01b7
e20co/helper-python-package
/helper_python/helper/type_checking.py
1,622
3.96875
4
from typing import Any def check_value(value: Any, value_name: str, value_type: Any) -> bool: """ Check if a value is not `None` and a subclass of a given type. Args: value (Any): The value to check. value_name (str): The value name, which is used in the exception messages. value_...
64049cebaff081e51484d57d110a7075b427b46f
mertyertugrul/Binary-Search-Tree-and-Graphs
/Trees/test_BinarySearchTree.py
1,293
3.828125
4
import unittest from BinarySearchTree import * class MyTestCase(unittest.TestCase): def test_BinarySearchTree(self): """ Testing insert, look_up, remove and traverse functions :return: None """ # insert function a = BinarySearchTree(9) a.insert(4) se...
2efd2857d718e222b548e1806363469b4c8defa6
toliahoang/seaborn
/aggregating_multi_col.py
223
3.78125
4
import codecademylib3_seaborn import pandas as pd from matplotlib import pyplot as plt import seaborn as sns df = pd.read_csv("survey.csv") print(df) sns.barplot(data=df,x='Age Range',y='Response',hue='Gender') plt.show()
ba19631431aa7462043d62a4185a05f0f181e37b
swyatik/coursera-python
/file_class.py
3,289
3.578125
4
import tempfile class File: def __init__(self, file_path): self.file_path = file_path # шлях до файлу self.result_line = None # string рядок, що повертається при ітерації self.size = None # кількість байт у файлі self.size_read_line = 0 # кількість прочитаних байт with open(...
dde6251d74b6fd8cf2014631c6ec0aa3210f0dd4
chapman-cpsc-230/hw1-enfie101
/sin2_plus_cos2.py
582
3.625
4
""" File: sin2_plus_cos2.py Copyright: (c) 2016 Callie Enfield License: MIT_License This code verified mathematic equations and also solved for a value using different variables and equations. """ import math from math import sin, cos, pi x = pi / 4 value = math.sin(x)**2 + math.cos(x)**2 print value v0 = 3 #m/s t = ...
8fa416561199d1e462d6a1f33074040b371aad4a
Kyloveslevine/secu2002_YQKTH58
/lab05/filter.py
569
4.09375
4
# Task 1 # Loop_filter: Goes thru the list and filters out variables that satisfy the condition of being > x # Input: List of items, condition # Output: List of variables that satisfy the condition def loop_filter(list, x): newlist = [] for y in list: if y > x: newlist.append(y) # The return...
8eb4f2c7ff636079e5551fda4c84d75d330ebdf7
LeonNie52/AlgorithmPrac
/Fibonacci.py
388
3.609375
4
# -*- coding:utf-8 -*- """ 大家都知道斐波那契数列, 现在要求输入一个整数n,请你输出斐波那契数列的第n项。 n<=39 """ class Solution: def Fibonacci(self, n): # write code here i,j = 0,1 if n == 0: return 0 if n==1: return 1 for x in range(1, n): i,j = j,i+j return j
13dc571dc69c433107f834e46830103cfb15fd11
Kiira1968A/Heracles1
/ee/spiridon/matem_avaldused.py
4,468
3.671875
4
''' Created on 18. okt 2021 @author: spiridon ''' 1 + 2 print(1 + 2) one = '4' two = '26' print(one + two) penta = [1, 2, 3, 4, 5] print(penta) heksa = [1, 2, 3, 4, 5, 6] print(heksa + penta) penta1 = ('a', 'b', 'c', 'd', 'e') heksa1 = ['f', 'g', 'h', 'i', 'j', 'k'] print(heksa1[3]) # heksa1 toon valja 4. elemendi , k...
a680d758ba2a9060e778101bbe3470d8e07178cc
liudengfeng/cnswd
/cnswd/ths/financial_analysis.py
4,271
3.53125
4
""" 财务分析 近三年财务分析 """ import pandas as pd from .base import THS url_fmt = "http://data.10jqka.com.cn/financial/{}/" titles = ['yjyg', 'yjkb', 'yjgg', 'yypl', 'sgpx', 'ggjy'] class FinancialAnalysis(THS): api_name = '' date_css = '.text' r_date_css = '.list' table_attrs = {'class': 'm-table J-ajax...
efec837bd438a999af80e075da6ad4241230194e
YukyCookie/learn-python-three-the-hard-way
/09:Printing,Printing,Printing/ex9.py
394
3.90625
4
days = "Mon Tue Wed Thu Fri Sat Sun" months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print("Here are the days: ", days) print("Here are the months: ", months) print("""There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """)...
6f562b53eda654c595231427663832a51908750d
YukyCookie/learn-python-three-the-hard-way
/14:Prompting and Passing/ex14-1.py
582
3.5625
4
from sys import argv script, user_name1, user_name2 = argv prompt = '>' print(f"Hello, {user_name1}. Welcome to the zork and adventure!\nNow, let's go and have some fun") first = input(prompt) print(f"You choice is {first}. So,Opening the small mailbox reveals a leaflet. ") second = input(prompt) print(f"""Good cho...
da2007e4d4f65b1e600f274f6cd5c37814a69830
YukyCookie/learn-python-three-the-hard-way
/19:Functions and Variables/ex19-1.py
1,726
3.90625
4
def classroom(student, teacher, desk, chair): print(f"In the classroom, we have {student} students and {teacher} teachers.\nHowever, we just have {desk} desks and {chair} chair.\nWhat should we do ? \nI hope that you can help me, Thank you.\n") print("one") numstu = int(input()) numteacher = int(input()) numdesk =...
934dbe4077d2eef6b1c3d477a683b1b90ca945af
TamirlanSH/PP2
/TSIS6/4.py
134
3.96875
4
def reverse(a): b = "" i = len(a) while i > 0: b += a[i-1] i -= 1 return b print(reverse("sadiufyh"))
471733b7ebe6f6a907bef6f174b5741b7c8da1d0
TamirlanSH/PP2
/TSIS6/3.py
103
3.625
4
def sum(list): s = 1 for i in list: s *= i return s print(sum((7, 5, 2, -1, 4, 9)))
2857b8f658ddb15d678ba6a0cbe53f4d8d98846a
TamirlanSH/PP2
/TSIS6/14.py
161
3.9375
4
import string, sys def isPangram(str1, ALPH=string.ascii_lowercase): ALPHset = set(ALPH) return ALPHset <= set(str1.lower()) print (isPangram(input()))
ab226fe8f63888e88fdb2c40546a44c3b72be070
emajinbrown1/Stock-Data-Visualizer
/Data_Visualizer.py
7,472
4.25
4
#File created 10 March 2021 #*****PLEASE READ****** # the input function when dealing with characters does not work in CLI # you must use raw_input instead # if you are testing in IDLE use input # if you are testing in CLI use raw_input #*************************************** #Could have a function that checks for ...
f81ce5221af4827cac4fafe7ae891faa751ce485
klborders/Python
/Practices/PracticePython.org/list-overlap.py
475
3.78125
4
# https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html import random def compare_list(list_a, list_b): return [set(list_a) & set(list_b)] def generate_random_number_list(): random_number_list = [] amount = random.randint(3,20) for i in range (amount): random_number_list.appe...
cb43682f18e797ba1aa9712739a54cbb9b1e655c
Wangjunling1/leetcode-learn
/python/947.py
1,858
3.53125
4
# n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。 # # 如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。 # # 给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。 # 解题 # 使用并查集实现该题解释 # 并查集模版 class bing: def __init__(self,len_list): self.queue=list(range(len_list)) self.root=set() def find(self,...
c6b6d7c80b81a2b5107e75579d9e358ad93bfe40
Wangjunling1/leetcode-learn
/python/567.py
640
3.8125
4
s1 = "ab" s2 ="eidboaooo" def main(s1, s2): len_1, len_2 = len(s1), len(s2) if len_1 > len_2: return False char_count = [0 for i in range(26)] ascii_a = ord('a') for i in range(len_1): char_count[ord(s1[i]) - ascii_a] += 1 char_count[ord(s2[i]) - ascii_a] -= 1 for i in...
92a1e95c0f5eff2d7c0e3744e768c86e777ce75d
briwhi/string_helpers
/tests.py
551
3.5625
4
import unittest from string_helpers import String_helper class StringHelpersTest(unittest.TestCase): def test_array_to_string(self): sh = String_helper() ia = [7,1,0,1,4] r = sh.integer_array_to_string(ia) print(r) self.assertEqual(r, '71014') def test_string_to_array(...
639c90325564deca785b57156c20c2194329364a
CCM-Balderas-Pensamiento-Comp/strings
/assignments/11CuentaMayusculas/src/exercise.py
359
3.75
4
def main(): #escribe tu código abajo de esta línea cadena = input("Dame una cadena de caracteres: ") minusculas = cadena.lower() cont = 0 for c in range(len(cadena)): if cadena[c]!=minusculas[c]: cont = cont +1 print("El número de mayúsculas en la cadena es:",cont) i...