blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
17cad3fa4c94d394cfed3c649083e9f0b31e611a
Andrej300/week3_day3_homework
/modules/calculator.py
395
3.703125
4
def add_numbers(number1, number2): return f"The answer is {int(number1) + int(number2)}" def subtract_numbers(number1, number2): return f"The answer is {int(number1) - int(number2)}" def multiply_numbers(number1, number2): return f"The answer is {int(number1) * int(number2)}" def divide_numbers(number1, ...
6eeedfde352ff2cef3441f539386b79fe4fc5e84
krishnanunni-pr/Pyrhon-Django
/OBJECT_ORIENTED_PROGRAMMING/Inheritance.py
595
3.703125
4
# Inheritance # single inheritance class Person(): # Parent class/base class/super class def pdetails(self,name,age,adrs): self.name=name self.age=age self.adrs=adrs print(self.name,self.age,self.adrs) class Student(Person): #child class/derived class/sub class def sdetails(sel...
96903b4999dde5db81ca563258572d369f983e01
yzjbryant/YZJ_MIX_Code
/Python_Code_Beginner/05_高级数据类型/hm_17_字符串的查找与替换.py
664
4.59375
5
hello_str = "hello world" #1.判断是否以指定字符串开始 print(hello_str.startswith("Hello")) #2.判断是否以指定字符串结束 print(hello_str.endswith("world")) #3.查找指定字符串 #index同样可以查找指定的字符串在大字符串中的索引 print(hello_str.find("llo")) #index如果指定的字符串不存在,会报错! #find如果指定的字符串不存在,会返回-1 print(hello_str.find("world")) #4.替换字符串 #replace方法...
09cbbca4201cfec9483e8906dbda3c9d8fc753c7
TreySchneider95/python_practice
/practice.py
13,253
4.15625
4
import string import random from pprint import pprint import itertools # print('h' in 'hello') # Exercise: # Generate a random Password which meets the following conditions # Password length must be 10 characters long. # It must contain at least 2 upper case letters, 1 digit, and 1 special symbol. def generate_ra...
3551bd1b336382f44ccaf765f8df3df59eb0e9d3
ivaMm/beginnerPythonPractice
/15_reverse_word_order.py
123
4.0625
4
def reverse_it(sentence): return ' '.join(sentence.split(' ')[::-1]) print(reverse_it('Hello there, it is Python!'))
cc1985ad1b7b5d95495b632d874385e5d9d6cdbb
fabionunesdeparis/Fundamentos-em-python3
/exer63.py
425
3.703125
4
# @ Fábio C Nunes - 18.05.20 print('*.' * 40) print('{:^80}'.format('------- Sequência de Fibonacci -------')) print('*.' * 40) qd_sequencia = int(input('\nQuantos elementos da sequência deseja visualizar? ')) -1 ant = 1 num = 0 result = 0 print(num, '',end='→ ') while qd_sequencia > 0: result = num + ant print...
4609c95eb93939268ad99e8b49f20a7d9730a9e1
wy/ProjectEuler
/solutions/problem29.py
329
3.65625
4
# coding: utf8 # Author: Wing Yung Chan (~wy) # Date: 2017 # Distinct Powers # Find the size of the set S # For all a^b fo 2<=a<=100 and 2<=b<=100 # S = {s = a^b | a,b in 2..100} def problem29(): powers = set() for a in range(2,101): for b in range(2,101): powers.add(pow(a,b)) re...
2638a8e0ae69e325ea5c619ff2cb68cb70781454
upendraBthapa/workshops
/CP5632_assignment1.py
4,592
3.71875
4
__author__ = 'jc449735' # Initialize the constants,which can be used in the below functions as it is UNIVERSALLY defined FILE = "books.csv" MENU = "Menu: \nR - List required books\nC - List completed books\nA - Add new book\nM - Mark a book as completed\nQ - Quit" def main(): print("Reading List 1.0 - ...
653fde6f253a8322839fad70927465c26878d178
MatrixAgent/AI
/Lesson1/task3.py
82
3.546875
4
# Задание 3 n = input('Figure: ') print(int(n) + int(n * 2) + int(n * 3))
eb8631290ea40b7ac15e70abdf19c6b9424e4621
Aasthaengg/IBMdataset
/Python_codes/p03286/s811751460.py
252
3.640625
4
def resolve(): n = int(input()) if n == 0: print("0") return out = "" base = 1 while n != 0: if n % (-2) == 0: out = "0" + out else: r = n % (-2) if r < 0: r = 1 n -= r out = "1" + out n /= (-2) print(out) resolve()
a42b9f46df26cdbb91b2625ee4ab6b44b55d9d89
IshpreetKGulati/100DaysOfCode
/day7.py
1,259
4.3125
4
""" Monotonic Array Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic. An array is said to be monotonic if its elements, from left to right, are entirely non-increasing or entirely non -decreasing. Sample Input: array = [-1, -5, -10, -1100, -1100, -11...
12f1f980d7ed2f4bf8333064405ae38fca31ff5d
blackplusy/weekend0303
/例子-0310-02.列表操作.py
454
3.796875
4
#coding=utf-8 l=[1,2,3,4] l2=[1,'kobe',2,'rose'] l3=[1,2,[3,4]] l=[1,2,3,4,5] print(l) for i in l: print(i) if 1 in l: print('1 is here!') l=['james','rose','kobe','no.3'] print(l[0]) print(l[-3]) #print(l[6]) print(l[1:]) print(l[:-1]) print(l[2:3]) l1=[1,2,3] l2=['heygor','ladeng'] print(l1+l2) print('*******')...
f09eef6248843ec511032d541e67eb04159f99dd
LeBron-Jian/BasicAlgorithmPractice
/SortAlgorithm/exercise3.py
1,573
3.75
4
# _*_coding:utf-8_*_ ''' 3,给定一个列表和一个整数,设计算法找到两个数的下标, 使得两个数之和为给定的整数。保证肯定仅有一个结果。 例如,列表[1,2,5,4] 与目标整数3,1+2=3,结果为(0,1) ''' def TwoSum(nums, target): ''' :param nums: nums是代表一个list :param target: target是一个数 :return: 结果返回的时两个数的下标 ''' for i in range(len(nums)): for j in range(i + 1, len(n...
82b67bc2c1553e1eb4e04910f59f6aef9162cbc6
nealkuperman/Python
/_projects/try/pandasqlMakePythonSpeak-0.py
1,244
3.703125
4
#Checking out meat and birth data from pandasql import sqldf from pandasql import load_meat, load_births def test_basic_import(): meat = load_meat() births = load_births() print (meat.head()) print (births.head()) # Let's make a graph to visualize the data # Bet you haven't had a title quite like this...
3102151155283494ed0f39132515014ad256bd3d
silvafj/BBK-MSCCS-2017-19
/POP1/worksheets/object-oriented-programming/courses.py
2,117
3.90625
4
from datetime import date class BirkbeckCourse: """This class represents a course at Birkbeck.""" def __init__(self, department, code, title, instructors=None): self.department = department self.code = code self.title = title self.students = dict() self.instructors = li...
677aa9c995019a7bfcb8588d884932622d05ab45
kkolamala/atm-project
/learnClass.py
1,632
4.46875
4
#Python allows creating properties of an object outside the class class Player: """initializer is a special method because it does not have a return type The first parameter of __init__ is self, which is a way to refer to the object being initialized Initializing the values of properties inside the class ...
2db0cc139a777d2bf008b329a457b2f3e9b1d087
AkashDevkule/pythonA2Z
/9.Web Scraping and DB/sqlite3_in_python.py
831
4.0625
4
import sqlite3 conn=sqlite3.connect('example1.db') c=conn.cursor() '''Insert query''' # c.execute("""CREATE TABLE IF NOT EXISTS EMP(ID INT PRIMARY KEY,NAME TEXT,SALARY REAL)""") # c.execute('INSERT INTO EMP(ID,NAME,SALARY) VALUES(101,"AKASH",1000)') # c.execute('INSERT INTO EMP(ID,NAME,SALARY) VALUES(102,"SHUBH",5000)...
e838ec30bddbeb7ce5eece4dca43d06bfae2700e
nimunkarkiran/Speetra
/palindrome.py
313
3.9375
4
def palindrome(str1): if len(str1) == 0 or len(str1) == 1: return True if str1[0] == str1[len(str1)-1]: return palindrome(str1[1:len(str1)-1]) return False print('dad', palindrome('dad')) print('abcdcba', palindrome('abcdcba')) print('pythonfor', palindrome('pythonfor'))
6db4b3a82ea6915f4a45a81c428b6bfccad89119
NeoGlanding/python-masterclass
/02-program-flow/else-in-loop.py
236
3.9375
4
numbers = [1,2,4,7,34,533] for number in numbers: if number % 5 == 0: print('This is unnacceptable numbers') break else: #jika di for loop tidak ada kondisi yang terpenuhi print('Good, all numbers are accepted')
e3b77066932bd93836c0645e0fb63673436fdb44
y33-j3T/FEEG1001-Python-for-Computational-Science-and-Engineering
/L03/L3Q6.py
287
4.0625
4
def count(element, seq): ''' Given parameters element and seq, counts how often the given element, element occurs in the given sequence, seq and returns this integer value ''' return seq.count(element) print(count('a', ['a', 'b', 'c', 'a']))
87ca31a5448af418ba6d7bf1cc82f3b56df2cf38
rojasreinold/Project-Euler
/p010-p019/p010/p10-attempt3.py
747
3.953125
4
import math def isPrime(num, array = [], *args): for i in range(0,len(array), +1): #print "%d" % array[i] if num % array[i] == 0: #print "divis by %d" % array[i] return False if math.sqrt(num) < array[i]: return True return True listPrimes =[2] current...
611c446661d415e9eae81701289a49a9d1b67814
tonggh220/md_5_nsd_notes
/nsd2007/py01/day02/game.py
797
3.8125
4
import random # 列出所有可用选择 all_choice = ['石头', '剪刀', '布'] # 计算机出拳 computer = random.choice(all_choice) # 人出拳 player = input('请选择(石头/剪刀/布): ') # 输出人机选择 print('player: %s, computer: %s' % (player, computer)) # 判断胜负 if player == '石头': if computer == '石头': print('平局') elif computer == '剪刀': print('Yo...
253f219593882055c312b0a531f51f84a47e5ac4
lnicholsonmesm/python-challenge
/PyPoll/main.py
3,208
4.28125
4
''' - You will be give a set of poll data called election_data.csv. The dataset is composed of three columns: Voter ID, County, and Candidate. Your task is to create a Python script that analyzes the votes and calculates each of the following: -The total number of votes cast -A complete list of candidates who received ...
5269083b87a62eb42db8b89798d6422e9ad98017
surajsomani/Basic_Python
/Python Basics/17_Module_Import_Python.py
624
3.828125
4
#import statistics #example_list = [5,2,5,6,1,2,6,7,2,6,3,5,5] #print(statistics.mean(example_list)) import statistics as s example_list = [5,2,5,6,1,2,6,7,2,6,3,5,5] print(s.mean(example_list)) from statistics import mean # so here, we've imported the mean function only. print(mean(example_list)) # and again we can ...
81e6642fc64ed80f461054770b1d28495d9b5e40
YeswanthSubhash/pymongo_dataload
/mongodb_id_allocated_automatically.py
971
3.515625
4
from pymongo import MongoClient def insert_records(client): # Access database mydatabase = client["sampledb"] # Access collection of the database mycollection = mydatabase["carsTable"] # dictionary to be added in the database mylist = [ {"Manufacturer": "Honda", "Model": "City", "Colo...
6c0900319e872a07f2703ef3935fada5194c2067
gaetaj/Test-Driven-Development-Example
/check_pwd.py
982
4
4
''' Author- Jacob Gaeta Test Driven Development Example Program that checks for valid passwords length between 8 and 20, one lowercase letter, one uppercase letter, one digit, one symbol. Returns true if requirements met, false otherwise ''' def check_pwd(pwd): if len(pwd) < 8: return False if len(...
455f981bfeca72458ca397b44a7a0858b71f3f87
edu-athensoft/ceit4101python_student
/ceit_190910_zhuhaotian/py1206/lambda_5_highorder.py
161
3.59375
4
def my_func(f, n): return f(n) f0 = lambda x: x*2 f1 = lambda x: x*3 f2 = lambda x: x*4 print(my_func(f0, 5)) print(my_func(f1, 5)) print(my_func(f2, 5))
78018c0b4ab40290bfbc391b78e67bacb8a8651c
joo7998/Python_NumberGenerator
/RandomPasswordGenerator.py
823
3.765625
4
# 8 characters # 2 upper, 2 lower, 2 numbers, 2 special letters import random # list = [1, 2, 5] # random.shuffle(list) # print(list) def shuffle(string): tempList = list(string) random.shuffle(tempList) return ''.join(tempList) # print(random.randint(3, 9)) # chr : returns a str representi...
101edd602ccc99272ee204ece48f2d99e741f2b5
tariq87/amazonproblem
/fib.py
276
3.78125
4
#Fibonacci Series def fibnac(s): n = len(s) fib = [0]*(n+1) fib[1] = 1 sm = fib[0]+fib[1] for i in range(2,n+1): fib[i] = fib[i-1]+fib[i-2] sm += fib[i] fin = list(zip(s,map(str,fib[1:]))) return str(sm)+"".join(sum(fin,())) print(fibnac("beautiful"))
95422374178f2fa848ff0d029ec34e6366e8a0e0
julian55/easteastpole
/hippocampus/data/str_method.py
1,415
3.625
4
from string import * #1 striping # strip() lstrip() rstrip() str_2b = "::2017-02-12::" print('origin string : ' + str_2b) print(str_2b.strip('-')) print(str_2b.lstrip(':')) print(str_2b.rstrip(':')) ''' output 1 origin string : ::2017-02-12:: ::2017-02-12:: 2017-02-12:: ::2017-02-12 ''' print('\t') #2. min() max() ...
7cbad5f30a84f3470084838d312bdf9006020b55
WaterWan/UdacityPA1
/Task2.py
1,494
3.6875
4
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信息: "...
f3950b2a4378a34327aabaed687eb15549cd1574
PanBartosz/semexp
/04_PsychoPy/self_paced_counting/self_paced_counting.py
2,921
3.59375
4
# Poniższy kod ilustruje jak wykonać proste zadanie typu "self-paced counting". # Zadanie to polega na tym, że badany naciskając klawisz odkrywa 2 lub 3 zamaskowane okręgi (dwa możliwe kolory). from psychopy import visual, core, event, data from random import randint window = visual.Window(fullscr=True, ...
35c7f2770ca82e7375435009cdea6ef94879bde9
arifkhan1990/Competitive-Programming
/Basic Programming/Dimik oj/Python3/প্রোগ্রামিং সমস্যা 29 - [৫২ সমস্যা বই] চিহ্ন পরিচয়.py
787
3.984375
4
# Name : Arif Khan # Judge: Dimik Oj # University: Primeasia University # problem: প্রোগ্রামিং সমস্যা 29 - [৫২ সমস্যা বই] চিহ্ন পরিচয় # Difficulty: Easy # Time Complexity: 0.3788 সেকেন্ড # ...
a15388d2c4bf73626fd295f2806a3fdfcb4d4288
zwalsh/fantasy-baseball
/tasks/task.py
1,574
3.515625
4
import logging.config from config import logging_config, notifier_config class Task: def __init__(self, username): self.username = username @staticmethod def create(username): """ Creates a Task, initializing whatever dependencies may be necessary. Each subclass must impl...
0d1a25860ef84ba20a192c2eadc698bbe4180e39
brenuvida/cursoemvideo
/Aula04/exercicio_11.py
155
3.796875
4
m = float(input('Digite um valor em metros: ')) print('O valor {} pode ser convertido como {} centimetros ou {} milímetos'.format(m, (m*100), (m*1000)))
f53e3d04b180ef7a9c362f00f5b1c8172fcacb38
bazhenov23/GB_Home-Work
/Lesson3/Task 3.2.py
619
3.921875
4
def info(): name = input("Введите имя ") surname = input("Введите фамилию ") year = int(input("Введите год рождения ")) city = input("Введите город ") email = input("Введите адрес электронной почты ") telephone = input("Введите номер телефона ") info_user = ( f"Пользователь {name} {s...
3912e216922a83f5f76f79e8c1b66df7ff90b330
pinguinato/corso-python
/esercizi/quantita_di_moto.py
390
3.78125
4
""" Author: Gianotto Roberto Quantità di moto = massa X velocità """ massa = float(input('Inserisci il tuo peso in kg: ')) velocita = float(input('Inserisci la velocità in m/s: ')) quantitaDiMoto = massa * velocita print("La quantità di moto è pari a: " + str(quantitaDiMoto)) energiaCinetica = (0.5) * massa * (vel...
f32be759b4cf165dae9c252a551ba85bb1b51903
gochicken-jp/sensormotion
/sensormotion/peak.py
7,614
3.703125
4
""" Peak detection algorithms. This modules contains functions for detecting peaks and valleys in signals. Signals can also be detrended by estimating a baseline prior to peak detection. Based on work by `Lucas Hermann Negri <https://pypi.python.org/pypi/PeakUtils>`_. """ from __future__ import print_function, divis...
1ddc49b86c038acab56a90c2c690bd23b7c6ec1b
phamhieu04/ss10-real
/ss10/diccreate.py
207
3.59375
4
movie={ 'name' : 'end game', 'discription' : 'part 2 of infinity', } movie['cost']='more than 3 million dollars' print(movie) ask=input("available on ") movie['available on']=ask print(movie)
987e11cc81b76c0a890ab84a164fb40e20be3143
RamonCris222/Ramon-Cristian
/questao_19_repeticao.py
108
4.0625
4
x = int(input("X = ")) while x != 0: if x == 0: pass else: print(x * 3) x = int(input("X = "))
d7e771fb90b6df8e17d993302801ce79e831bb7f
gwy15/leetcode
/src/654.最大二叉树.py
886
3.640625
4
# # @lc app=leetcode.cn id=654 lang=python3 # # [654] 最大二叉树 # class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.le...
e02cdc4a3d4b8f59cc1afc44676d99426b8eb38c
johannagwan/nus-botfessions
/web-scrape/confessions-codes/nuswhispers_popular.py
1,363
3.53125
4
from selenium.webdriver import Chrome import pandas as pd import time webdriver = "D:\Hanna programme downloads\chromedriver_win32\chromedriver.exe" driver = Chrome(webdriver) def scroll(driver, timeout): scroll_pause_time = timeout i = 0 # Get scroll height last_height = driver.execute_script("retur...
b7fb2d0a3ba27c05246f136a5c189f91b9ad77b9
Sudhanshu277/python
/listpractice.py
349
3.5625
4
a = input("Enter hobbie:") b = input("Enter 2nd hobbies:") c = input("Enter 3rd hobbies:") d = input("Enter 4th hobbies:") e = input("Enter 5th hobbies:") f = input("Enter 6 hobbies:") g = input("Enter 7 hobbies:") h = input("Enter 8 hobbies:") i = input("Enter 9 hobbies:") j = input("Enter 10 hobbies:") list = [a,b,...
39f4e9233f649d8a4ed766adbddfb805e7c7f214
ChrisKou/Algorithms
/ShapeDrawingSimple.py
276
3.921875
4
prompt = "Please enter a number: " numbers = [int(input(prompt)), int(input(prompt)), int(input(prompt)), int(input(prompt)), int(input(prompt))] for x_count in numbers: output = '' for x in range(x_count): output += 'x' print(output)
4b9ac12675c3cb151dcebbd520ff21fac05f6daa
LakeSuburbia/CS50-Intro
/pset6/credit/credit.py
1,199
3.578125
4
import math from math import log10 from cs50 import get_int creditcard = get_int("kaartnummer: ") mem = creditcard checksum = int(0) length = math.floor(log10(creditcard))+1 firstdigits = int(0) digit =int(0) for i in range(length): digit = int(mem % 10) mem = int(mem / 10) if (i % 2 == 1): digit ...
e55c537501520464baff9b4cd263b883146ee5e6
lindongyuan/study2020
/project/Chapter_09/c9-14_try.py
260
3.609375
4
from random import randint class Die(): def __init__(self): self.sides = 6 def roll_die(self): print("\n这个是6面的骰子:") for x in range(10): x = randint(1,6) print(x) die = Die.roll_die()
45a3e5a70cfaff2cd05bf449b72aad067deaaf24
Svegge/GB_2021_06_py_foundations
/02_homeworks/01/task_06.py
1,564
3.84375
4
''' 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. Программа должна принимать значения п...
0a8ee1841f9614dc7f81eb6c76bfbbb7a3a387e8
linchuyuan/leetcode
/grayCode.py
201
3.65625
4
#generate n gray code. e.g. n = 2 -> return [0,1,3,2] def grayCode(n): rst = [0] position = 0; for i in range(n): for k in range(len(rst)): rst.append(~k); return rst; print grayCode(3);
d64cdbd65fc4ac2af220c7319983d54276ee7fa6
LuccaSantos/curso-em-video-python3
/Desafios/modulo02/def58.py
545
3.78125
4
''' Melhore o jogo do desafio 28 onde o computador vai 'pensar' em um numero de 0 a 10 onde o jogador vai chutando valores e quando acertar mostre a quantidade de chutes ''' from math import e import random print('= ' * 6 + '' + ' =' * 6) numero_chutes = 0 tentativa = True numero = random.randrange(0, 11) wh...
c0e33b3628283a0623e3582fff79da53cf405945
Abhi1o/python_learning-
/3day/3_nested_if_else.py
308
4
4
print("welcome to rollercoaster!") height=int(input("what is your height in cm ")) age=int (input("what is you age ")) #condition check if height != 120: print("enjoy your ride") if age<=18: print("pay $7") else: print("pay $12") else: print("sorry,you can't ride")
a89eaa0af8f55a024b4bbc0cdc3a55d1931d621d
sheamus-hei/whiteboarding
/search-and-sort/search_rotated_array.py
1,325
3.890625
4
# An sorted array of integers was rotated an unknown number of times. # Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null. # For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in...
cd5c70d34004a2b71a6101f48498890c1af6c8ca
castrodeko11/Python
/Python Exercícios/EX 028.py
853
4.03125
4
#28 Algoritmo que faça computador pensar em um número inteiro de (0,5) import random import time list = [0,1,2,3,4,5] s = random.choice(list) n = int (input("Digite um número ")) if (s == n): { print("Número Sorteado: {} \nVocê Acertou".format(s)) } else: print("Número Sorteado: {} \nVocê Errou"....
7f2994c0ab4f305c6e2a6df047938d5213ce3b99
mextier/PythonULess
/CS_GAME.py
2,974
3.515625
4
import random class Game: def __init__(self): self.Players = list() self.CTPlayers = list() self.TPlayers = list() self.SpecPlayers = list() def JoinPlayer(self,player,team): self.Players.append(player) if team==0: self.SpecPlayers.append(p...
84c98fcf7ae89f3b68d6e064725931dba6cabaa0
liamthanrahan/lunchtime-python
/2017/session-1/problem4.py
489
4.34375
4
# Ask the user to input a string. Return this string, with every character (char) repeated twice. # e.g. ‘python’ should become ‘ppyytthhoonn’ # Use input() to test your program, but make sure you remove print statements and the input function when you submit def double_char(word): word_with_repeated_chars = "" ...
86a5a331608230cde74443fba1543848bb1375fe
HugoPorto/PythonCodes
/prime.py
257
3.65625
4
def prime(n): lista = [] for j in n: if j > 1: for i in xrange(2, j): if j % i == 0: break else: lista.append(j) return lista print(prime([2, 3, 5, 8, 13 ]))
c46344a946074bdb0f241757160caa5291655c26
dakenan1/LeetCode-Offer
/Array/Quick_array2.py
461
3.640625
4
# -*- coding:utf-8 -*- def Quick_array2(array): if len(array) >= 2: #空集以及完全分开之后 l = [] r = [] key = array[0] array.pop(0) for i in range(len(array)): if array[i] <= key: #顺序排列 l.append(array[i]) else: r.ap...
ad34bb8412ca1a3b8ac8d37824502cd93751f058
sunsiz/puzzles
/misc/cipher.py
1,670
4.59375
5
""" Julius Caesar protected his confidential information by encrypting it in a cipher. Caesar's cipher rotated every letter in a string by a fixed number, making it unreadable by his enemies. Given a string, and a number, encrypt and print the resulting string. Note: The cipher only encrypts letters; symbols, s...
46bc9ad276315715c4777edbf99f92e0a2498909
ishantk/GW2019PDec
/Session6A.py
375
4.1875
4
# Operators # Relational # >, <, >=, <=, ==, !=, is, not a = 10 b = 20 c = 10 print(">> Is a and b equal? ", (a == b)) print(">> Is a less than b? ", (a < b)) print(">> Is a equal to c ", (a is c)) print(">> Is a not same as b ", (a is not b)) # Explore : What is difference between is and == # Relational operators a...
bd95fe17c5375585f1e490984ee8f4e80250cd8e
yyl2016000/somePy
/leetcode_070.py
280
3.5625
4
class Solution: def climbStairs(self, n: int) -> int: dp = {0:1,1:1} for i in range(2,n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] def main(): n = int(input()) print(Solution().climbStairs(n)) if __name__ == '__main__': main()
c08430b27c9d102afda6aa4e09f43aca2438a844
frigid-sll/python
/python实习代码/_2Two month/第七单元 线程/共享全局变量.py
2,907
4.15625
4
#多线程-共享全局变量 #多线程之间共享全局变量有两种方式: #子线程函数使用global关键字来调用函数外全局变量 #列表当作实参传递到线程中 #在一个进程内所有的线程共享全局变量,很方便在多个线程间共享数据 #缺点就是,线程是对全局变量随意遂改可能造成多线程之间对全局变量的混乱(即线程非安全) # 共享全局变量-global全局变量 #例如: # from threading import Thread # from time import sleep # num=100 # def work1(): # global num # for i in range(3): # num+=1 ...
30c5afe7d8392820ec40905b67cf1b905446968a
KETULPADARIYA/Sql
/sqlLiteCoreySchafer/sqlLite_demo.py
1,311
4.25
4
import sqlite3 from employee import Employee conn = sqlite3.connect("employee.db") c = conn.cursor() def insert_employee_in_employee_db(employee:Employee,conn=conn): with conn: c.execute("""insert into employees values (:first ,:last,:pay) ;""", {'first':employee.first, ...
c6c1dff1aefdf97225b0f057d49252d135db2d52
FB-18-19-PreAP-CS/wordplay-AndresF2201147
/odometer.py
549
3.53125
4
def palindromic(): for i in range(1000000): str_i = str(i).zfill(6) if str_i[2:] == str_i[5:1:-1]: i += 1 str_i = str(i).zfill(6) if str_i[1:] == str_i[5:0:-1]: i += 1 str_i = str(i).zfill(6) if str_i[1:5] == str_i[5...
356f399a67b9b8f6384a5e140ba53f034fbe1a11
light-weaver/desdeo-emo
/desdeo_emo/population/CreateIndividuals.py
4,553
3.671875
4
import numpy as np import random from math import ceil from pyDOE import lhs def create_new_individuals(design, problem, pop_size=None): """Create new individuals to the population. The individuals can be created randomly, by LHS design, or can be passed by the user. Design does not apply in case of...
957d2136760f49b124e78104a177d9de0e74dfff
theolamide/Computer-Architecture
/ls8/cpu.py
4,146
3.65625
4
"""CPU functionality.""" import sys class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.ram = [0] * 256 self.register = [0]*8 self.flag = [0]*8 self.running = True self.pc = 0 self.CALL = 0b01010000 self.LDI = 0...
8ece2c949d8b618ce11455aa16ff233abdd16be3
Edwardeddie10/Python-Challenge
/Pybank/main.py
2,389
3.921875
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv csvpath = os.path.join('..', 'Resources', 'budget_data.csv') with open(csvpath, newline="")as csvfile csvreader = csv.reader(csvfile, delimiter=",") print cs...
78f3d41081a1574739c5f8c573ebd9b26847a284
spencertse122/Learning-Miscellaneous
/ClassMethod_StaticMethod.py
1,434
4.6875
5
# Python program to demonstrate # use of class method and static method. from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a Person object by birth year. @classmethod def fromBirthYear(cls, nam...
33e755828d4e26c1a8f8180d88a6259d5264ad98
kishanSindhi/python-mini-projects
/minipro5.py
1,131
4.1875
4
# Author - Kishan Sindhi # date - 30-5-2021 # discription - HEre in this mini project i have created a contact list with the help of dictonary # in project you can add, delete, search and you can view whole contact list from time import sleep contact = {"kishan": "123456", "akshay": "1234", "shivam": "1234567"...
1ec006ddbf3829abc196384875b4f173319f2592
enecatalina/Python
/Python_Fundamentals/Stars.py
337
3.625
4
my_list = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"] # def draw_stars(list): # for num in my_list: # print "*" * num # draw_stars(my_list) def draw_stars(list): for x in list: if isinstance(x,int): print "*" * x elif isinstance(x,str): print x[0].lower() * ...
797fc449f6fa88e3daa383b163575159f3247fa3
AbhiGowdaIndia/Mechine-Learning
/Linear Regression/LinearRegression-Example-1.py
1,226
3.859375
4
#import packages import numpy as np import pandas as pd import matplotlib.pyplot as plt #Read Dataset ds=pd.read_csv("salary.csv") #split data into x and Y axis x=ds.iloc[:,:-1].values y=ds.iloc[:,1].values #Devide the dataset into training and test dataset from sklearn.model_selection import train_test...
1e07e1e0b144ac38a92509645cdd6647837188bb
cmbernardi/python_coursera
/nim.py
2,215
3.984375
4
def computador_escolhe_jogada(n, m): if m >= n: return n else: restantes = n % (m + 1) if restantes > 0: return restantes else: return m def usuario_escolhe_jogada(n, m): jogada = int(input("\nQuantas peças você vai tirar? ")) while jogada > m or jogada > n or jogada < 1: print("\nOops! Jogada in...
4aa3fb4e67452c4cbe8845ab8ddf486f1ee13594
lpham4/PythonPractice
/Bestdeal.py
620
3.828125
4
# Class: 1321L # Section: 02 # Term: Fall 2018 # Instructor: Professor Malcolm # Name: Ly Pham # Lab: Python small_weight = int(input('Small box weight: ')) small_price = int(input('Small box price: ')) large_weight = int(input('Large box weight: ')) large_price = int(input('Large box price: ')) small_total = (small_p...
24f73c43a038286fed6f78f920cdc1e7e6e83fdb
robinklaassen/advent-of-code-2019
/day18/part1.py
825
3.625
4
from itertools import permutations from math import factorial from day18.parse import parse_input from day18.util import get_entrance_node, get_keys_blocked_by_door def main(): graph = parse_input('puzzle_input.txt') keys = [key for node, key in graph.nodes(data='key') if key is not None] doors = [door f...
d9d0f9a6afc3f51ac63483086007a0704702c507
maria-kravtsova/learning-python
/automateBoringStuff/dateTime.py
171
3.578125
4
import datetime countTo = datetime.datetime(2017, 12, 17, 00, 00, 00) graduationIn = countTo - datetime.datetime.now() print('Days till graduation: ' + str(graduationIn))
d2087fd3772d1ffefdbd34fd84d48b56d282f6d3
geekcomputers/Python
/gcd.py
357
4.125
4
""" although there is function to find gcd in python but this is the code which takes two inputs and prints gcd of the two. """ a = int(input("Enter number 1 (a): ")) b = int(input("Enter number 2 (b): ")) i = 1 while i <= a and i <= b: if a % i == 0 and b % i == 0: gcd = i i = i + 1 print("\nGCD of {...
c02113fd42c41a206effe1f09719fab11bd418f8
ReezanVisram/Project-Euler
/Problem-1-Multiples-of-3-and-5.py
239
4.03125
4
# Project Euler Problem #1 # Find the sum of all the multiples of 3 or 5 below 1000 total = 0 # Store the current total of all multiples for i in range(1000): if (i % 3 == 0) or (i % 5 == 0): total += i print(total)
7c76b7cf2368a34ce3dbc9fced52ee629d99d7cb
ChenHaiyuan/PythonPractice100
/NO.14.PY
607
3.703125
4
''' 题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 ''' def reduceNum(n): print('{} = '.format(n)), if not isinstance(n,int) or n <= 0: print('Please input a correct number!') exit(0) elif n in [1]: print('{}'.format(n)) while n not in [1]: for index in range(2,int(n+1)): ...
cd7a73ffe2a4341efc19ed1d4d17d4924b655d6c
Xovesh/python-exercises
/strings exercises/isSubStringRecursive.py
316
3.890625
4
def issubstring(word, sub): if word == "": return True elif word != "" and sub == "": return False else: return (word[-1] == sub[-1] and word[:-1] == sub[-(len(word[:-1])+1):-1]) or issubstring(word, sub[:-1]) a = "abba" b = "abbbaabba" print(issubstring(a, b)) print(a in b)
c73d587cc01b182062ca709d60ea56018696b97d
jack-davies/leetcode
/14.py
459
3.5
4
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ output = "" i = 0 try: while True: char = strs[0][i] for string in strs: if string[i] != char: ...
68b03d63f6ccc1d0ecf09966389597ca9be438c5
ghost099/Online-Class-Bot
/time.py
220
3.5625
4
import time #this module is preinstalled in python ''' this module helps python do a task after or before some alloted time ''' while 1: print("bruh") time.sleep(1) #this will print "bruh" every 1 second
d8cdbb7c3a7127935afdef1ced40e63a6d282579
ResolveWang/algorithm_qa
/basic_algrithms/sort_algrithms/top.py
914
3.578125
4
# 拓扑排序 def indegree0(v, e): if not v: return None tmp = v[:] # 找出入度为0的节点 for i in e: if i[1] in tmp: tmp.remove(i[1]) if not tmp: return -1 # 在关系图中标记出入度为0的节点 for t in tmp: for i in range(len(e)): if t in e[i]: e[i] = '...
d417b0ee423fae7ec8382a4acba2f62ae8fdfbb6
CocoYeh1014/CCCPython
/guessNumber.py
462
3.78125
4
import random num = random.randint(1,10) time = 0 while True: guess = int(input('num?')) if guess < num: print('bigger') time+=1 if time>5: print('over 5 times') break elif guess > num: print('smaller') time+=1 if time>5: ...
fd77a8beb342aff6112c83b66ee71c29cf19e6e7
Azurisky/Leetcode
/Finish/M445_Add_Two_Numbers_II.py
1,505
3.828125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ## Build Linked list ...
f29b015192b7a84f811c2a907257ea9884b6dcf2
ViraYermolenko/codeWars
/codewarsbegin.py
527
3.6875
4
# def square_digits(num): # a = [] # while num > 0: # a.append(num % 10) # num //= 10 # # a.reverse() # # for x in range(len(a)): # a[x] = a[x]*a[x] # # # res = int(''.join(map(str, a))) # print(res) def square_digits(num): return int(''.join([str(int(x) ** 2) for x...
044dbf3c2cab4bb6dce837364b47aa1b77e3ddfa
Magda7Lena/pair-programming
/pair.py
7,466
3.96875
4
# Memory Game - Pair programming import string import random import os def chose_level(): # printing main menu levels = ["1","2","3"] print(" 1 - easy \n 2 - medium \n 3 - hard") level = input("Chose level: ") if not level in levels: print("Invalind input") chose_level() return...
e312fc905adcbcd0717aa317057fb27596372ac4
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/27_7.py
2,813
4.34375
4
Python Program that Extract words starting with Vowel From A list Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u). > **Input** : test_list = [“all”, “love”, “get”, “educated”, “by”, “gfg”] > **Output** : [‘all’, ‘educated’] > **Ex...
6d8cea7420bdd3e34d4103b6031432d9c582f2ef
Iris11/MITx--CMITx--6.00.1x-Introduction-to-CS-and-Programming-Using-Python
/Problem Set 2_2.py
482
3.84375
4
##Problem Set 2-2 ##20150627 #balance, annualInterestRate def fixed_monthly_payment(balance, annualInterestRate): result = 0 rest = balance while rest>0: result = result + 10 rest = balance i = 0 while i < 12: Interest = (rest - result)*(annualInterestRat...
499ff769e51b78906801d0ce706968da722ca577
JayMackay/PythonCodingFundamentals
/[Session 1] Basic Syntax & String Manipulation/[4] String Manipulation/03 string_3.py
152
4
4
# Python string # Before running this code, what do you expect the output to be? text = "Python" x = len(text) print(x) print(text[len(text) - 1])
b4eb9ed217f8d9d2cb4f7211866093415b206bc8
mjburgess/public-notes
/python-notes/12.Errors/Demo12-04.7.Exceptions.py
7,119
4.46875
4
# EXCEPTIONS """ NOVICE ASIDE: Why do we use exceptions? Errors as values. """ # 1. exceptions # thus far in python code, if an error has occured the program terminates... """ 10/0 #causes program to stop """ # we can however catch the error before it causes termination... try: 10 / 0 # code which might...
e4877d18c63258ff10c098bd384fd36ebe338f6b
zizouvb/codewars
/5kyu/move_zeros.py
252
3.59375
4
def move_zeros(array): zero_counter=0 i=0 while i < len(array)-1: if array[i] == 0 and array[i] is not False: del array[i] zero_counter +=1 continue i+=1 return array+[0]*zero_counter
c5b59b3512b9e388a155c64742bf7f708d6dfcb3
itbullet/python_projects
/Stack_20190722/stack_homework2.py
576
3.625
4
import stack_class number_stack = stack_class.Stack() number_list = [1, 2, 3, 4, 5] print(number_list) """Version 1 for i in range(len(number_list)): num = number_list[i] #print(str(i) + " " + str(num)) number_stack.push(num) """ #Version 2 for item in number_list: #print(item) number_stack.push...
74affefce828dba0524cbb79c58f9c9c6a9dc16a
owlrana/cpp
/rahulrana/python/Leetcode/#055Cells with Odd Values in a Matrix.py
806
3.8125
4
# https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/ class Solution: def oddCells(n: int, m: int, indices): # Create matrix of size MxN matrix = [] for i in range(n): lst = [] for j in range(m): lst.append(0) matrix.append(l...
f4131e80b25d2852d8fcda31ad03d76ed1bc6833
aesavas/HackerRank
/Python/Sets/Symmetric Difference/solution.py
332
3.5
4
""" author : Ali Emre SAVAS Link : https://www.hackerrank.com/challenges/symmetric-difference/problem """ if __name__ == "__main__": counterM = int(input()) M = set(map(int, input().split())) counterN = int(input()) N = set(map(int, input().split())) for i in sorted(M.symmetric_difference(N)...
9fba001c4edb83eaaf95eee753af3afe6b0c0d47
dannycrief/full-stack-web-dev-couse
/Web/B/3/3.7/practice.py
661
3.765625
4
class NutritionInfo: def __init__(self, proteins, carbs, fats): self.proteins = proteins self.carbs = carbs self.fats = fats def __add__(self, other): return NutritionInfo(self.proteins+other.proteins, self.carbs+other.carbs, self.fats+other.fats) def __mul__(self, other): ...
7a0788e299ad3eab72a3d737121ed2dd805c2e8a
yrnana/algorithm
/challenge/e200324.py
771
3.609375
4
def solution(baseball): from itertools import permutations def check(number, question, strike, ball): question, s, b = str(question), 0, 0 for i in range(3): if number[i] == question[i]: s += 1 elif question[i] in number: b += 1 re...
515533b7a6b7b8676228166edfe5a941a6ecb7a0
Skyler3259/KCC
/CIS-121-Intro-to-Programming-Logic/Lists_and_Tuples/barista_pay.py
466
3.953125
4
NUM_EMPLOYEES = 4 def main(): hours = [0] * NUM_EMPLOYEES for index in range(NUM_EMPLOYEES): print('Enter the hours worked by employee ', index + 1) hours[index] = float(input()) pay_rate = float(input('Enter the hourly pay: ')) for index in range(NUM_EMPLOYEES): gross_pay = ...
4b8835b4b567f6735b975e8d7607ed86dfa375aa
EoinStankard/pands-problem-set
/ProblemFour-collatz.py
1,408
4.28125
4
#Name: Eoin Stankard #Date: 28/03/2019 #Problem Four: Write a program that asks the user to input any positive integer and outputs the #successive values of the following calculation. At each step calculate the next value #by taking the current value and, if it is even, divide it by two, but if it is odd, multiply #it ...
2a9382db04b8945d309459c60539bd8c115a59a8
aethyris/floyd-airport-example
/floyd.py
2,833
3.890625
4
# Final Exam CUS1188 Calvin Kwong import math import copy def load_graph(node_filename, edge_filename): ''' Loads the two datafiles and returns an adjacency matrix which represents a weighed, directed graph that encodes the routes between the various airports and the travel distance between each route....
f67938018441baf074afba29a6f69b6aff208b3c
BalaMurugan6/python_programs
/sort alphabetically the words from str.py
108
3.78125
4
x="Hello This Is an Example" words=[i.lower() for i in x.split()] words.sort() print(" ".join(words))
d0483b480f859e82be4ef1af52c723235220dd7a
RonAstern123/Idea-Maker
/Ideas.py
408
3.625
4
import random, time forever = 1 while forever == 1 ideas = ["Game", "Trail Art", "Shape Art", "Featured Project"] idea_chosen = ideas[random.randint(0, len(ideas) - 1)] print("Make a: " + idea_chosen) if idea_chosen == ideas[0]: including = ["Shapes", "People", "You\, the cre...
b9cf2bc4977619883bac99459e5eca168878bc81
TenaWalcot/new-to-python
/day6 homework3.py
175
4.21875
4
import pandas as pd df=pd.DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]],columns=["A","B","C","D"]) print(df[df["A"]>3]) print(df[df<10]) print(df[(df<10)&(df>3)])