blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
4ce8c121e9e60bbc5de392c9ce9a92cc4b1a366f
harshita1804/UCSD
/ece143/hw6/chunkify.py
1,109
3.609375
4
import os def split_by_n(fname,n=3): ''' Split files into sub files of near same size fname : Input file name n is the number of segments ''' assert isinstance(fname, str) assert isinstance(n, int) assert n>0 file_size = os.stat(fname).st_size chunk_size = file_size...
9d1ae5fb7496ca2ff213f5dc028726fc2e02217d
yzh1994414/LetsCode
/HUAWEI_TEST_07.py
446
3.703125
4
'''题目描述 写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。 输入描述: 输入一个正浮点数值 输出描述: 输出该数值的近似整数值 示例1 输入 复制 5.5 输出 复制 6''' inputs = float(input()) int_inputs = int(inputs) if inputs-int_inputs >= 0.5: print(int_inputs+1) else : print(int_inputs)
a54edf2c05af2bea8199a4bb0b8e6226d13336dc
sususaiasusubendera/Tubes-Doraemonangis
/exit.py
675
3.734375
4
import sys from save import save from save import nosave def exit(role): if (role == ""): nosave() sys.exit("Terima kasih!") # else ans = str(input("Apakah anda mau melakukan penyimpanan file yang sudah diubah? (y/n) ")) while ((ans != 'y') and (ans != 'Y') and (ans != 'n') and (ans != 'N')): print("Jaw...
6c45aed589bb693a7adc0a4a27d8665cce376a45
raghuprasadks/pythontutoriallatest
/db-mysql/3-insertdata.py
626
3.609375
4
import pymysql # Open database connection db = pymysql.connect("localhost","internuser","123","pythoninterndb") # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to INSERT a record into the database. sql = "INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('%...
ac0599fe18d396bfaaaa29325621be2aaef6fabd
jhiltonsantos/ADS-Algoritmos-IFPI
/Atividade_Fabio_01/fabio01_39_expressoes.py
450
3.953125
4
#entrada numero_a = float (input('Digite o A: ')) numero_b = float (input('Digite o B: ')) numero_c = float (input('Digite o C: ')) # processamento expressao_r = (numero_a + numero_b) ** 2 expressao_s = (numero_b + numero_c) ** 2 expressao_d = (expressao_r + expressao_s) / 2 # saida print('Resultado da exp...
68b502c206780634aa51e1404e7e30b68c49025f
vincent4986/Python
/TimeAssignment.py
1,869
4.15625
4
""" NAME: WASSWA VINCENT STUDENT NO: 214018980 REG NO: 14/U/15890/EVE """ import calendar print("This Program is intended to produce the exact date you were born") print("................................................................") dy = mth = yr = None #PROGRAM ACCEPTS INTEGER TYPE VARIABLES #while ...
6d9746f9c1fe2146d15080abd73c5d31859c02af
Velikoa/Python_for_Data_Science_and_Machine_Learning_Course
/13.2 Data Capstone - FInance.py
3,955
3.6875
4
from pandas_datareader import data, wb import pandas as pd import numpy as np import datetime import seaborn as sns import matplotlib.pyplot as plt #Need to first create a date object using the datetime module otherwise python wont see it as a date but a string which is wrong. start_date = datetime.datetime(20...
0d2c8ad6af81d8853db40a6481db9dcac9d17882
ganrod/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-in-Python
/lecture 5 greatest common divisor iterative.py
210
3.578125
4
def gcdIter(a, b): min = a if min > b: min = b while min > 1: if a%min == 0 and b%min == 0: return min else: min -= 1 print(gcdIter(8, 12))
7996b99e6e8db7f93701b79d396d76b6d9a574df
jixinfeng/leetcode-soln
/python/023_merge_k_sorted_lists.py
956
3.96875
4
""" Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ ...
6c7705ba9c81f4334f815084797d0be762472c43
vtymch12/pp1
/Thonny programs/zad 04_7.py
243
3.734375
4
def numbers(): num = ("1 2 3\n4 5 6\n7 8 9") return num print(numbers()) import re str = "The rain in Spain" x = re.findall("Spain", str) print(x) if (x): print("Yes, there is a match!") else: print("No match")
fb810fc8ebb1648992503d73685b61474c97a077
oransimhony/nand2tetris
/06/Assembler/code.py
2,032
3.578125
4
class Code(object): def dest(self, mnemonic): if mnemonic == 'null': return "000" elif mnemonic == 'M': return "001" elif mnemonic == 'D': return "010" elif mnemonic == 'MD': return "011" elif mnemonic == 'A': return "100" elif mnemonic == 'AM': return "101" elif mnemonic == 'AD': re...
ad0b1428b3fc41880144742d4e9bc7d951fb8691
zinsmatt/Programming
/CodeForces/58A-Chat_room.py
184
3.609375
4
s = input() target = "hello" a = 0 for c in s: if c == target[a]: a += 1 if a >= len(target): break if a == len(target): print("YES") else: print("NO")
14a533d4eb3ef5d4068c3a41afd4523fa0068e2a
anasatasiyazyamzina/python_1
/zyamzina_hometask_presentation.py
4,849
3.9375
4
########################################## # 1 слайд ########################################## # 1 задание def daysforsomekm(km): a = 0 days = 1 while a <= km: a += 2 ** days days = days + 1 return days k = 10000 day = daysforsomekm(k) print("1. Понадобится", day, "дней...
f6731540b8277c590144ba3bdc929d88c0a86799
BenWarwick-Champion/Euler
/python/p28.py
483
3.828125
4
# Project Euler # Problem 28: Number of spiral diagonals def find_diagonals(n): '''Finds diagonals of an n*n spiral''' current, line, count = n**2, n-1, 0 diagonals = [] while current != 1: diagonals.append(current) current -= line count += 1 if count == 4: ...
8ee54a9187f8646024603535741e979161ec8b85
JackRyannn/LeetCode
/20.py
710
3.84375
4
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ l = [] for i in s: if i =='(' or i == '[' or i =='{': l.append(i) else: if not l: return False p...
f6834a08cca351b9f404d41f836b11d89a0c3622
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/2367.py
568
3.515625
4
n_cases = int(raw_input()) def read_int(): return int(raw_input()) for case in range(1, n_cases+1): C, F, X = map(float, raw_input().split()) rate = 2.0 time_elapsed = 0.0 remaining_time = X / rate while True: new_remaining_time = X / (rate + F) new_farm_time = C / rate total_remaining_time = new_farm_...
8bb96c180dcbf06f0781178feac73a8225d39e7c
wonjongah/multicampus_IoT
/인터페이스 실습코드/workspace/workspace/01_python/chapter3/ex01_19.py
108
3.671875
4
x = 10 y = 20 # x와 y의 값을 교환하세요 temp = y y = x x = temp print("x: ", x) print("y: ", y)
ae0887b3b9a478609e9d96fe8df82a8142b0499f
wuxu1019/leetcode_sophia
/medium/others/test_621_Task_Scheduler.py
1,925
4.09375
4
""" Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. However, there is a non-negat...
77dc0a4135a19ca52d8fcd2ac552799e834b69d1
dook-robotics/Database
/scripts/renameExt.py
865
3.640625
4
## rename.py ## ## Rename files with .JPG to .jpg ## # # Authors: # Mikian Musser - https://github.com/mm909 # Eric Becerril-Blas - https://github.com/lordbecerril # Zoyla O - https://github.com/ZoylaO # Austin Janushan - https://github.com/Janushan-Austin # Giovanny Vazquez - https://github.com/giovannyVazqu...
705101b00a48d54591afcdfe07677c0318ccd0bd
Nutpapat/Python_Lab
/py/ol1.py
233
3.53125
4
"""LOL""" def main(): """LOL""" tum = float(input()) tuu = float(input()) kuku = (tum * tuu) print("Subtotal:", int(tum)) print("Tax ("+str(tuu*100)+"%):", int(kuku)) print("Total:", int(tum+kuku)) main()
ce370ee2790220339068546f6059bcc0e722e24f
maxwayne-mills/qr_code_gen
/gen_gr_code.py
378
3.578125
4
#!/usr/bin/env python3 import pyqrcode def gen_qr_code(user_url): url = pyqrcode.create(user_url) url.png('url.png', scale=8) # Change scale level to increase or decrease size of png image print("Printing QR code for URL " + str(user_url) ) print(url.terminal()) if __name__ == '__main__': ...
119ebe0ae5954220af8685aac8837500a1c2bc2d
SilentPenguin/React.py
/__init__.py
948
3.984375
4
from decorators import call, sender, receiver, messenger ''' Senders are callables which call subsiquent methods when called Receivers are callables which receive calls from Senders Messengers provide the functionality of both Senders and Receivers The call function formats whatever you pass it, for the internals of ...
f19d0dd02e7f61100ded317d8ecf426b2e55afd3
JollenWang/study
/python/python_prj/default_param.py
236
3.5
4
#!/usr/bin/python #this is a program demo of default parameters def talk(msg,count = 1): print('msg=', msg); msg = input('input a string:'); print((msg +'\n') * count); talk('Jollen\n'); talk('Happy!\n', 6);
b0e2d6292731ffe05e5cd7c88721b3e0c93cbbc5
NaifeiPan/oop-assignment-NaifeiPan
/src/read.py
661
3.53125
4
import csv import os from abc import ABC, abstractmethod class Read(ABC): def __init__(self, dataset): self.dataset = os.getcwd() + dataset super().__init__() @abstractmethod def read(self): fields = [] rows = [] with open(self.dataset, 'r') as csvfile: ...
a2649cb83b2f2fda8f6b4ba9cc34fe80810fa577
netanelpr/NumricalAnalysis
/cleanfiles/assignment4A.py
3,058
3.84375
4
""" In this assignment you should fit a model function of your choice to data that you sample from a given function. The sampled data is very noisy so you should minimize the mean least squares between the model you fit and the data points you sample. During the testing of this assignment running time will be co...
6e40f2f1b7470d3aa8a7cdf32111b9bd8261ec46
iduseev/LeetCode
/LeetCode_Weekly_Contest/Maximum_Absolute_Sum_of_Any_Subarray_1749/kadanes_algo.py
462
3.84375
4
#!/bin/python '''The program for the Kadane's algorithm explanation''' def maxSubArray(n, arr): local_max = global_max = 0 for i in range(n): local_max = max(arr[i], arr[i] + local_max) if local_max > global_max: global_max = local_max return global_max if __n...
cd5808d6a56b7212e154ead0f76bca0884d0565e
Chandrakantgit/Tkinter
/images.py
2,081
3.546875
4
from tkinter import * from PIL import ImageTk,Image root=Tk() root.title("images..images") ##root.iconbitmap('address of icon in memory') #python aonly supports two image type .gif and .pnm # we have to import a libray pil (Python Image Library),we use pillow updated version of it def forward(image_number): ...
fd75d181e576c4811d978756867c73fa46bc81f6
AfaqAnwar/Machine-Learning-Basics
/decision_tree/fruit_classification/apples_oranges_dt.py
607
3.734375
4
from sklearn import tree """ Simple Decision Tree Classifier. @Author Afaq Anwar @Version 02/23/2019 """ # Also sometimes represented as X # [Weight (Grams), Smooth or Bumpy (1 = smooth, 0 = bumpy) features = [[130, 1], [130, 1], [150, 0], [170, 0]] # Also sometimes represented as y # 0 = Apple, 1 = Orange labels = ...
43b3a388c2f7b47c0cda6eca5ade2e6d103dc59e
bensonlee5/priority_health
/dialer/create_call_list.py
4,164
3.5625
4
from datetime import datetime from datetime import timedelta import pandas as pd import argparse def calc_recency(df_input): """ Calculates # of days since patient was last touched by specific action type If the patient has never been touched, 99999 is populated in recency field :param df_input: Inp...
c4d2b4e8944303b494729d41c256e6edf5652144
ankit-119/acadview-assignements
/decision control and loops/ques4.py
441
4.0625
4
age=int(input("enter the age")) sex=input("Enter sex(M/F)") status=input("Enter the status(Y/N)") if(age<20 or age>60): print("ERROR") elif(sex=='F' or sex=='f'): print("This person will work only in urban areas") elif(age>=20 or age<=40): print("this person can work anywhere") elif(sex=='M' and (ag...
87a469eaf867f954d4bc30cb40fd444d247c5dd5
cddolanc/cct-start
/wk8/Wk1-8/exerciseswk8.py
640
3.953125
4
# try: # for i in ['a','b','c']: # print(i**2) # except: # print("This is not correct") # try: # x = 5 # y = 0 # z = x/y # except: # print("There seems to be a problem") # finally: # print('All Done.') from math import sqrt def ask(): while True: try: ...
69cdbd070cbee60260563836e32513c3ef789507
Sakae-o/Software-Engineering-Assignment1
/segmentation.py
2,511
3.71875
4
import os def segment(root): ''' Break each row of the text into a list of individual words without ' ', '(', ')', ':' , and ',', then merge those lists into one list which will be returned. ''' f = open(root, "r") lines = f.readlines() result = [] is_annotation = 0 ...
343618ed7484a4d1cdd515547a03b0724fd1c4bf
SirDifferential/algorithms
/tournament/roundrobin.py
6,316
4.21875
4
# Gives an example on how to use Round Robin in a tournament # There are some Players playing a generic tournament and getting score # by random chance. The program assigns all matches in advance, then plays the # tournament and finally prints the final score # The number of matches needed for n players is (n/2)*(n-1) ...
58049cb73ac9ead3ec58a92dc4277b18e724632b
grilhami/Attar-Git-Practice
/handzdirty/Practices/reverseString.py
398
3.578125
4
isi = input() #blue-green-yellow balik = lambda isi : isi.split("-") # isi = isi.split("-") # ['blue', 'green', 'yellow'] # isi.reverse() jawab = balik(isi) jawab.reverse() def ini_function(masuk): hasil='' for i in masuk: if(i != masuk[-1]): hasil += i + '-' else: ...
bb3b901b00051498a034d3c44a4f56920364f43a
yaolin-Li/Python-note
/Demo/venv/src/day01/test09.py
366
3.765625
4
import random answer = random.randint(1,100) counter = 0 while True: counter += 1 number = int(input('Please input number:')) if number < answer: print('bigger') elif number > answer: print('smaller') else: print("right!") break print('You guess %d time'%counter) if ...
8cf70ba54462a715c9ed8c4811532b6c3414958e
tremlab/HB_shopping_list
/shopping_list.py
2,490
4.375
4
global_shopping_list = {'Target':['apples','bananas']} def Menu(): print "0 - Main Menu" print "1 - Show all lists." print "2 - Show a specific list." print "3 - Add a new shopping list." print "4 - Add an item to a shopping list." print "5 - Remove an item from a shopping list." p...
396877dc911db78c6167a0146052ce0a4b2787e9
yeseongcho/-
/프로그래밍1/hw13_p1-1.py
3,488
3.609375
4
""" Name : 조예성 Student ID : 21600685 Description : 이 함수는 Player 4명이 임의로 카드를 뽑아 그 카드 목록을 print해주는 함수입니다. """ import random import time # 카드 생성 class Card : # Card class variable suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"] rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10...
d02802f9d17d27c2b4a70f72317ee110e4b8a5eb
mathias-ta/alx-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
430
3.703125
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): len_a = len(tuple_a) len_b = len(tuple_b) if len_a <= 0: a0 = 0 else: a0 = tuple_a[0] if len_b <= 0: b0 = 0 else: b0 = tuple_b[0] if len_a <= 1: a1 = 0 else: a1 = tuple_a[1] if l...
f12cbdbae2e5c6c355950204cadd54920945228e
mvela/PythonPractice
/classes.py
298
3.609375
4
#basic class class animal: def __init__(self, anim, gen, weig): self.animal = anim self.gender = gen self.weight = weig animal1 = animal("dog", "male", 56) print(animal1.animal, animal1.gender, animal1.weight) animal1.animal = "cat" print(animal1.animal, animal1.gender, animal1.weight)
86c9dbe04c30a39d9c5eec0018cb9ba225d6b68c
helei0147/pathfinding
/dijkstra.py
4,952
3.65625
4
import sys,os,math,string MAX_COST=10086 BLOCK=3 FLAT=0 SOURCE=1 TARGET=2 TRIAL=4 WIN_WIDTH=1920 WIN_HEIGHT=1080 DEFAULT_FRAME_WIDTH=50 ''' rows=input("Please enter the number of rows:") cols=input("Please enter the number of cols:") matrix=[[]for i in range(rows)] for i in range(rows): for j in range(cols): ...
9a43386c8c860221f3f8e5e24452e4612927109f
Ashish-Yadav/TDDPythonQuiz
/FizzBuzz.py
1,105
3.71875
4
""" Q1. Why is the report method untestable ? [2 pts] Ans:- The report method has external depndencies. It depends on the "open function" and the Txt file. Q2. How will you change the api of the report method to make it more testable ? [2 pts] Ans:- The API of the report method can be changed by the the number of ...
3b559d42f113d2abcbb68ac8210152847a326b2f
BhagyaSri22/code_chef_march_challenge_2016
/chef_and_special_dish.py
1,014
3.9375
4
''' https://www.codechef.com/MARCH16/problems/CHEFSPL One day, Chef prepared D brand new dishes. He named the i-th dish by a string Si. After the cooking, he decided to categorize each of these D dishes as special or not. A dish Si is called special if it's name (i.e. the string Si) can be represented in the form of a ...
23e60dd4ab899181fde63477420841fadafec73b
Autobahn1racer/Python_school
/palindrome_no.py
326
4
4
def palindrome(n): z=str(n) l=len(z) t=n s=0 for i in range(l,-1,-1): d=t%10 N=d*(10**(i-1)) s=s+N t=t//10 if s==n: print("It is a palindrome.") else: print("It is not a palindrome.") n=int(input("Enter a number: ")) palindrome(n) ...
ffd165e0826f228dd4ddf4e59e17ec8fb723b1c0
MarshalLeeeeee/myLeetCodes
/10-expressionMatch.py
3,551
4.1875
4
''' 10. Regular Expression Matching Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be em...
a9a4fef596fe2c1a1b888399d0908c0adb998962
dictator-x/practise_as
/algorithm/leetCode/0543_diameter_of_binary_tree.py
561
3.578125
4
""" 543. Diameter of Binary Tree """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: ret = 1 def search(root): if not ...
410578f966b856119a1ddf68b49e9c0ba7147e5f
oskar-zhang/Python-Crash-Course
/Chapter 6 Dictionaries/favorite_numbers.py
1,242
4.4375
4
""" 6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers. Think of five names, and use them as keys in your dictionary. Think of a favorite number for each person, and store each as a value in your dictionary. Print each person’s name and their favorite number. For even more fun, poll a few friend...
69d320cffc0f851e0f236cc9e97b6942f257dd60
adrianoazevedo/codesfiap
/fase2/cap2/RM88447_EX03.py
1,142
3.953125
4
print("====Apuração de Votos - Melhor dia para Lives====") segunda = int(input("Insira os votos da Segunda-feira: ")) # variável dia terca = int(input("Insira os votos da Terça-feira: ")) # variável dia quarta = int(input("Insira os votos da Quarta-feira: ")) # variável dia quinta = int(input("Insira os votos da...
110ef0de9a7174c298ffda640a731f6dda22d0ad
JHanek3/HackerRank
/python/loops.py
355
3.984375
4
#Task #The provided code stub reads an integer,n, from STDIN. For all non-negative integers i < n, print . #print i^2 #Input Format #The first and only line contains the integer n. #Output Format #Print n lines, one corresponding to each i, def square(): n = int(input()) for i in range(n): if i >= 0:...
8c8cff27ab06f31a3b24be038decff2b87dc102f
icejoywoo/HelloPython
/src/lab/fizz_buzz.py
674
3.796875
4
#!/bin/env python # ^_^ encoding: utf-8 ^_^ # @author: icejoywoo # @date: 14-2-14 # 写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”, # 对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。 # 这个解法很精辟啊 simple = ["fizz"[x % 3 * 4::] + "buzz"[x % 5 * 4::] or x for x in range(1, 101)] print simple result = [] for i in range(1, 101): x, y = ...
7e89727a6af33362bd8a29afe128059196d8f69a
psabhishek/webcrawl
/wikistates.py
1,112
3.671875
4
''' Given is a page having a list of all the states and union territories of India. Try the following: Fetch count of States and Union Territories Fetch population and date of formation of each state ''' import urllib import requests from lxml import html url = "https://en.wikipedia.org/wiki/States_and_union...
7d62d89d5a89b98808950d8284e8b2c48310e0c5
alifele/Python
/Desing patterns in python/Datalogger and Signleton Object/singleton_object.py
823
3.671875
4
class Singleton_object(object): class __Singleto_object(): def __init__(self): self.val = None def __str__(self): return "{0!r}{1}".format(self, self.val) instance = None def __new__(cls): if not Singleton_object.instance: Singleton_object.in...
74d0683acfd3ef17156a7ffe983fd206cae1ed29
salisu14/learn-python-programming
/say_hello.py
288
3.703125
4
#!/usr/bin/env python3 def say_hello(name): name = ['Zainab', 'Muhd', 'Haidar'] if name == name[0]: print(name[0]) else: print(name[1]) def main(): name = input("Enter your name: ") say_hello(name) if __name__ == "__main__": main()
c258ad84f629d60f1384f58f9c1402ebe4f522af
gosyang/leetcode
/Algorithms/tree/501.find-mode-in-binary-search-tree/find-mode-in-binary-search-tree.py
1,887
3.796875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017 gosyang. All Rights Reserved # """ File: find-mode-in-binary-search-tree Author: gosyang Date: 2020/2/8 11:28 AM """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.le...
0baf053a9a52db4866fd756b5855eb1712800d39
Veranchos/ftyers.github.io
/2018-komp-ling/practicals/Practical 2/transliterate.py
1,539
3.734375
4
def read_text(filename): f = open(filename,'r', encoding='UTF-8') text = f.read() text = text.replace('\ufeff', '') return text def write_new_text(filepath, text): new_text = open(filepath, 'w+', encoding='UTF-8') new_text.write(text) new_text.close() return new_text def create_map...
16878cf157fe11a83ed5cc1e0a4f8112bd8ef226
asutosh04choubey/asutosh-choubey
/2tictac.py
6,406
4.34375
4
from random import randrange # add a variable to store current player current_player = '' # game winner winner = '' ## # First step : init board # A Tic Tac Toc board is a 2 dimensions array # eg : 3 x 3 => 3 rows and 3 columns ## def init_board(): # we must put the new variable current_player as global to modif...
f68891bc510307cfc7dfe2fb13141175caefe206
InCodeLearning/InCodeLearning-Python3
/coding_style/indentation.py
396
3.671875
4
# google used to indent 2 spaces, mixed indentation is fine in same file # PEP 8 recommends 4 spaces # https://www.reddit.com/r/learnpython/comments/1xfoxz/pep_indentation_using_4_spaces_vs_googles_2_spaces/ if 1 + 1 == 2: print("hello with 2 spaces indentation") # print("hello with 4 spaces same block") not ok In...
335c0ab0125e1fc2e9aa13d3f675d1a8479ddaa7
BuildABuddha/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
1,581
3.984375
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList:...
7f04c17c9f93d4cb0faf70385fce936ddcb8b671
fhightower/my-cipher
/cipher.py
923
3.609375
4
import random import string JOIN_SYMBOL = ',' def _create_encoding_data(s: str) -> dict: s += string.printable return dict(enumerate(s)) def _get_index_for_char(char: str, encoding_data: dict) -> int: possible_indexes = [index for index, base_char in encoding_data.items() if base_char == char] retu...
7308fde2ecd9a7a76db2159d17eb567af46f26da
skafev/Python_basics
/Third_week/01Excellent_result.py
66
3.625
4
number = float(input()) if number >= 5.5: print("Excellent!")
dea12e5fdb8208c9e6a90d08ffb9a90c9bbcc39f
BrunoAntunes23/treino-dataframe
/treino_dataframe/treino_dataframe/treino_dataframe.py
248
3.609375
4
#manipulação de dados import pandas as pd import sqlite3 #criação do conector conector=sqlite3.connect("conta.db") df=pdread_sql_query("select*from Cadastro",conector) print(df.head()) for nome in df['nome']: print(nome) print(data)
8dad88f29abb5a9b5abf240e1dc175abd2b4a755
tazmike77/PL-app
/Backend/TreeManagement.py
3,664
4.1875
4
''' Tree ''' from treelib import Node, Tree from utils import GetTreeLevel import pickle class TreeNode: ''' "TreeNode" class defines tree node structure. Each class instance (node) is composed the following atributes: - status: status of the subtest ("ok" or "not ok"); - comment: commen...
c781d690e9352d04572147e6dae67eb06ad6ce1f
SaiGulipalli/project3
/printing the letters.py
488
3.921875
4
def mostfrequent(word): l = list(word) d = {} for e in l: if e in d: d[e] += 1 else: d[e] = 1 dl = set(d.values()) for i in range(len(dl)): max_ = max(dl) for k, v in d.items(): if v == max_: ...
2d5d70f7c51bd7359cfb344217d2c01ab1c0c31c
ajerit/python-projects
/sorting/project/arreglos.py
2,176
3.71875
4
#! /usr/bin/python # -*- coding: utf-8 -*- # Autores: # Mathias San Miguel 13-11310 # Adolfo Jeritson 12-10523 import random # Descripcion: Chequea si el arreglo dado esta ordenado # Parametros: A: Un arreglo de elementos numericos # dataset: Tipo de arreglo a crear # Retorna: True si esta ordenado, det...
4e11ee39bc5c48c8c13e54264f21f1d8f69ccff8
wanglinjie/coding
/leetcode/spiralmatrix.py
2,513
4.03125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # date:20160711 class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Gi...
664bc584afcd46975cc69f0bd769a504153f74d4
dnlR/exercism
/python/word-count/word_count.py
249
3.828125
4
import re from string import punctuation from collections import Counter def count_words(sentence): sentence = re.sub("[,_]", " ", sentence) words = [word.strip(punctuation).lower() for word in sentence.split()] return Counter(words)
859077b8f9747d06cd4e23c619ff94509ad70cd1
saurabhxml/testrepo1
/DataTypes.py
408
3.5625
4
# No need to declare any type of variable i=10 print(i) i=i+.1 print(i) i="test" print(i) x=50 y=x print(id(x)) # print identity of x print(id(y)) # print identity of y min_bal=100 print(min_bal) number_of_months=12 print(number_of_months) a=b=c=4 print(a,b,c) a,b,c=10,3,"Saurabh" print(a,b,c) s1="Hello World" pr...
d4adc145b135ce2ab910f47a9cc5e415aea92dd1
berkersonmez/TaleHouse
/Teller/shortcuts/logic_evaluator.py
2,370
3.640625
4
class LogicEvaluator: def __init__(self): pass str_to_token = {'True': True, 'False': False, 'and': lambda left, right: left and right, 'or': lambda left, right: left or right, '(': '(', ')': ')'} ...
58471dd027076810ba47f5c43c4305136d313ba3
leonl42/MLinPractice
/scripts/feature_extraction/feature_ngrams.py
3,315
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 26 17:09:20 2021 @author: leonl42 Computes the ngram distribution and the corresponding feature vectors by looking at the most frequent ngrams and using one hot encoding. """ from scripts.feature_extraction.feature_extractor import FeatureExtrac...
18ce744872c6e67df9ea96d2cab09298ed460fcc
darrencheng0817/AlgorithmLearning
/Python/leetcode/KthLargestElementInAnArray.py
440
3.75
4
''' Created on 1.12.2016 @author: Darren '''''' Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5. Note: You may assume k is always valid, 1 k array ...
a16e3c6dbcb07fc5bdd124fa016dc15121f8e2c0
Aadeshkale/Python-devlopment
/5.Data Structure/2.Tuple/2.indexing.py
231
3.671875
4
t=(121,'aadesh' ,123,'sachin',(124,'kunal')) print(t) print(t[0]) print(t[:]) print(t[2:]) print(t[-1]) print(t[4][1]) # length of tuple print(len(t)) l=len(t) # revrse of tuple print(t) print(t[::-1]) print(t[len(t):0:-1])
8578bf2a6e28a29cc5dabff48798d2e4bffcb2ef
romiof/cc1py
/S06/jogo_nim.py
2,998
3.90625
4
# # Jogo MIN contra o PC. # Escolher entre jogar (1) partida ou (2) campeonato. # Defina Quantidade de Peças (N) e a Quantidade a ser Retirada (M) # Programado para sempre o PC sempre vencer # def main(): fgModoJogo = True modoJogo = 0 while fgModoJogo: print("Bem-vindo ao jogo do NIM! Escolha:\n") ...
3740c09e7e0afde9b6beef2fca047b6e75215796
harshittiwari/LeetCode
/add_two_numbers.py
3,262
3.9375
4
#You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. #Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) #Output: 7 -> 0 -> 8 # Definition for singly-linked list. class ListNo...
b5ed8b7cbf085476c91963fcec63c1c5460778de
blitzmann/euler
/problem17.py
2,139
4.03125
4
""" https://projecteuler.net/problem=17 This one was a pain and not fun at all. There is probably a much more efficient way of doing it, but I didn't care enough. We have three lists: ones-place names, teens-place names, and tens-place names. This solution hardcodes the number of digits to satisfy the problem, but it ...
232a2eb4a927fc61ea680f1aa813338a7c7fedbd
tjnovak58/cti110
/M5LAB1_Novak.py
352
3.578125
4
# CTI-110 # M5LAB1 - Shapes # Timothy Novak # 10/22/17 # Call turtle module. import turtle wn = turtle.Screen() tim = turtle.Turtle() # Draw a square. for count in range(4): tim.right(90) tim.forward(100) # Draw a triangle. for count in range(2): tim.right(-120) tim...
8d59ac7347895230af851ab828fe075ceb0ae01e
ThaisMB/Curso-em-Video-Python-Exercicios
/ex058.py
589
3.546875
4
from random import randint from time import sleep palpite = 0 chute = 11 print('Pensei em um número entre 0 e 10. Você consegue adivinhar?') computador = randint(0,10) while chute!=computador: chute = int(input('Em qual número eu pensei?')) print('\033[33m PROCESSANDO... \033[m') sleep(2) ...
a9d3291351a3c6a44767c0b4f32fa85055303b05
daegu-algo-party-210824/hojin_algo
/book_dongbinna_with_python/chapter11그리디기출/03문자열뒤집기.py
356
3.65625
4
string1 = input() new_string = string1[0] for i in range(len(string1) - 1): if string1[i] != string1[i + 1]: new_string += string1[i + 1] # print(new_string) result = 0 if new_string.count("0") > new_string.count("1"): result = new_string.count("1") else: result = new_string.count("0") print(...
043f67c1d5b3e939894b6693fc42285ab2fe41f4
IhsanE/CSC411
/A2/code/q2_2.py
6,463
3.71875
4
''' Question 2.2 Skeleton Code Here you should implement and evaluate the Conditional Gaussian classifier. ''' import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt D = 64 def compute_mean_mles(train_data, train_labels): ''' Compute the mean esti...
6a03f8d109f1851dd95878c05e07ff23b21d7bab
Yangjiaxi/exp_toolkit_snippet
/plot.py
246
3.765625
4
from matplotlib import pyplot as plt import numpy as np def sigmoid(x): return 1.0 / (1 + np.exp(-x)) if __name__ == "__main__": x = np.linspace(0, 8, 50) + np.abs(np.random.randn((50))) * 0.3 plt.plot(sigmoid(x)) plt.show()
d88b50d921cba4668a2c72bcddd4458dbb9bcd18
woodymax/python-raspberry
/LED_Blink.py
1,037
4.21875
4
import RPi.GPIO as GPIO # Import GPIO library import time # Import library to use 'sleep' # Configure the GPIO to use the physical pin numbering GPIO.setmode(GPIO.BOARD) # Configure the pin 7 to receive the output GPIO.setup(7, GPIO.OUT) # Function to blink the LED def Blink(numberOfTimes, speed): try: for i i...
3b3582045d32238823dcf20455ceb057814e3814
juliotrigo/pycalculator
/tests/test_input_string.py
676
3.71875
4
# -*- coding: utf-8 -*- """Input string tests.""" import unittest from pycalculator.calc import validate_argv class ArgvTestCase(unittest.TestCase): """Testing the argv validation.""" def test_no_argv(self): self.assertRaises(TypeError, validate_argv, None) def test_empty_list(self): ...
b7e0d59b77f2c3e97cb2d53d720b499b5cc268fb
Abhishek-IOT/Data_Structures
/DATA_STRUCTURES/DSA Questions/Strings/Converttonumbermobile.py
656
4.375
4
""" Convert a sentence into its equivalent mobile numeric keypad sequence Difficulty Level : Easy Last Updated : 06 Nov, 2020 Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence. LOgic=Make the dictinory of mobile no and then just check if in dicttionary and print. "...
7745a80f7f2259bd4b11edf7b93129d9176b22bc
SManyet/Con-Chess
/board.py
7,707
3.65625
4
#!/usr/bin/python # board.py: class to hold abstraction of the chess board import piece class Board: def __init__(self, board_array=None, turn=1, white_cap=[], black_cap=[], move_history=[], white_king=None, black_king=None): if board_array: self.board_array = board_array else: ...
e2cf595694872cffbef3b4452254f63888c931b5
chenlifeng283/learning_python
/7-handling conditions/case_insensitive_comparisons.py
300
4.5625
5
country = 'CANADA' # by converting the string entered to lowercase and comparing it to a string # that is all lowercase letters I make the case-insensitive # If someone types CANADA or Canada it will still be match if country.lower() == 'canada': print('hello en') else: print('hello')
5276789300cec1aeecc6e67ba765cfc739d2c5bd
zambrzycki-zbigniew/python-playground
/CourseLab75.py
2,604
3.578125
4
task = ''' Tym razem pomożemy lekarzom przeprowadzając wstępną analizę: czy pacjent ma grypę, czy tylko przeziębienie (zakładamy, że pacjentowi coś dolega, w tym zadaniu mamy tylko pomóc zdiagnozować czy to jest grypa czy przeziębienie): 1. Utwórz 3 zmienne -musclePain - wartość false -fever - wartość true ...
8c9b65c9a97ced6cf85051d08b863a2a8c089694
yannsantos1993/Exercicios-Python
/Modulo_1/Lista UFMG/Exercício 14.py
291
3.828125
4
#14 - Escreva um algoritmo em PORTUGOL que receba quinze números do usuário e imprima a raiz quadrada de cada número. contador = 0 while contador < 15: num = int(input("Informe um número:")) print(f'A raiz quadrada do número informado equivale a: {num**(1/2)}') contador +=1
2757b65ead8b446ba9d24dca60add6f80db876de
danimano/TRP
/pearlib/pearlib/create_image.py
1,379
3.703125
4
from pearlib.get_all_lines import * from pearlib.create_image_from_lines import * def create_image(network, layer_indices, res = None, img = None, plot_output = False): """Generates the image with the boundary lines. -- network: The Network object representing the network -- layer_indices: indicat...
7c6e3a4cd64ca7b2261f6437ad3cdd70113e0c7d
Yanaigaf/NextPy-Coursework
/nextpy3.2.py
914
3.515625
4
""" 3.2.5 - Read file exception handling with try-except-else-finally Added decorator for fun """ import pathlib def content_print(fn): def wrapper(*args, **kwargs): print(f"{'FILE READ START':_^30}") fn(*args, **kwargs) print(f"{'FILE READ END':_^30}\n") return wrapper @content_prin...
c2203fd16a972c80f7e86e9578f094709880f46b
aponte411/algorithms-python
/sorting/count_sort.py
811
3.921875
4
from typing import List def sort_scores(scores: List[int], max_score: int) -> List[int]: result = [] counts = [0 for _ in range(max_score + 1)] for num in scores: counts[num] += 1 # walk backwards and add scores in descending order # forward for ascending count_idx = len(counts) - 1 ...
246ad84b66d03493cbcc1949e58c377038f2adb7
scorbettlw/Python101
/Lesson-002_IntroductionToStrings/string_methods_two_complete.py
5,901
4.625
5
""" Lesson 002 - Pt7: String Methods II Python's ability to manipulate strings is one of the language's greatest strengths. The index() and len() methods, when combined with Python's slice syntax, makes extracting and/or manipulating string methods relatively painless. However, there are a number ...
a1b8fcf858e8d0027132da717f09ebd498ba22fd
danny135/MIT-6.00.1x
/hilo.py
644
4.15625
4
# Paste your code into this box done = False print "Please think of a number between 0 and 100!" lowest = 0 highest = 100 guess = 50 while not done: print "Is your secret number " + str(guess) + "?" input = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' t...
0b9382361fb6bc36b40cd48269c0ad4070dbd974
stavidi/python_step_by_step
/chapter_seq/examples/sort_wh.py
1,167
3.5
4
a = [(166, 55.2), (157, 55.2), (170, 55.2), (175, 90), (166, 73), (180, 73)] print(a) b = sorted(a) print(b) # [(157, 55.2), (166, 55.2), (166, 73), (170, 55.2), (175, 90), (180, 73)] def weight(t): h = t[0] w = t[1] return w # или return t[1] b = sorted(a, key=weight) print(b) # [(166, 55.2), (...
874e4fe0d9610789e45fdd2c79ed22b35f13cbaa
FabianForsman/Chalmers
/TDA548/Exercises/week5/src/samples/useaclass/TestComplex.py
1,082
3.75
4
# package samples.useaclass from Complex import Complex # This is for tests of the Complex class def test_complex(): # Create objects of type Complex c1 = Complex(1, 2) # Instantiate, use constructor on right side c2 = Complex(-3, -5) c3 = Complex(c2) # Use constructor to create a copy ...
b74f6deb7a82cb8131f02811618b378e5671f886
YeFeiyangx/grownup_share
/orLearning/assignSchHospital.py
6,985
3.546875
4
#%% """ 每个班次来,任意一个护士都可以做 """ from ortools.sat.python import cp_model class NursesPartialSolutionPrinter(cp_model.CpSolverSolutionCallback): """Print intermediate solutions.""" def __init__(self, shifts, num_nurses, num_days, num_shifts, sols): cp_model.CpSolverSolutionCallback.__init__(self) s...
d4e28bee3eea26a9a42518340e1dc79b51a6bfd7
OleksandrLozinskyy/Hillel_Python_Lessons
/Lesson15/students_journal.py
4,221
3.84375
4
class Student: grades = [] def __init__(self, firstname, lastname, age, sex): """ Инициализирует экземпляр класса передаваемыми значениями :param firstname: Имя :param lastname: Фамилия :param age: Возраст :param sex: Пол """ # При инициализации з...
2d864783fcf511208454d2f9d325a02386549af1
liyan2013/hogwarts
/python01/game.py
691
3.515625
4
import random def game(): # 我的血量 my_hp = 1000 # 敌人的血量 enemy_hp = 1000 while True: # 我受到随机的攻击,减少血量 my_hp = my_hp - random.randint(0, 50) # 敌人收到随机的攻击,减少血量 enemy_hp = enemy_hp - random.randint(0, 50) if my_hp <= 0: # 如果我此时的血量<=0,则敌人赢了 ...
0548c44c5f954cb930b44ddb5c1b9bbe798ae987
sam16222/CSC510_43
/tests/test_num.py
282
3.515625
4
from main import the from num import Num def test_num(): '''Test case for div function''' num = Num() the['nums'] = 512 for i in range(1, 101): num.add(i) std = num.div() median = num.mid() return 0 if 30 < std < 32 and 50 <= median <= 52 else 1
f305a228ae03a506896fbb5901187b7c2d6ef892
DanayaDarling/cs114
/distance_converter3.py
591
4.125
4
convert_equations = input('What are you converting? (miles to kilometers, etc.) ') miles = int(input('How many?') def convert_number(convert_equations): if convert_equations == 'miles to kilometers': converted_number = miles * 1.60934 elif convert_equations == 'miles to feet': converted_numbe...
d7816cabdce6252122bb46a36153a58158ba6d5a
byunwonju/2020_programming
/0606/func07.py
171
3.75
4
def avg(a,b,c): s=(a+b+c)/3 return s in1= int(input("값1:")) in2= int(input("값2:")) in3= int(input("값3:")) r=avg(in1, in2, in3) print("평균 =",r)
609986fb73498c40df0dcd49ddfd9acf2ddf7ce3
ChrisM-csuf/lab2
/direction_traffic.py
327
4.375
4
""" get the street number if the street number is even display eastbound if odd, display westbound finish """ def calculate_street(street): print("divide: ", street / 2) print("Modulus: ", street % 2 == 0) if (street % 2) == 0: print("Eastbound") else: print("westbound") calculate_stre...
03a53e6fb161682792ca862878b2aad791625735
DariaKnyazeva/project_euler
/problems/p032.py
998
4.0625
4
# PANDIGITAL PRODUCTS """ We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 thr...