blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ebe64f9cc91e45d6038ba34f15201566328bdc50
Haut-Stone/study_Python
/PythonCookbook/<3>数字日期和时间/11-随机选择.py
546
3.75
4
''' ''' import random values = [1, 2, 3, 4, 5, 6] print(random.choice(values)) print(random.choice(values)) print(random.choice(values)) # 想要取出N个元素,将选出的元素移除以做进一步的考察,可以使用random.sample() print(random.sample(values, 2)) print(random.sample(values, 2)) # 打乱顺序 random.shuffle(values) print(values) # 生成随机整数 print(ra...
d42bb2c01669d8bb3e4b8354076e6b5d7d0e178b
mveselov/CodeWars
/tests/kyu_8_tests/test_barking_mad.py
356
3.65625
4
import unittest from katas.kyu_8.barking_mad import Dog class DogTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(Dog("Beagle").bark(), 'Woof') def test_equals_2(self): self.assertEqual(Dog("Great Dane").bark(), 'Woof') def test_equals_3(self): self.assertEqu...
a9ae85551ea5d35db0118e1907afeb3597223e89
chrinide/Mahjong-5
/AI.py
12,165
3.6875
4
AI_name_list=['no_AI','zr_AI','zx_AI(zrzr)','zx_AI(zrno)','zx_AI(nozr)','zx_AI(nono)','human'] def init(player,gametable): if player.AI_name == None: player.AI_name = player.name while player.AI_name not in AI_name_list: print("可用的AI方法有:", ", ".join(AI_name_list)) player.AI_name = str(i...
f4ff5535438cd0c972f3062f1a3f9b30e203986b
jaford/thissrocks
/Python_Class/py3intro3day 2/EXAMPLES/fmt_signed.py
393
4
4
#!/usr/bin/env python values = 123, -321, 14, -2, 0 for value in values: print("default: |{:d}|".format(value)) # <1> print() for value in values: print(" plus: |{:+d}|".format(value)) # <2> print() for value in values: print(" minus: |{:-d}|".format(value)) # <3> print() for value...
4bd1e0de72840f708132df376ecaa40cd941fffa
JdoubleW/Opdrachten_programmeren
/Week 2/pe3_3.py
211
3.875
4
age = eval(input('Wat is je leeftijd?')) passport = input('Heb je een paspoort?') if age >= 18 and passport == 'Ja': print("Gefeliciteerd! Jij mag stemmen!") else: print("Jij mag niet stemmen.")
5e88c5e02104d94684a53a24c78e0ab540249fd7
GuillyK/University-world-ranking-group-4
/Used python code/student_count.py
801
3.6875
4
###################################################################################### # moves the universities into 3 different catogories based on the amount of students. # adds these values in to the csv ###################################################################################### import googlemaps import ...
8b0e669e821771dc7122c0a0baaf0e41d6f67bca
MTrajK/coding-problems
/Math/sum_of_multiples.py
1,140
4.1875
4
''' Multiples of a OR b If we list all the natural numbers below 10 that are multiples of 3 OR 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of A or B below N. ========================================= Don't need iteration to solve this problem, you need to find only how...
7aa7a3e47bcaa541acfef053bba89a8995a7e63c
daorox/aoc2019
/day13/e13.py
1,550
3.703125
4
from computer import Computer class TileTypes: EMPTY = 0 WALL = 1 BLOCK = 2 PADDLE = 3 BALL = 4 class BreakOutAi: def __init__(self, computer): self.computer = computer self.computer.mem[0] = 2 self.db = {} self._update_db(computer.run(0)) def destroy_all...
bbb07334f86b66ff8f620978b603b221213c5139
akimi-yano/algorithm-practice
/lc/222.CountCompleteTreeNodes.py
2,208
4.0625
4
# 222. Count Complete Tree Nodes # Medium # 2425 # 228 # Add to List # Share # Given a complete binary tree, count the number of nodes. # Note: # Definition of a complete binary tree from Wikipedia: # In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last ...
9d1226581eecf399ce55e8c104946e7395eca760
supergonzo812/cs-module-project-algorithms
/eating_cookies/eating_cookies.py
1,155
4.21875
4
''' Input: an integer Returns: an integer ''' def eating_cookies(n): # Cookie Monster can eat either 1, 2, or 3 cookies at a time. If he were given a jar of cookies with `n` cookies inside of it, how many ways could he eat all `n` cookies in the cookie jar? Implement a function `eating_cookies` that counts the numb...
5a1c6d4d39839b13b29dddba41817049016de02f
LinkIsACake/PTUT-CoffreFortElectronique
/src/EncryptCore/sources/Utilities.py
3,885
3.5
4
from math import log, ceil def bundleSizeAndRest(size: int, rest: int): """ # get a bundled number of the rest and the bytes needed to store the cipher # Note: some arbitrary modification is done to this number to protect it against reverse engineering :param size: the size of the cipher to bundle (ma...
ad4a7392e6ac0c0f2122a21d3a12dd4cd9a78b6d
gerrymanoim/advent_of_code
/2019/5.py
4,476
4.4375
4
""" An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). To run one, start by looking at the first integer (called position 0). Here, you will find an opcode - either 1, 2, or 99. - 99 means that the program is finished and should immediately halt. - Opcode 1 adds together numbers read from ...
0fe427120d8b5e1fbf5eded244a18e4a2a5b01f2
sprinter-17/PyChess
/test/test_board.py
1,081
3.65625
4
import unittest from board import Board, Piece class MyTestCase(unittest.TestCase): def setUp(self): self.board = Board() def test_board_created(self): self.assertIsNotNone(self.board) def test_pieces_count(self): self.assertEqual(len(self.board.pieces), 32) def test_pieces...
03f2bc7a6f7d99acfafd8bcb2899e79c02c9421d
maiconferreira/atividade-aula-ALPC
/Atividade-2/main.py
1,086
3.890625
4
''' Instruções: -O custo ao consumidor de um carro novo é a soma do preço de fábrica com o percentual de lucro do distribuidor e dos impostos aplicados ao preço de fábrica. Faça um programa em Python que receba o preço de fábrica de um veículo, o percentual de lucro do distribuidor e o percentual de imposto, calcule e ...
764185b7c0ed762159f87b983f64c0ce9e41225a
Crayon2f/hello-world
/src/base/for.py
895
3.890625
4
# coding=utf-8 # for循环 print('------------------ for ------------------------') fruits = ['apple', 'banana', 'mango'] for fruit in fruits: print(fruit) for index in range(len(fruits)): print(index) print('-------------- for else ------------------') numbers = [1, 2, 3, 4, 5, 6, 7] for number in numbers: ...
7e826d4bb889c4a2f3b826dfd3d30428357ac3df
MKDevil/Python
/学习(千峰)/03语句和语法/02 循环语句练习.py
1,188
3.75
4
''' Author: MK_Devil Date: 2021-12-20 17:18:09 LastEditTime: 2022-01-19 17:13:00 LastEditors: MK_Devil ''' #!/usr/bin/env python # -*- coding:utf-8 -*- import random # 打印 1-50 内可以被 3 整除的数字 n = 1 while n <= 50: if n % 3 == 0: print(n, end='\t') n += 1 print() n = 1 counter = 1 while n + 3 < 50: n ...
8f1ba4dffabe554af96aca45218c9c2c44ba490d
AdamZhouSE/pythonHomework
/Code/CodeRecords/2445/60866/266045.py
335
3.8125
4
def chazhao(a,b): if len(a)!=len(b): print('false') else: A=[ord(x) for x in a] B=[ord(x) for x in b] s1=set(A) s2=set(B) if len(s1|s2)!=len(s1): print('false') else: print('true') import re a=input() m=re.split(r'\"',a) a=m[1] b=m[...
166d7d78bf258a953944dc4ba04276e40a5071ce
noorulameenkm/DataStructuresAlgorithms
/Recursion/factorial_memoization_decorator.py
328
3.71875
4
def fact_memoization(func): memory = {} def fact(num): if num not in memory: memory[num] = func(num) return memory[num] return fact @fact_memoization def factorial(num): if num == 1: return 1 return num * factorial(num - 1) print(factorial(5)) print(facto...
6fc68e3bf57bcfa85dfbaf5df66529957e899acf
suterm0/Project13
/Assignment13.py
9,506
4.28125
4
import sqlite3 from sqlite3 import Error def choice(): print(""" Put 1 to pull up the customer menu, 2 for the books menu, 3 to pull up the orders, 4 to exit code. """) answer = int(input(">")) while answer <= 1 >= 3: # Unlimited loop for the menu choice() if answe...
57157eb13c843c4a0ae3f178243d2ed19260a29b
yixinj/cs4417asn2
/part3/query.py
1,390
3.75
4
import sys for query in sys.stdin: # Take query and process it query = query.strip().upper().split() # If length of query is 1 (so 1 search term) if len(query) == 1: genre_first = query[0] # genre1 is genre to search for with open('part3/movieInformation', 'r') as f: for l...
78f7349cf6a8030df3bd4e5ad7f95660753a9a4f
josealb94/platzi_AplicacionTerminal
/contacts.py
3,695
3.890625
4
# -*- coding: utf8 -*- import csv WELCOME = """ --------------------------------------------------- | B I E N V E N I D O A L A A G E N D A | --------------------------------------------------- """ class Contact: def __init__(self, name, phone, email): self.name = name ...
10127bc09d0220f9e17404e417c405988e54e1c3
wuxu1019/1point3acres
/Amazon/count_clump.py
980
3.65625
4
""" count clumps of same color in the tree, here are two clumps below R R R G R B B G """ class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None count = 0 def CountClumps(root): def CountClumpsH...
7ec2fa0fbf97e5fc56e0608b3944090d8d6b6e60
commGom/pythonStudy
/백준/개념/링크드리스트.py
1,769
4.09375
4
# 노드 : 칸에 있는 데이터, 다음 칸에 어떤 노드가 연결되어있는지 # 1.Node 클래스 만들기 class Node: def __init__(self,data): self.data=data self.next=None # 2.링크드리스트 append print insert delete # 링크드 리스트는 head에 노드만 가지고 있고 노드.next에 노드를 연결하여 리스트를 만든다 class LinkedList: def __init__(self,data): self.head=Node(data)...
14df1fb6801a97164fbd15cb7e9b3a61355a306d
Ukabix/python-basic
/core ideas/functions/function call multiple.py
682
3.921875
4
# wywołanie bez domyślnego arg: def get_integer(help_text): return int(input(help_text)) age = get_integer("Tell me your age: ") # tutaj zwróci podany tekst school_year = get_integer("What grade are you in? ") # tutaj zwróci podany tekst if age > 15: print("You are over the age of 15") print("You are in grade " + s...
26ed2fe2b2662f8849a1131fb00760080c29db46
kashyapa/interview-prep
/revise-daily/epi/revise-daily/9_heaps/1_merge_sorted_files.py
590
3.859375
4
import heapq def merge_sorted_lists(): min_heap = [] for i, one_d_list in enumerate(two_d_list): heapq.heappush(min_heap, (one_d_list[0], 0, one_d_list)) result = [] while min_heap: val, list_index, one_d_list = heapq.heappop(min_heap) result.append(val) if list_ind...
ad19f07b9347aaa327473251e4f57ebec45f651a
ishank-dev/College-Work
/Semester5/Scripting Languages Lab/SEE/Scripting/6/6b/6bprac.py
821
3.90625
4
class Reverse: def __init__(self,sentence): self.sentence = sentence def reverse(self): reverseSen = ' '.join(reversed(self.sentence.split())) # print(reverseSen,'\n\n') return reverseSen def vowelCount(self): count = 0 vowels = ['a','e','i','o','u'] for i in self.sentence.lower(): if i in...
6e4845730f47d32663a1234d1c5d3c31c60f6c2e
jingyiZhang123/leetcode_practice
/recursion_and_backtracking/93_restore_ip_addresses.py
939
3.703125
4
""" Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example: Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) """ class Solution(object): def _restore(self, soFar, rest): if not rest: ...
e10b06c5ce47f618628e4cb5b72ea831e573d992
alaa-samy/Tic-Tac-Toe
/tic-tac-toe.py
3,797
4
4
board = [' ' for i in range(10)] def insert_letter(letter,position): board[position] = letter def space_is_free(position): return board[position] == ' ' def print_board(board): print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print('----------------') print(' ' + board[4] ...
caaa8fb142f2ad4be294bb2364a46bba452b11a7
bhaumeek/music_recommendation
/Music Recommender/music.py
993
3.765625
4
import pandas as pd import numpy as np from sklearn.tree import DecisionTreeClassifier #sklearn is the package & algoritm udes is decision tree import joblib #used for saving and loading models music_data = pd.read_csv('music.csv') #music_data #in the csv file 1 is given for male and 0 is given for female #we w...
c855a09628e68e1828d167f081c76688e579f18a
chc1129/introducing-python3
/chap05/stdlib6.py
563
3.515625
4
from collections import Counter breakfast = ['spam', 'spam', 'eggs', 'spam'] breakfast_counter = Counter(breakfast) print(breakfast_counter) print(breakfast_counter.most_common()) print(breakfast_counter.most_common(1)) breakfast_counter Counter({'spam': 3, 'eggs': 1}) lunch = ['eggs', 'eggs', 'bacon'] lunch_counter =...
f12cbccc204786404b5329a0e5e40cf4591315b3
rlavanya9/hackerrank
/datastructures/practice1.py
1,522
3.75
4
# def binary_search_arr(a, key, low, high): # if low > high: # return -1 # mid = low + ((high-low)//2) # if a[mid] == key: # return mid # elif key < a[mid]: # return binary_search_arr(a, key, low, mid-1) # else: # return binary_search_arr(a, key, mid+1, high) ...
9fe1deb49cf847916162a055224ccf4dc418d85c
fredy-prudente/python-brasil-exercicios
/Estrutura De Decisao/ex19.py
893
3.875
4
""" Faça um Programa que leia um número inteiro menor que 1000 imprima a quantidade de centenas, dezenas e unidades do mesmo Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo: 326 = 3 centenas, 2 dezenas e 6 unidades """ n = int(input('Digite um numero menor que 1000: ')) st...
2f5bddfbf59e2064e16bf187874b49efa0e4f619
arturolearczuk/zadania
/zad2(czynniki).py
366
3.609375
4
def rozloz(liczba): dz = 2 while liczba > 1: while liczba % dz == 0: print(f"{liczba} {dz}") liczba = liczba // dz dz += 1 print("Podaj zakres Liczb jakich chcesz rozłożyc na czynniki") x = int(input("Od: ")) y = int(input("Do: ")) for i in range(x, y): ...
869752d60753074d446a7f313645f25fec32956b
pbarden/python-course
/Chapter 10/extra_credit.py
327
3.734375
4
test_grades = [101, 83, 107, 90] sum_extra = -999 # Initialize 0 before your loop, useless initialization provided by the assignment instructions sum_extra = 0 # Correct the default, srsly why would -999 be useful here at all!? for n in test_grades: if n > 100: sum_extra += n % 100 print('Sum extra:', sum...
ec994851e653c108b2081d71ce6616aaa19b7382
tabatafeeh/URI
/python/1008.py
165
3.921875
4
# -*- coding: utf-8 -*- num = int(input("")) numh = int(input("")) salh = float(input("")) salt = numh * salh print ("NUMBER = %d\nSALARY = U$ %.2f" %(num, salt))
eaff9a41194a242db9f2bec92bd6380e9c5ce836
tianlelyd/pythonPainting
/画电脑.py
3,206
3.6875
4
# 画电脑 from turtle import * tracer(50) def computer(): #start from the most northwest corner of the computer. pensize(4) pencolor('blue') seth(10) circle(-500,16) rt(90) fd(10) rt(90) circle(500,14) lt(85) fd(85) rt(90) fd(15) rt(90) fd(90) rt(120) fd(90) ...
3e38a5c4e71084f6bcd47000deb20a7ec047f9b5
dataders/AJS
/codechef/TRISQ/TRISQ_sub_joel.py
171
3.53125
4
T = int(input()) for i in range(T): C = int(input()) if C <= 3: fx = 0 else: gx = int(0.5*(C-2)) fx = int(0.5*gx*(gx+1)) print(fx)
7b8ca5348a79601ee822db195a41203bd2d700ed
sjc2870/LeetCode
/python/string/buddyStrings.py
624
3.5
4
#!/usr/bin/env python3 #coding=utf-8 ''' leetcode issue 859 ''' class Solution: def buddyStrings(self, A: str, B: str) -> bool: if len(A) != len(B): # 长度不相等必定不符合 return False idx =[i for i in range(len(A)) if A[i] != B[i]] if len(idx) == 2 and A[idx[0]] == B[idx[1]] and A[idx...
2ebc6da08605492ddf109d63398e7e936353f0bf
nikitabuts/Image-classification
/DataCreator.py
5,063
3.90625
4
import matplotlib.pyplot as plt import numpy as np class Functions: def __init__(self, x, a, b, alpha): self.x = x self.y = self.x.copy() self.a = a self.b = b self.alpha = alpha @staticmethod def _reverse(f, x, y): x_2 = x * np.cos(f) - y * n...
ba3606232a9bd13c27296d7c0e69c046b83ffbcf
penguin-wwy/leetcode
/source/29-Divide Two Integers/29. Divide Two Integers.py
1,081
3.671875
4
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend == 0 or divisor == 0: return 0 flag = 1 res = 0 tmp_dividend = dividend tmp_divisor = diviso...
2a4d577008b1aee3b290917d7c9b4b61264bcad0
OscarVegener/TicTacToe
/main.py
3,494
3.796875
4
def paint(): print("---------") print("| " + nested_lst[0][0] + " " + nested_lst[0][1] + " " + nested_lst[0][2] + " |") print("| " + nested_lst[1][0] + " " + nested_lst[1][1] + " " + nested_lst[1][2] + " |") print("| " + nested_lst[2][0] + " " + nested_lst[2][1] + " " + nested_lst[2][2] + " |") prin...
c8e09e16c9947de834fc0ecd585285eaced75a94
naveensakthi04/PythonTraining
/Basics/basics.py
7,161
4.09375
4
import math as M from math import ceil print("Hello World!") print(5 // 2) print(5 / 2) print(2 * 7) print(2 ** 7) print('Hello World') print('''Naveen''') print('''Naveen''') print("\"Naveen\"") print(10 * "Naveen ", end=" ") print(r'\naveen') x = 10 y = 12 print(x + y) # split function print("Hai...
b733170325793d63b2db089bb0a4a31dd5d36c55
dimaape/GeekBrains_Python_Course
/Lesson_1/GB_Py_HW_1_1.py
1,252
4.34375
4
# Задание 1.1 # Поработайте с переменными, создайте несколько, выведите на экран print("Поработайте с переменными, создайте несколько, выведите на экран.\n") var_a = 0 var_b = "some text" var_c = 10 var_d = "some text again" print(var_a, var_b, var_c, var_d, sep='\n') # Запросите у пользователя несколько ...
65b070c3ff4e9cf6551eb5fa776b623d01aab524
madiyar99/webdev2019
/week10/hackerrank/9.py
334
3.75
4
n = int(input()) arr = [] for i in range(n): lis = list(input().split()) arr.append(lis) name = input() for i in range(n): if(arr[i][0] == name): math = float(arr[i][1]) physics = float(arr[i][2]) chemistry = float(arr[i][3]) average = float((math + physics + chemistry) / 3) break print('{0:.2f}'.for...
431be85fffa91b7b0bc2c879bc867de4379a3bbf
tslator/arlobot_rpi
/src/arlobot/environment/onoffmonitor.py
2,108
3.71875
4
#! /usr/bin/env python from __future__ import print_function # The purpose of this script is to allow the Raspberry Pi to shutdown gracefully when the Arlobot power switch is turned # off. # Idea stolen from here: https://www.element14.com/community/docs/DOC-78055/l/adding-a-shutdown-button-to-the-raspberry-pi-b # # T...
ed253782297205366fa4fabcc628823aac342e93
kamath7/Automate-The-Boring-Stuff-Al
/Basics/app12.py
1,048
4
4
#Dictionaries my_dict = {'name':'Kams','age':25,'nationality':'Indian'} print('My name is {0}'.format(my_dict['name'],)) some_other_dict = {0:'India',1:'Brazil',2: 'Argentina'} print(some_other_dict) #Comparing two same dictionaries a_dict = {'name':'Kams','age':29,'nationality': 'Indian'} b_dict = {'age':29,'nation...
5a3eaff983d3c29af6f5cd01105ed957748126d4
lxgzhw520/ZhangBaofu
/day029/hw_001_双下str方法.py
629
3.859375
4
# _*_ coding:UTF-8 _*_ # 开发人员: 理想国真恵玩-张大鹏 # 开发团队: 理想国真恵玩 # 开发时间: 2019-04-16 08:32 # 文件名称: hw_001_双下str方法.py # 开发工具: PyCharm # 内置的类方法和内置的函数之间关系非常紧密 print(repr(1)) print(repr('1')) print(1, '1') print('--' * 22) class A: def __str__(self): return 'A的说明信息:原生调用的是地址{}'.format(id(self)) a = A() # 实际上是调用了类...
9e689a2c59b920a5dc21212d0f557c13e1a54773
mjgutierrezo/MCOC-Nivelaci-n-
/23082019/000300.py
1,089
3.8125
4
# -*- coding: utf-8 -*- """ Aplicar ciclo while para recorrer una lista y someter a los elementos dentro de ella a condiciones """ from numpy import * #000300 given_list = [5, 4, 4, 3, 1, -2, -3, -5] #se quiere obtener la suma de sólo los números positivos de la lista total = 0 i = 0 # en vez de usa...
70a201e94ffe034bc090275d9939c8a6cd9cf92b
Biscuit28/WKEXP1
/HTML/main_crawler/tools/dateformat.py
1,659
4
4
def compare_date(sdate, edate): ''' recursively checks if sdate is bigger than edate Expects date format to be YY-mm-dd ''' print sdate sdate = sdate.split('-') edate = edate.split('-') def check(index=0): if int(sdate[index]) > int(edate[index]): return False ...
8b2e32a69338825a226d76faafb673f2e3a600af
ssam1994/bootcamp
/lesson_39.py
1,672
3.546875
4
""" Lesson 39: Intro to Image processing """ import numpy as np import scipy.stats import matplotlib.pyplot as plt import pandas as pd import scipy import seaborn as sns sns.set_style('dark') import skimage.io import skimage.exposure import skimage.morphology import skimage.filters import skimage.measure phase_im = ...
d7ed83a87e1eb77d01eda1b216368dc7b1d22602
rochaktamang/pythonProject
/lab 1/apples.py
324
3.890625
4
N=int(input('enter the number of students: ')) K=int(input('enter the number of apples: ')) number_of_apples_each_students_get=K//N numbers_of_apples_in_basket=K%N print(f'the number of apples each students get is {number_of_apples_each_students_get}') print('the number of apples in basket is', numbers_of_apples_in_bas...
659a6de586382f12ca40d39b5fc43a3d2da48f8b
Nicole-Bidigaray/Bootcamp-pirple.com
/Python_is_Easy/Homework#3/main.py
1,108
4.3125
4
""" pirple.com/python Homework Assignment #3: "If" Statements If conditionals. Create a function that accepts 3 parameters and checks for equality between any two of them. Your function should return True if 2 or more of the parameters are equal, and false is none of them are equal to any of the others. Bonus: Modify y...
e1415877ddcc3eca4fb9e9033675cbcd02d05e11
vins-stha/hy-data-analysis-with-python
/part05-e05_best_record_company/src/best_record_company.py
584
3.828125
4
#!/usr/bin/env python3 import pandas as pd def myfilter(df): # The filter function must return a boolean value return df["WoC"].sum() >= 10 def best_record_company(): df = pd.read_csv("src/UK-top40-1964-1-2.tsv", sep="\t") #print(df.head()) publishers = df.groupby("...
d3c7a472c2dc343b4e5d19e454032ba26c80e9f8
JianmingS/Practice-Code
/leetcode/双指针/面试题 02.02. 返回倒数第 k 个节点.py
471
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def kthToLast(self, head: ListNode, k: int) -> int: start_point = head end_point = head cnt = 0 while start_point: start...
1f457ec4bd96b1375d21c09e45021c56dbb4fcc7
irina-rus/Geekbrains
/L6/hw6_t2.py
1,229
3.71875
4
#Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). # Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. # Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. # Использовать форм...
487317f842b366efa579064ef21cd1908b4e1386
petersimachev/Struct-Prog
/lab1-3.py
491
4.15625
4
import math print('Сейчас будет решено выражение:') print('N = (z+(z*x)^(1/5))^(1/5))/e^x+a^5*arctg(x)') z = float(input('Введите переменную z: ')) e = float(input('Введите переменную e: ')) x = float(input('Введите переменную x: ')) a = float(input('Введите переменную a: ')) sqrz=z+math.sqrt(z*x) n=math.pow(sqrz,1/5)/...
457ea69a221c2de3d22dbc5b094425d2e67040ba
sushantMoon/Personal-Development
/Geeks4Geeks/activity_selection.py
689
3.609375
4
""" Sushant Moon Date 14/7/2018 Activity Selection Problem Reference : https://www.geeksforgeeks.org/greedy-algorithms-set-1-activity-selection-problem/ """ def activity_selection(activity): activity = sorted(activity, key=lambda item:item[1]) results = [] results.append(activity[0]) for index, item i...
541b97af90e998ba930d5943a492689a7ddca71e
aletisunil/Covid19_liveTracker
/Covid19_liveTracker.py
1,253
3.5
4
import requests import bs4 country_name=input("Enter the Country name: ") def covid19(country): res = requests.get("https://www.worldometers.info/coronavirus/#countries") soup = bs4.BeautifulSoup(res.text, 'lxml') index = -1 data=soup.select('tr td') for i in range(len(data)): i...
b8fcd7fcc7d3885ec836d98dd811ba12e11c80e6
seanchen513/dcp
/dcp160 - given tree with weighted edges, compute length of longest path.py
3,970
4.28125
4
""" dcp#160 This problem was asked by Uber. Given a tree where each edge has a weight, compute the length of the longest path in the tree. For example, given the following tree: a /|\ b c d / \ e f / \ g h and the weights: a-b: 3, a-c: 5, a-d: 8, d-e: 2, d-f: 4, e-g: 1, e-h: 1, the longest pat...
c798db8fbf7348d4793b24ecff4f39be3e1deb00
eltechno/python_course
/CODES/17. Logical Operators/logicaloperators.py
620
4.125
4
'''number = int(input("Type a number and I will tell if it's between 1 and 10: ")) if (number > 1 and number < 10): print("number between 1 and 10") ''' a = 5 b = 2 if (not(a > b and b == 5)): print("test") ''' LOGICAL operators True False and True True - True True False - False...
c0fb388cafc01226f6c1968eeeb1f843b670593d
pratik-iiitkalyani/Python
/function/return_print.py
181
3.65625
4
# return vs print # return def add_three(a,b,c): return a+b+c #function returning the value print(add_three(5,4,3)) # print def add_two(a,b): print(a+b) add_two(5,4)
f4461e360ce4e1cd22361ec8452ef74e020e3fe7
gulberkdemir/isanagram
/Anagram.py
334
3.765625
4
import sys import os import string import time import argparse class Anagram: def __init__(self): pass @staticmethod def isAnagram(s1, s2): s1 = sorted(s1) s2 = sorted(s2) if s1 == s2: print("This is an anagram") else: print("This is not an a...
5b0f6ed9a64ded26d94b96dd86d62789a9208acc
xuqil/DataStructures
/第三章线性表/链接表/单链表/单链表反转.py
1,318
3.84375
4
class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def rev(link): pre = link cur = link.next pre.next = None # 第一个元素变为最后一个元素,它的next指向None while cur: temp = cur.next cur.next = pre pre = cur cur = temp return ...
4ca6087351dd33a465efa05fcf7ece8b6982c835
fyber/jenkins_test
/sample.py
90
3.703125
4
import math NUMBER = 16 print('Square root of {} is {}'.format(NUMBER, math.sqrt(16)))
ba3748d39d4fa6016cd8ef96851c73a9aa50d469
danieldiniz1/blue
/aula 14.05/exercicio 3.py
1,297
3.828125
4
opc = True gabriel = 0 pedro = 0 matheus = 0 ana = 0 nulo = 0 branco = 0 total = 0 while opc ==True : print("eleição! numero dos candidatos: 1- gabriel, 2- pedro, 3- matheus, 4- ana, 5- NULO, 6- BRANCO.") voto = int(input("Digite seu voto: ")) if voto == 1 : gabriel += 1 total += 1 ...
7b21c840e4b72e5f500137d20e2b392f7a6549b1
donfreiday/cs50-web-programming
/lecture02/name.py
108
4.21875
4
print("Enter your name: "); name = input() # f is new in python 3.6, format string print(f"Hello, {name}!")
aeb8515ed95abcc3ab69595ae6533af5652aaba9
stOracle/Migrate
/Programming/CS303E/bmi.py
316
4.34375
4
#prompt user to enter their weight and height w = float(input("Enter your weight in pounds:")) h = float(input("Enter your height in inches:")) #convert weight to kilograms k = w * .45359237 #convert height to meters m = h * .0254 #calculate bmi bmi = k / m ** 2 #print BMI result print("BMI is" , bmi , end=".")
18c7fb246077d25c323ae61efff2c07fe09042e0
jhondare/WeJapa
/wave-1/Lab2of1.py
131
3.828125
4
street = "No 5 Francis Road" city = "Sambisa City" print("The stubborn shild lives at {}, which is in {}".format(street, city))
318407d0b315c828efdd0c8b171b2a3a1106abb8
Psingh12354/PythonNotes-Internshalla
/code/IF_ELSE.py
343
4.125
4
price=int(input("Enter the price : ")) quantity=int(input("Enter quantity : ")) amount=price*quantity if amount>1000: print("You got a discount of 10%") discount=amount*10/100 amount-=discount else: print("You got a discount of 5%") discount=amount*5/100 amount-=discount print("Total ...
2c58020eaf8c1753c69a27ee3dfdeaa3fd876fc0
raghavddps2/Technical-Interview-Prep-1
/UD_DSA/Course1/Recursion/subsets.py
290
3.71875
4
import copy def subsets(arr): if len(arr) == 0: return [[]] else: res = [] temp = arr[0] res = subsets(arr[1:]) for i in copy.deepcopy(res): i.insert(0,temp) res.append(i) return res print(subsets([1,2]))
20eb9d6e2ebf1f28749e47aebeafb984c9e537e1
ardicsobutay/phys48y
/Assignment 2/Homework 1/hw1_huseyinanilgunduz.py
744
4.0625
4
balance = float(raw_input('Please enter balance:')) annualInterestRate = float(raw_input('Please enter annual Interest Rate:')) monthlyPaymentRate = float(raw_input('Please enter monthly Payment Rate:')) monthintrate = annualInterestRate / 12.0 totalpaid=0.0 for i in range(12): minmonthpay = monthlyPaym...
4a763fa79818d9b03f185576a0460e7ccea03a32
javacode123/oj
/leetcode/middle/treeGraph/kSmall.py
972
3.921875
4
# -*- coding: utf-8 -*- # @Time : 2019-08-23 12:48 # @Author : Zhangjialuo # @mail : zhang_jia_luo@foxmail.com # @File : kSmall.py # @Software: PyCharm # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = N...
d2e25f7a65ba1cdbff2dc63f72f9added65b95ff
sashkarivkind/imagewalker
/fbm_mbm_lic/mbm.py
4,843
3.5625
4
"""Generate realizations of multifractional Brownian motion.""" import inspect from math import gamma import numpy as np class MBM(object): """The MBM class. A class for generating multifractional Brownian motion or multifractional Gaussian noise using approximate methods. """ def __init__(self...
28b488c744f253b61e20f65636e5755bcd2d426e
EmilioAlzarif/intro-to-python
/week 5/Practical/P10.py
143
3.828125
4
list1= [1, 2, 43, 5, 213, 4] def list_func(list1): for x in list1: yield x value = list_func(list1) print(value) print(next(value))
ecf663ad4537e8f4f2a3a3068b12407cb0cc3e69
archana986/Python-Coding-Projects-Udacity
/bikeshare Project 2.py
27,516
3.875
4
import csv import calendar import datetime from collections import Counter from operator import itemgetter import pprint import time def get_city(): '''Asks the user for a city and returns the filename for that city's bike share data. Args: none. Returns: (str) Filename for a city's bi...
d779a6553d646d7ce6347aa8c55e975afad77198
swapnilvishwakarma/100_Days_of_Coding_Challenge
/12.Find_First_and_Last_Position_of_Element_in_Sorted_Array.py
497
3.796875
4
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a # given target value. # If target is not found in the array, return [-1, -1]. from bisect import bisect_left, bisect_right class Solution: def searchRange(self, nums: list, target: int) -> list: l = b...
75a169c5da376cabac50cef74656576ed17cab24
JonahEgashira/competitive-programming
/abc158b.py
114
3.671875
4
x = int(input()) ans = 0 money = 100 while money < x: money *= 1.01 money = int(money) ans += 1 print(ans)
ec327ec7923093333c3585a395808a277bc7e9bf
Minkov/python-oop-2020-02
/encapsulation/1_person.py
542
3.8125
4
class Person: def __init__(self, name, age): self.__name = name self.__age = age def __validate_age(self, age): if age < 0 or age > 125: raise ValueError('Invalid age value') def get_name(self): return self.__name def get_age(self): return self.__ag...
2da27a7c0109f54641fc887100444e22217da6ca
naimucar/8.hafta_odevler-Fonksiyonlar
/BUYUK kucukharf fonk.py
579
3.78125
4
#Kullanıcıdan bir input alan ve bu inputun içindeki büyük ve küçük harf # sayılarının veren bir fonksiyon yazınız. def buyuk_kucuk_harf(metin=input('metin giriniz:')): sayac1=0 sayac2=0 sayac3=0 for sayac in metin: if sayac.islower():#kucuk harf kontrolu sayac1+=1 if sayac.is...
675bdf361b67001df0e7d96124b1ba1cf2b75136
psnluiz/exercises-and-stuff
/Soma de dez números inteiros.py
395
4.125
4
n = 1 soma = 0 while (n <= 10): if n == 1: num = int(input("Type the 1st number: ")) elif n == 2: num = int(input("Type the 2nd number: ")) elif n == 3: num = int(input("Type the 3rd number: ")) else: num = int(input("The the {}th number: ".format(n)) n += 1 soma...
b834d729614414dd5ff6f35b17aab19917c8bfed
eragon11/codekata
/Beginner/set1/hellon.py
97
3.796875
4
n = int(input()); if (n == 0): print(); else: for i in range(n): print("Hello");
f9d0b6738ec933f6bfb0d64b8f998c9954dd9e33
easystart-co/python
/MultiThreading/main9.py
1,511
4.15625
4
# 用队列进行多线程数据传递 import threading import time def threading1(): global numA,numB add_times = 100 time.sleep(1) for i in range(add_times): lockR.acquire() #获取锁 numA = numA+1 thread_name = threading.current_thread().getName() print(thread_name+'-numA:'+str(numA)) ...
6ca546991e83505cc32efe4f4632404a73d04203
daniel-reich/ubiquitous-fiesta
/r8jXYt5dQ3puspQfJ_21.py
400
4.0625
4
def split(txt): new_sentence = "" for char in txt: if is_vowel(char): new_sentence += char ​ for char in txt: if not is_vowel(char): new_sentence += char ​ return new_sentence ​ ​ def is_vowel(character): vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o",...
1b9fbecacd4c3af89cd4c0f2ff1aa5231e31d463
salisu14/learn-python-programming
/Q4.py
287
4.1875
4
#!usr/bin/env python3 num1 = input("Enter First Number: ") num2 = input("Enter Second Number: ") if num1 > num2: print(num1,"is greater than", num2) elif num2 > num1: print(num2,"is greater than", num1) elif num2 == num1: print(num1, "and", num2, "are equal")
fa793b5457e3d2ad1f5a85844e5965896f829151
okq550/PythonExamples
/PIRPLE/HomeWorks/main8.py
2,637
4.25
4
import os def readFile(fileName): #Print the content of the passed file print('** Operation Read For File', fileName , '**') myFileHandler = open(fileName, 'r') print(myFileHandler.read()) myFileHandler.close() return True def appendToFile(fileName): #Append content to the passed file ...
5c4b17f07d9ea9958d3a332b4c2815757f2ba38b
Devin6Tam/python_practice
/lesson101/practice_day03.py
1,292
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/15 17:51 # @Author : tanxw """ 6、编写代码设计简易计算器,用户通过3次输入,可以进行两个整数的加减乘除运算并输出结果。 7、闰年判断程序: if判断、格式化输出、运算符 要求: 输入一个有效的年份,判断是不是闰年; 如果是闰年,则打印“***年是闰年”;否则打印“***年不是闰年”; 如输入"2017",将打印“2017年不是闰年” """ num_a = int(input("请输入一个整数:")) operator = input("请输入一个运算符:") n...
fae7fece7248517b6f6f5c5f335ffd68352b596a
rmiguelito/python-rest
/get-movies.py
919
3.609375
4
import requests import json #isto eh uma funcao def requisicao(titulo): #tratando erros com try except, ainda tenho que entender os mecanismos internos no VSCODE try: req = requests.get('http://www.omdbapi.com/?apikey=a9b0d085&t=' + titulo) dicionario = json.loads(req.text) return di...
77c86462ea9cca4fbd8e3a6307ad501bb8924c69
XMK233/Leetcode-Journey
/py-Jindian/16.02.py
870
3.546875
4
''' [面试题 16.02. 单词频率 - 力扣(LeetCode)](https://leetcode-cn.com/problems/words-frequency-lcci) 设计一个方法,找出任意指定单词在一本书中的出现频率。 你的实现应该支持如下操作: WordsFrequency(book)构造函数,参数为字符串数组构成的一本书 get(word)查询指定单词在书中出现的频率 示例: WordsFrequency wordsFrequency = new WordsFrequency({"i", "have", "an", "apple", "he", "have", "a", "pen"}); wo...
25836c343dbc69c704744c70bc7569bfb4530eb1
nathy-mesquita/script_python
/Desafio_17.py
382
4.125
4
#Cálculo do Seno, Cosseno e Tangente from math import radians, sin, cos, tan num = float (input (' Insira o valor do ângulo: ')) sen = sin(radians(num)) print ('O Seno do ângulo {} é {:.2f}'.format(num, sen)) cos = cos(radians(num)) print ('O Cosseno do ângulo {} é {:.2f}'.format(num,cos)) tan = tan(radians(num)) print...
bf54a9a9e4d308eeeeed4cc4fb81720c0098fdc5
alvkao58/pylot
/pylot/control/messages.py
1,240
3.609375
4
import erdos class ControlMessage(erdos.Message): """ This class represents a message to be used to send control commands. Attributes: steer: Steer angle between [-1.0, 1.0]. throttle: Throttle command between [0.0, 1.0]. brake: Brake command between [0.0, 1.0]. hand_brake: Bo...
308c9a9b0baa25166eb2c68fec949a14ff22d29a
sryhan/Coding-Exercises
/codingbat_exercises/warmup1_missing_char.py
414
4.15625
4
""" Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive) """ def missing_char(str, n): if str == "": return False if n > len(str...
25e2210aabfca90f7bff1a1ac02a3c5eb05b95f9
ZhehanZhang/Leetcode-NowCoder-Practice
/lc849.py
410
3.53125
4
##https://leetcode.com/problems/maximize-distance-to-closest-person/ ##通过计算连续0的个数来决定坐在哪一组0的中间(或者坐在最两边) n = int(input()) res = [] for i in range(n): stair = int(input()) if stair == 1: print(0) else: f1, f2 = 0,1 for s in range(stair): f1, f2 = f2, f1+f2 res.appen...
ef50eee05af6658c33ba0d9127fd1452aab9b78a
nub8p/2020-Summer-Jookgorithm
/강재민/7월/[20.07.06]1002.py
568
3.546875
4
import math T = int( input() ) for i in range(T): input_list = input().split() j = ( int(input_list[0]), int(input_list[1]) ) b = ( int(input_list[3]), int(input_list[4]) ) r1 = int(input_list[2]) r2 = int(input_list[5]) distance = math.sqrt( ( j[0] - b[0] )**2 + (j[1] - b[1] )**2 ) if( j...
2e5a107e9dc14ff0ee3dab7b9b6f795ba4542872
nnelluri928/DailyByte
/intersetion_numbers.py
997
4.25
4
''' This question is asked by Google. Given two integer arrays, return their intersection. Note: the intersection is the set of elements that are common to both arrays. Ex: Given the following arrays... nums1 = [2, 4, 4, 2], nums2 = [2, 4], return [2, 4] nums1 = [1, 2, 3, 3], nums2 = [3, 3], return [3] nums1 = [2, 4,...
6eb711ec4e534d0c8a6d4e4c8943a4b4cc583467
tosunufuk/pEuler
/Python/pProblem_2.py
369
3.5
4
from datetime import datetime startTime = datetime.now() maxVal = 4000000; val = 1; pastVal1 = 0; temp = 0; total = 0; while val < maxVal : temp = val; val += pastVal1; pastVal1 = temp; if ((val & 1) == 0) : total += val; print(total) ...
20147c9ceab8e0ca59667b57b43c58f1f1fc8609
gogenich/homework_vasiliy_redkin
/lesson_2/the_task_5.py
382
3.6875
4
l = [7, 6, 4, 3, 3, 2] namber = int(input('введите целое положительное число: ')) print(f'старый список: {l}') i = 0 for x in l: if namber > x: l.insert(i, namber) break i = i + 1 print(f'новый список с введенным числом: {l}') print(f'позиция введенного числа: {i}')
b7b30612c56a2e52edb5f59e9f356c1f71732b2d
WILDCHAP/python_study_std
/python_Project_03/hash哈希.py
338
4.1875
4
''' Python中内置有一个名字叫做hash(o)的函数 。接收一个不可变类型的数据作为参数 。返回结果是一个整数 ''' # 无论什么时候输出都一样 print(hash(1)) print(hash("hellow")) print(hash((1,))) # 不能列表(因为可变) # print(hash([1, 2])) # 不能字典(因为可变) # print(hash({1: 2}))
20c0a9a41928d8fda89dba26ae86451726bbb770
bpate05/PyBank-PyPoll
/mainPP.py
2,425
3.765625
4
#PyPoll import os import csv # set a csv file path for the data poll_csv = os.path.join('election_data.csv') # define function def get_results(data): # define variables totalVotesCount = 0 votes = [] candidateCount = [] uniqueCandidates = [] percent = [] # start looping through rows...
2d79716197efaee245bf7ea7f99e29b244c9bdc8
KaisChebata/Computing-in-Python-III-Data-Structures-GTx-CS1301xIII-Exercises
/Extra Practice Problems/IMDb2.py
1,921
4.125
4
#Write a function called imdb_dictionary. imdb_dictionary #should have one parameter, a string representing a #filename. # #On each row of the file will be a comma-and-space-separated #list of movies, then a colon, then a performer's name. For #example, one file's contents could be: # #Avengers: Infinity War, Sherlock ...
a5b5a7495632910ba32e0db22f2041cd798de9d4
Vencislav-Dzhukelov/101-3
/week7/2-SQL-Starter/create_company.py
1,053
3.96875
4
import sqlite3 def create(): db = sqlite3.connect('company.db') cursor = db.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS company(id INTEGER PRIMARY KEY, name TEXT, monthly_salary REAL, yearly_bonus REAL, position TEXT) """ cursor.execute(create_table_quer...