blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
84f89df2cfebe4eb26697bde14d1f03fb8d321ee
ahathe/some-a-small-project
/MyPython/somePy/for_while.py
88
3.875
4
count = raw_input("input you string!:") num = count[0:] while num < count: print count
58b6c5b00be6654c5235b69a13d69bf8944d76e4
ahathe/some-a-small-project
/MyPython/Dict/rot13.py
745
3.8125
4
#!/usr/bin/env python import string letter = string.letters dict1 = string.letters[26:] dict2 = string.letters[:26] dict3 = dict1[13:] dict4 = dict1[:13] dict7 = dict2[:13] dict8 = dict2[13:] dict5 = dict(zip(dict3,dict4)) dict6 = dict(zip(dict4,dict3)) dict9 = dict(zip(dict7,dict8)) dict10 = dict(zip(dict8,dict7)...
5f88e6660cc3121adae13be51fd615eb346339fb
mergarrie/2017sum_era1_kol2
/kol2.py
793
3.703125
4
# # Class diary # # Create program for handling lesson scores. # Use python to handle student (highscool) class scores, and attendance. # Make it possible to: # - Get students total average score (average across classes) # - get students average score in class # - hold students name and surname # - Count total attend...
0fb3cd7ebc06fc8eba460ad9c5f272b65d0789ca
kgodden/monty_hall_simulation
/monty_hall.py
6,154
4.40625
4
#! /usr/bin/python # Copyright 2019 Kevin Godden # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
01b80d8260d356a43f51fb37827694b10eedb70a
Xandeus/little-bits
/python/Tictactoe.py
10,429
3.5625
4
from Tkinter import * master = Tk() gameboard = Canvas(master, width=300, height=300) #Window size gameboard.pack() gameboard.create_line(100, 0, 100, 300) #Tic tac to board gameboard.create_line(200, 0, 200, 300) gameboard.create_line(0, 100, 300, 100) gameboard.create_line(0, 200, 300, 200) # var...
2edd4a70bd9dd50e8bad02d288fa41d9c50f37a4
melinadriscoll/112_Term_Project
/blocksAndHangman.py
24,951
3.6875
4
################################################# # Term Project #Melina Driscoll, msdrisco ################################################# import random from tkinter import * def init(data): data.margin = 10 data.movingBlocks = [] data.bottomBlocks = [] data.stoppedBlocks = [] data.count = 0 ...
0eec82d183b766a6a16ae94eb3bd5cb922a03534
RayWLMo/Eng_89_OOP_Calculator_Task
/functional_calculator.py
2,183
4.03125
4
from calculator import Calculator import math class Functional_Calculator(Calculator): def __init__(self): super().__init__() def Circle_Area(r): return "The area of the circle is " + str(math.pi * (r ** 2)) def Square_Area(l): return "The area of the square is " + str(l ** 2) ...
d74575baa09a23518130f9b3fdf602b333421d36
brainstorm6334/Script-Connect-4
/Connect4.py
3,570
3.59375
4
from random import randint import os import time os.system('clear') numRows = 7 numCols = 6 trials = 0 turn = 0 numPlayers = 2 checker = ['x', 'o', '+', '*', '#'] emptyCell_symbol = "." players=[] for player in range(numPlayers): players.append(input("Player"+str(player)+", please, enter your name: ")) print() b...
7cff1b3532b012b7ca7e47c605c60ca440034f87
ayushmad/puzzles
/quora/feed_optimizer/py-imp/knapsack.py
7,894
3.53125
4
import os import sys INVALIDATED = 1; VALIDATED = 2; class KnapSack: def __init__(self, height, time_window): self.__height__ = height; self.__time_window__ = time_window; self.knapsack_state = INVALIDATED; self.__entry_set__ = []; self.best_sacks = []; return; ...
9136ddc6bbedb140ced8c4bfa73a338d3acd0bb3
ayushmad/puzzles
/hacker_rank/hack_prac/markov_snk.py
5,012
4.0625
4
import random class Die: """ Die class represents a die being inti lazied. It takes the die configuration in its constructor and provides the following A.P.I's:- roll :- generates a number in the range given the probabilites get_configuration :- returns the configuration of...
a9e211df9b7760e1e6374c259b47aed54e10fd5e
gvannest/divers
/ocs_python/game.py
2,114
4.09375
4
class Jeu: """ This is the class representing the current state fo the game (the labyrinthe). Args: Map number """ def __init__(self, map, forbidden_symbols=None): """ Builder of our game object which is the current state of the game """ self.map = '' ...
9e4fbbfc1701f780a6900d7f78636375f7e929a6
zeldafan22/Repositorio_concurrente
/Actividad_extraordinaria/login.py
1,317
3.90625
4
#Declaración de variables Users = ["test@gmail.com", "javieralvarezserrano@gmail.com", "admin"] Passwords = ["1234","uem2020","admin"] Usernames = ["test", "Javier Álvarez Serrano","admin"] user_aux = "a" #Variables usadas por el usuario usuario=input('Email: ') passw = input('Password: ') #Declaración de la función ...
c6ce051bccb4f5a3caf15e3be9a4d7bd5b9728ae
yuricoppe/Zookeeper---JetBrains-Academy
/Problems/Half-life/task.py
201
3.59375
4
initial_amount = int(input()) final_amount = int(input()) half_life = 12 count = 0 while initial_amount > final_amount: initial_amount = initial_amount / 2 count += 1 print(count * half_life)
13db3ff60e0b4a29fd875525d1d59e1adeea268d
DoubleTheDots/ubiquitous-waffle
/AttackRoller.py
1,551
3.65625
4
#D&D Attack Roller #12-04-2020 #A script to perform attack rolls of D&D weapons import random attackModifier = ('') weaponChoice = ('g') # Find out the attack modifier from the user while attackModifier not in range(0, 6): print ('what is your attack modifier?') if attackModifier in range(...
6631af2f44689a1c92d2f3b4b8568e2ec1496bdc
yashika0810/python02
/filehandling.py
1,103
4.03125
4
# with open('data.txt','r') as file: # data=file.readline() # for i in data: # word=i.split() # print(word) # try: # filehanlder=open('test.txt','r') # content=filehanlder.read() # print(content) # except: # print("Enter the correct name of the file") # finally: # ...
bd59f1e237b8033e511830a0cc0bd2b875227362
yashika0810/python02
/decorator.py
358
3.953125
4
def decorator(func1): def inner(): print("this is before function execution") x=int(input("ennter any no")) y=int(input("enter second value")) result=x+y print(result) func1() return inner @decorator def need(): print("hello I need to be decorated"...
e1539b1b259dfa90d1f776b332daee0b8a4d1863
dan0n34ik/python
/task6.py
2,336
3.875
4
my_list = [] count = 1 stop = input('Введите "стоп" чтобы остановиться или "следующий товар" чтобы продолжить заполнение: ') while True: if stop != 'следующий товар' and stop != 'стоп' and count != 1: stop = input('Введите "стоп" чтобы остановиться или "следующий товар" чтобы продолжить заполнение: ') ...
1298ec09dc5cf5bbbe9ad19dd9a691e60e384b2c
JaclynStanaway/PHYS19a
/tutorial/lesson00/numpy-histograms.py
2,352
4.53125
5
""" Author: Todd Zenger, Brandeis University This program gives a first look at Numpy and we plot our first plot. """ # First, we need to tell Python to bring in numpy and matplotlib import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm # np and plt are the standard shortcut names we give it...
0351a888a10020c1d2445fb1700e28e85ffd933a
xiliangMa/algorithm
/python/01-sort/heap_sort.py
1,153
3.71875
4
#coding=utf-8 ''' 堆排序 heapsort parent = (i+1)/2 左子节点: c1 = 2i + 1 右子节点: c2 = 2i + 2 n 为数组长度 i 为任意指定的节点 ''' def Heapify(tree, n, i): if i >= n: return tree c1 = 2 * i + 1 c2 = 2 * i + 2 max = i if c1 < n and tree[c1] > tree[max]: max = c1 if c2 < n and...
31eaa43355a00f1b855fd3b30cc4804e3e7cd4ad
ayeshnayana/Matchine-learning-code-for-semileptonic-decay-
/dataMonteCarlo.py
2,406
3.65625
4
#This function creates the file monteData.mat. This creates the training set and # target to train the neural network. The input data is provided in the .csv form. #Import python packages import scipy import io import numpy as np import csv import pandas as pd import scipy.io as sio ###########################...
ba522adf755c38008a07ac70acb9effcc2dafe1e
sonushakya9717/Hyperverge__learnings
/dsa_step_10/power_of_number.py
238
4.15625
4
def power_of_number(n,x): if x==0: return 1 elif x==1: return n else: return n*power_of_number(n,x-1) n=int(input("enter the number")) x=int(input("enter the degree of no.")) print(power_of_number(n,x))
079f4ffc6d13290d5d5a926759221caec930ebec
sonushakya9717/Hyperverge__learnings
/dsa_step_10/sum_natural_no.py
171
3.9375
4
# def sum_natural_no(n): # if n<=1: # return n # else: # return n+sum_natural_no(n-1) # n=int(input("enter your no.")) # print(sum_natural_no(n))
19d776a2dc1d105996f4c5e98177fcda5febad3b
sonushakya9717/Hyperverge__learnings
/sorting/Insertion_sort.py
288
3.90625
4
############# Insertion Sort ######## def insertion__sort(a): for i in range(1,len(a)): tem=a[i] j=i-1 while j>=0 and a[j]>tem: a[j+1]=a[j] j-=1 a[j+1]=tem return a a=list(map(int,input().split())) print(insertion__sort(a))
c084e12c1e637b862d2122f9e1cd465cbbd5ae12
sonushakya9717/Hyperverge__learnings
/dsa_step_11/bineary_treee.py
3,012
3.9375
4
# class Node: # def __init__(self,data): # self.data=data # self.left=None # self.right=None # def in_order_traversal(self): # array=[] # if self.left: # array+=self.left.in_order_traversal() # array.append(self.data) # if self.right: # ...
0ce12d065b879d092e75e5f094d7e22fd2f360eb
sug5806/TIL
/Python/Multi_Thread/multithread_exam.py
1,061
3.671875
4
import threading import time # python에는 GIL이 있기 때문에 # multithreading을 해도 # 시간상의 성능 향상은 기대하기 어렵다 # 공유 자원 # 전역변수는 대표적인 공유 자원(shared resource) # 데이터 영역이나 힙 영역에 있다면 # 모든 스레드에서 접근 및 수정이 가능 li = [i+1 for i in range(100000000)] n = 100000000 offset = n // 4 # 250 # start = time.time() # for i in range(1000): # li[i] *...
1fb377e56c6f657126e54d1bf079638d7050b3d9
sug5806/TIL
/Python/data_struct/Linked_list/dummy_double_linked_list/DLL_prac.py
3,868
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None self.previous = None class DoublyLinkedList: def __init__(self): self.head = Node("head") self.tail = Node("tail") self.d_size = 0 self.head.next = self.tail self.tail.previo...
2bf76ff03bc78a825eff0c703cd08aa05a35bd40
sug5806/TIL
/Python/algorithm/sort/merge/normal2.py
1,004
4.09375
4
# 특정 케이스를 만들고 그것에 대해 알고리즘을 만들어서 푼다 def merge(arr, start, mid, end): left = start right = mid + 1 li = [] while left <= mid and right <= end: if arr[left] <= arr[right]: li.append(arr[left]) left += 1 else: li.append(arr[right]) right += ...
b0679a30488be0b0704f9a18531ce7814cc14cb3
sug5806/TIL
/Python/data_struct/stack/prac_node_stack.py
981
4.03125
4
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.top = None def is_empty(self): if self.top is None: return True else: return False def peek(self): return self.top.dat...
b692121aa036155e4db1b52d93d8fcf4d879636d
sug5806/TIL
/Python/algorithm/fibonacci/fibo_recur.py
449
4.125
4
def fibo_recursion(n): # base case if n<= 1: return 0 elif n==2: return 1 return fibo_recursion(n-2) + fibo_recursion(n-1) # 꼬리 재귀 --> while문으로 치환가능 def fibo_iteration(n): a = 0 b = 1 for _ in range(n-1): a, b = b, a+b return a if __name__=="__main__": ...
83df2224e1b1e338d87d1d3504008a45b9faab4c
sug5806/TIL
/Python/generator/coroutine/coroutine.py
644
3.578125
4
def read_data(filename): f = open(filename,'rt') line = f.readline() while line != '': print(f'read_data : {line}') yield int(line) line = f.readline() def delegate(*filelist): for i in filelist: g = read_data(i) print(f'delegate : {i}') r...
0260e09ca5d5145f4782b5f1d273b4b0d2af6fe0
sug5806/TIL
/Python/OOP/Inheritance/method_overriding.py
942
3.953125
4
class CarOwnder: def __init__(self, name): self.name = name def concentrate(self): print("{} is concentrating!".format(self.name)) class Car(): def __init__(self, owner_name): self.car_owner=CarOwnder(owner_name) def drive(self): self.car_owner.concentrate() pri...
958ed56d4e180c73b9a67a8be3033821b4aa8b90
sug5806/TIL
/Python/algorithm/fibonacci/fibo_memoization.py
439
4.03125
4
# Memoization --> 넓은 의미로는 dynamic programming라 할수도 있음 # 이미 기억해 놓은것을 기준으로 접근횟수를 현저히 줄임 def make_fibo(): cache = [0, 1] def inner(n): if len(cache) < n: cache.append(inner(n-2) + inner(n-1)) return cache[n-1] return inner if __name__ == "__main__": fibo=make_fibo() for i ...
370ceae1a2ed0c9bce39eef6037ce4be529f1ca9
sug5806/TIL
/Python/algorithm/sort/quick/normal.py
1,485
3.703125
4
import random as rd def get_pivot_index(li, start, mid, end): """ get_pivot_index(li, start, mid, end) -> index 리스트의 맨 처음 값, 가운데 값, 마지막 값 중에서 중간 값을 가진 인덱스를 반환한다 """ idx_li = [start, mid, end] if li[idx_li[0]] > li[idx_li[1]]: idx_li[0], idx_li[1] = idx_li[1], idx_li[0] if li[id...
7b8085319c5b9c2e4b79c00dffc776da9aae6ce1
sug5806/TIL
/Python/algorithm/Queue/circular_queue.py
2,457
3.9375
4
# circular queue (원형 큐) # - 1. 크기가 정해져 있는 배열(list) # - 2. head, tail # - 3 - 1. 비어있는 큐를 어떻게 표현할 것이냐? # - 3 - 2. Out of Index 를 어떻게 할 것이냐? # head와 tail을 같은곳에 둔다 => h와 t가 같으면 empty이다 # --> 큐가 가득 찬것과 비어있는 것을 어떻게 구분할 것이냐? # tail은 값을 넣은 후에 움직인다. -> 마지막 데이터의 다음을 가리키고 있다. # -> t + 1 == h이면 full이다 # ADT -> Abstract Data Type...
30e508735a30749ae2f199c778115a2de631990f
VilmantasT/cardGameDurak
/fractionClass.py
2,533
3.640625
4
def gcd(m,n): while m%n != 0: oldm = m oldn = n m = oldn n = oldm%oldn return n class Fraction: def __init__(self, top, bottom): try: common = gcd(top, bottom) self.num = top // common self.den = bottom // common except:...
647c89efa14fb4e71a304cf4a83201ed7b49d5d9
pengye91/algorithms
/demo/josephus_queue.py
436
3.71875
4
from queue import Queue import sys def josephus(q, n, m): ret_list = [] for i in range(n): q.put(i) while not q.empty(): for j in range(m): if j == (m - 1): ret_list.append(q.get()) else: q.put(q.get()) return ret_list if __n...
89265e8f1a2c96cb98dca6a2fa8583a4b9e4e96b
5l1v3r1/Bot-Selenium-Referencing-WebSite
/FindAndOpenAWebPage.py
4,396
3.828125
4
from random import randint from selenium import webdriver """ This class allows to open google chrome, search a web site thanks to Google. On google, a method can search the web site on the pages of google if the web site is on the page it can open it. And there is another that allows to go to the next page...
232ec8bcc58c5dced9e49c338128f41da6ce1852
samirelanduk/points
/points/matrices.py
11,278
4.28125
4
"""Contains the Matrix class.""" from fractions import Fraction from .vectors import Vector, VectorSpan class Matrix: """A Matrix is a rectangular array of numbers. They are created from iterables, which will be interpeted as rows unless specified otherwise. They can be added and subtracted from each oth...
48626db607ee2c2ffe35a375fb90587d46fae838
mkdirlove/python-gibberish
/practiceProg.py
24,149
3.859375
4
import itertools import re from collections import Counter, OrderedDict from itertools import cycle, groupby import time class practiceProg(): #Write code to check a String is palindrome or not? def isPallindrom (self, string): reversed_string = string [::-1] if not string: print ...
be8c9022b14f0aa4bb32f7eb340cdfe6e199c902
Pierretag/hashcode2018
/src/vehicule.py
2,016
3.578125
4
class Vehicule(object): def __init__(self): """ Constructeur """ self.posX=0 self.posY=0 self.listRides= [] self.currentRide =0 self.tempsIndispo = 0 def evaluateRide(self,time,ride): """ Ressort la rentabilité d'un Ride {"...
3c33ad6979ce12d8da5fe0600b22f4236dd8852e
Ameerfrz/Secular-stagnation
/capital_extension/household.py
4,815
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 2 15:43:11 2021 @author: Ameer """ import matplotlib.pyplot as plt import numpy as np import policy as pol import production as pro import Government as gov β= .77 γ= .3 α = 0.7 Π_star = 1 i_star = 0 φ_π = 2 D = 0.2 g = 0.20 l_bar = 1 B_g= 0.02...
f1a0eff84fa17aa3bfcda45cb1ec7a6f7cd89385
RokcSSGChae/202003_platform
/박석채/quiz1_20.py
605
3.90625
4
"""20. 1부터 100까지 369 게임을 하려고 한다. 3,6,9가 들어가는 부분에는 '짝' 을 출력하고, 5의 배수에는 '아자' 를 출력, 그외에는 수를 출력하는 프로그램을 만드시오.""" def game_369(a): num = str(a) data = list(num) for data in num: if '3' in data or '6' in data or '9' in data: return True return False for i in range(1,101): if game_369...
75a55868e0e25a266ff2f1920e7f5315e2cb7ef2
TasnimNoshin/create-use-and-test-simple-ADT
/report/CircleADT.py
4,293
4.28125
4
## @file CircleADT.py # @title CircleADT # @author Adele Olejarz (400010177) # @date Jan 28th, 2017 #MacID: olejarza ##want to use math.pi import math ## @brief This class represents a circle # @details This class represents a circle as a triple (x,y,r) class CircleT(object): ##@brief Constructor for CircleT ...
16aa9b0bee5c58573ea785abb3dbc87dd3d4697f
messup/AlgorithmsPart1
/Week 2/week2.py
1,656
3.984375
4
from random import randrange class Deque: def __init__(self): self.items = [] def is_empty(self): if len(self.items) == 0: return True else: return False def size(self): return len(self.items) def add_first(self, item): self.items.inser...
bb596882dd9fdf844b7996063ba7c672eb7f908a
ipsorus/lesson_2
/string_challenges.py
2,148
4.125
4
# Вывести последнюю букву в слове word = 'Архангельск' def last_letter(word): print(f'Последнняя буква в слове {word}: {word[-1]}') #last_letter(word) # Вывести количество букв "а" в слове word = 'Архангельск' def count_letters(word): letters = [] res = 0 letters = list(word) for letter in lette...
c0ce351076e780f0e59de674076758d093d7a362
1181888200/python-demo
/day3/10.py
1,131
4.28125
4
# 使用枚举类 # 更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能: from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) # value属性则是自动赋给成员的int常量,默认从1开始计数。 for name , member in Month.__members__.items()...
c5df38b28dd6bff7f810b41b4c1bfc51d196e8b9
1181888200/python-demo
/day2/5.py
1,090
3.84375
4
# 切片 # 取一个list或tuple的部分元素是非常常见的操作 L = ['jack','mark','lwl','tom'] # 取前三个 # L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。 k = L[0:3] print(k) # Python支持L[-1]取倒数第一个元素,那么它同样支持倒数切片 # 记住倒数第一个元素的索引是-1。 k = L[-2:-1] print(k) a = list(range(100)) # 取奇数 # 表示从第几位开始,每隔几位取一个数 b = a[1::2] print(b) # 取前50位的偶数 b = a[0:...
6c2b19f69f039cc5e898eeb96527daf6faefd426
1181888200/python-demo
/day3/7.py
1,296
3.9375
4
# 使用@property ''' 在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改 为了限制score的范围,可以通过一个set_score()方法来设置成绩,再通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数: 但是,上面的调用方法又略显复杂,没有直接用属性这么直接简单。 有没有既能检查参数,又可以用类似属性这样简单的方式来访问类的变量呢?对于追求完美的Python程序员来说,这是必须要做到的! 还记得装饰器(decorator)可以给函数动态加上功能吗?对于类的方法,装饰器一样起作用。...
941d81fce52d2ac33c15647ab2fe2b6e0e587baf
Saquith/WISB256
/Opdracht2/Sieve_of_E.py
780
3.5
4
import sys import time import math argumentList = sys.argv fileName = argumentList.pop() upperLimit = int(argumentList.pop()) #Create the full numbers list primes = [True] * upperLimit T1 = time.perf_counter() for i in range(2, int(math.sqrt(upperLimit))) : for j in range(i, upperLimit) : # i squared, ...
f0e63c29dea4714b74ed59254633ef30e169eac1
dhruv3/IntroToPython
/Unit 5/P2.py
544
3.671875
4
# # # # # class Animal: def __init__(self, name, weight): self.weight = float(weight) self.name = name def jump(self): return self.name,"just jumped" def speak(self): return "Sound" class Dog(Animal): def __init__(self, name, weight, breed): Animal.__init__(s...
b803ec7f655a7d542913aa4403aaa6d295cad089
dhruv3/IntroToPython
/Unit 2/lists.py
263
3.53125
4
### List MyList = ['d', 'h', 'r', 'u', "v Dogra", 3] print(MyList) print(MyList[4]) MyList[4] = 'v' print(MyList) newList = ["test", MyList, 'error'] print(newList) newList[1][1] = "I replaced u" print(newList) intList = [1, 2, 3, 4, 5] print(sum(intList))
41c0150c818998f8cdc11aeed37df13d66a8a6f3
MAzarbad/SnakesAndLadders
/Snakes&Ladders.py
1,752
3.71875
4
#!/usr/bin/env python # coding: utf-8 import sympy as sp import numpy as np sp.init_printing() snakeheads = np.array([27,55,61,69,79,81,87,91,95,97]) snaketails = np.array([10,16,14,50,5,44,31,25,49,59]) ladder1 = np.array([6,8,13,20,33,37,41,57,66,77]) ladder2 = np.array([23,30,47,39,70,75,62,83,89,96]) st1 ...
dffdaf2533949385d9f615e4f4f5d8883486ab0b
ulyvodka93/paradigmas
/.gitignore/Adivina_Numero.py
1,809
4.15625
4
# Ulises Thompson python3 import msvcrt import random MENSAJE1 = "El rango de numero a adivinar va desde el 1 hasta el?... " MENSAJE2 = "Ingresa cuántas oportunidades habrá para adivinar el numero... " MENSAJE3 = "Cuál es el número?... " def pedirNumero(mensaje): """Retorna un numero ingresado po...
b732cda25aed23b3a2f629b89bccf286cf16c62c
mrvrbabu/MyPycode
/Python Developer Bootcamp/Section5-Python_Loops/1.for_loops_pt-1.py
472
4.4375
4
# ----------------------------------------------------------------------- # # --------------- ** For Loops ** -------------------------- # # Example 1 - DRY - Do not repeat yourself # n = 3 # for (i=0, i<=n,): # print(i) # i += 1 for x in range(10): print(x + 1) print("\n") for number in range(5): pri...
24a8c11de8abacaf180b9e99452ddf3e7adc17d6
mrvrbabu/MyPycode
/Python Developer Bootcamp/Section4-Python_Logic-Control_Flow/21.Conditional_statements.py
621
4.46875
4
# ----------------------------------------------------------------------- # # --------------- ** Control Statements ** ---------------------------- # """ if (boolean expression): execute the statements """ # ******************** Example Check for a single condition ******************* temperature = int(input(...
d0d29d933e69c997308480233cd114b6e10e188d
mrvrbabu/MyPycode
/Python Developer Bootcamp/Section5-Python_Loops/4.iterables.py
342
4.125
4
# ----------------------------------------------------------------------- # # --------------- ** Iterables ** -------------------------------------- # # *** Example 1 print(type(range(4))) for char in "Welcome Home": print(char) # *** Example 2 for somethin in ["Coffee", "Play with the cat", "Walk the dog"]...
04d6298043726dff3b7633ce8c5b3ad33d3884fc
scottkeller/driverreport
/driverreport-pkg/driverreport/tests/test_driver.py
4,565
3.65625
4
""" MODULE: test_driver.py DESCRIPTION: Runs unit tests on the driver module """ import unittest from ..core.driver import Driver from ..core.trip import Trip # Constants TIME_FORMAT = '%H:%M' class TestDriver(unittest.TestCase): """ Unit tests for the driver.Driver class """ def setUp(self): ...
7ae0757dc2bb97b133ac87d1a16474b9bf8f99b9
s1m0000n/PyBackend_Course
/1. XO Game/tic_tac_toe.py
7,063
3.96875
4
"""This module is a Tic Tac Toe terminal game for 2 players, nothing really special. To use it, simply import XOGame, use default constructor to initialize it with an int n or nothing, the default is the classic 3*3 board. Then use .start() to start playing! Example: from tic_tac_toe import XOGame XOGame(5).start(...
98423de12bc1da570fad223f895cf6b07df04516
mdsiegel/unit6
/palindromes.py
243
3.703125
4
#Matthew Siegel #5/10/18 #palindromes.py - finding palindromes file = open('engmix.txt') for line in file: line = line.strip() word = "" for i in range(len(line)-1,-1,-1): word += line[i] if line == word: print(word)
7724be5d1958e68c4e9c7ffef5bdf499023913f6
Miguel75An/Word-Count-Plus-Pie-Chart
/Notes5.py
906
3.84375
4
for i in [0,1,2,3,4]: print(i*2) #output 0 2 4 6 8 range(start,stop) //start is inclusive list(range(0,5)) range(start,stop,step) range(2,-10,-2) #out put 2,0,-2,-4.....-8 range(2,-10,2) #gives empty range for i in range(10,-1,-1) print(i) #output 10,9,8,7,6,.....0 #principal ...
34f49f2309446ee9150f6f42ae073d000a0c0b89
quantatic/Project_Euler
/Python/21-30/euler_26.py
1,271
3.71875
4
import time startTime = time.clock() maxCycle = 0 maxDenom = 0 def calcFraction(num): #calculates 1/num total = "0." remainder = 1 for i in range(10): if num == 0: break remainder *= 10 if not remainder % num == remainder: total += str(remainder / ...
9915ebcc44f2d7f9102941cc4355af4f198a4033
quantatic/Project_Euler
/Python/61-70/euler_62.py
473
3.53125
4
import time, itertools startTime = time.clock() i = 0 minimum = 10 ** 50 cubes = {} while True: tmp = "".join(sorted(str(i ** 3))) if tmp in cubes: cubes[tmp][0]+= 1 if cubes[tmp][0] == 5: minimum = min(cubes[tmp][1], minimum) else: cubes[tmp] = [1, i] i ...
31b3bea7d9b96ad9ba6e8e786b198a8fae7def47
sourabh60/Python
/GuessingTheNumber.py
2,534
4.09375
4
#without using functions import random print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100.") random_no=int(random.randint(1,100)) print(random_no) input1=input("Choose a difficulty. Type 'Easy' or 'Hard':") if input1 == "easy": noo=11 for i in range(1,11): print(f"Yo...
52893a9712649f11c99e4b040b9b70264f040478
eamaccready/Grok-Algos-Exercises
/recursion/sum_array.py
187
3.796875
4
# Sum function exercise 4.1 def sum_list(list): if len(list) == 0: return 0 else: return list[0] + sum_list(list[1:]) test = [2,4,3,5,1] print(sum_list(test))
6d68a6fbf26ed2aad8ce849ae8101e17b7d01eb9
faustfu/hello_python
/concur03.py
974
3.625
4
import threading import queue def washer(dishes, queue): for dish in dishes: print('washing', dish, 'dish') queue.put(dish) # create a task def dryer(tasks): while True: dish = tasks.get() # get a task if dish is None: break print('drying', dish, 'dish')...
f1eb5c32c6491efaf42302aaec66662258c9d08a
faustfu/hello_python
/concur01.py
748
3.53125
4
# Use another process to be a queue. import multiprocessing as mp def washer(dishes, queue): for dish in dishes: print('washing', dish, 'dish') queue.put(dish) # create a task def dryer(tasks): while True: dish = tasks.get() # get a task print('drying', dish, 'dish') ...
d8bd37582b365cef954fed9b43d08d12f88bf5a7
faustfu/hello_python
/file05.py
293
3.546875
4
# 1. Module:yaml(pyyaml) is for yaml processing. import yaml filename = 'a.yaml' a = {'col1': {'col11': 'a'}, 'col2': '一'} with open(filename, 'wt') as fout: fout.write(yaml.dump(a)) with open(filename, 'rt') as fin: raw = fin.read() print(raw) print(yaml.safe_load(raw))
f9741005102bfe6a30f0fd83feedcb5b337d7c5a
faustfu/hello_python
/class02.py
554
4.09375
4
# 1. Inheritance is a way to reuse codes. # 2. Subclass could replace superclass's methods or create new methods. # 3. Subclass could use super() to get superclass's object reference. # 4. Python allows multiple inheritance. It is good to just use multiple inheritance with abstract classes. class Car(): def __init_...
f5ead3e39134f4109e4e5ded915ae12a7d2e7e8e
faustfu/hello_python
/enum01.py
871
3.984375
4
# 1. Use module:enum and class to declare an enum class. # 2. A enum class cannot be initialized and its properties are immutable. from enum import IntEnum, unique # case 1: Inherite IntEnum or Enum to be an enum. class Action(IntEnum): stop = 1 right = 2 left = 3 up = 4 down = 5 print('Action is ', Action,...
7a3d476958d7a43f3545000557bd7c66990e2ab6
faustfu/hello_python
/def01.py
1,281
4.5
4
# 1. Use "def" statement with function name, parameters and indented statements to declare a function. # 2. Use "return" statement with data to return something from the function. # 3. If there is no "return" statement, the function will return "None". # 4. All parameters are references. # 5. Parameters could be assign...
b44c32a951b2689410795d427c0e89fee1be2f7e
RAGURAM-S/Machine-Learning
/machine_learning_code/boost.py.py
1,673
3.515625
4
import pandas dataset = pandas.read_csv("C:/ml/Machine Learning A-Z Template Folder/Part 10 - Model Selection & Boosting/Section 49 - XGBoost/XGBoost/Churn_Modelling.csv") x = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values #encoding categorical data from sklearn.preprocessing import LabelEncoder label_en...
a85a997d43746be36af3d634f373a22c053f60d9
Hooiu/cording_test
/Internship2020_No1.py
1,834
3.609375
4
#키패드를 누르는 규칙 #1,4,7 : 왼손 // 3,6,9 : 오른손 // 2,5,8,0 : 두 손 중 가까운 쪽(같을 경우 주 사용 손잡이에 따라) #시작은 각각 *과 # #좌표로 저장 points = {'*':[0,0],'0':[0,1],'#':[0,2],'7':[1,0],'8':[1,1],'9':[1,2],'4':[2,0],'5':[2,1],'6':[2,2],'1':[3,0],'2':[3,1],'3':[3,2]} #손가락의 최근 위치를 지정 left, right def solution(numbers, hand): num = list(map(s...
11da2210a62f491e5fc0daf99a2c899c7ce2e895
Eru-1luvatar/laba3
/laba3.py
2,075
3.546875
4
import matplotlib.pyplot as plt import math f1 = [] # список значений х f2 = [] # список значений y try: a = int(input('введите значение a:')) x = int(input('введите начальное значение x:')) xn = int(input('введите конечное значение x:')) k = int(input('введите шаг вычисления функции k:')) ex...
1a0337eb638e6164925a6ba39728971b4d459b13
englishta/python
/study/montyhall.py
1,619
3.8125
4
import random def Main(): print("Monty Hall Simulation Start!!") cnt = 10000 # ゲームの試行回数 # 扉を変更しないゲームを実施 win_cnt1 = game("Nochange", cnt) print("Nochange game : ", win_cnt1, "/", cnt) # 扉を変更するゲームを実施 win_cnt2 = game("change", cnt) print(" change game : ", win_cnt2, "/", cnt) def game(M...
3db5a60b38278665eb92c5f91da26c944b8f0549
Algumi/Python-university-practice
/Part_1/Part1_task11.py
503
3.59375
4
from datetime import date, timedelta def task_1(): d, m, y = map(int, input().split(".")) birth_date = date(y, m, d) age = (date.today() - birth_date) // timedelta(days=365.2425) print(age) print(date(y + age + 1, m, d).weekday()) def task_2(): d, m, y = map(int, input().split(".")) life...
d9651a9af2e3e3e94924014aeb30760c91793534
Algumi/Python-university-practice
/Part_1/Part1_task5.py
834
3.90625
4
def task_1(): tmp = 1 max_2 = 0 max_1 = 0 while tmp != 0: tmp = int(input()) if max_1 < tmp: max_2 = max_1 max_1 = tmp elif max_2 < tmp: max_2 = tmp print(max_2) def task_2(): cur_num = 1 last = 0 ans = 0 tmp = 1 wh...
2434973498196435ad7bf6e2bff438f03b7bfc62
enverdavid/python_learning
/04-Lambda/ejercicio.py
297
4.03125
4
# Vamos a hacer un jerecicio para saber si una palabra es palíndromo o no # Empleamos lambda: variable_contenedora = lambda argumento: argumento == argumento[::-1] print(variable_contenedora('ana')) # Empleamos una función normal: def fun(arg): return arg == arg[::-1] print(fun('ana'))
e240fabceddd8c71f1a81d400582a996bbd0ac07
avbpk1/learning_python
/circle_area.py
251
4.4375
4
# Program to accept radius and calculate area and circumference radius = float(input("Please Enter Radius:")) pi = 22/7 area = pi * radius**2 circumference = pi * 2 * radius print(f"Area is : {area}") print(f"Circumference is : {circumference}")
2c95c3f1109bd296b05896f637a61c155f2ef6d8
avbpk1/learning_python
/assignments.py
476
4.125
4
# This is assignment 1 # Program to take input from user until 0 is entered and print average. Negative input to be ignored total = 0 cnt = 0 while True: num = int(input("Please enter a number (Entering Zero will terminate) : ")) if num == 0: break elif num < 0: continue else: ...
dc01565803203b47b81cf663706fc915b235d331
avbpk1/learning_python
/19May_filter_prime_ass1.py
241
3.90625
4
# select prime numbers from a list of numbers using filter def isprime(n): for i in range(2,n//2 + 1): if n % i == 0: return 0 return 1 nums = [3,4,7,9,10,25,47] for n in filter(isprime,nums): print(n)
9f1190f69f2799fd18d2e86845f794643761d4c2
avbpk1/learning_python
/20May_ass4.py
568
4.1875
4
# -- ass4 -- use map to extract all alphabets from each string in a list. Use map and a function def ext_alpha(word_str): new_word = '' for c in word_str: if c.isalpha(): new_word += c return new_word words = ['Ab12c','x12y2','sdfds33&'] for word in words: alpha_extract =...
22cacf54126ef76723f2477cd2baa80a66c10d8f
jaiwardhan/leetcode-practice
/easy/merge-two-sorted-lists/python/code.py
2,219
3.578125
4
class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next @staticmethod def parse_into_node(some_list): head = None last = None for k in some_list: if head is None: head = ListNode(k, None...
3883b5ac776226587a30846b9d266d872e9b5905
iamrafal1/college_projects
/chat/client_solution_lab1.py
1,752
3.8125
4
# from the socket module import all import socket # Create a TCP server socket #(AF_INET is used for IPv4 protocols) #(SOCK_STREAM is used for TCP) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # set values for host 'localhost' - meaning this machine and port number 10000 # the machine address and...
2aa9d77ac95b0efd0b4b994f8971d82b39000529
AfkZa4aem/python-password-manager
/main.py
4,306
3.515625
4
from tkinter import * from tkinter import messagebox from random import randint, shuffle, sample import pyperclip import json # ---------------------------- PASSWORD GENERATOR ------------------------------- # def create_password(): password_entry.delete(0, END) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', '...
9aa2f36dc8539c6a7e8b7734fa8e32e8acd2d901
Hemant1-6/python-practice
/chapter6/codebundleANDdata.py
1,447
3.59375
4
#function to filter the list def sanitize(data): if '-' in data: splitter = '-' elif ':' in data: splitter = ':' else: return data (min , sec) = data.split(splitter) return (min + '.' + sec) # to open and split the file def get_coach_data(filename): try: with ope...
43aa1410040d47341dab6e09813c0820f38d3f97
LalithaNarasimha/Homework2
/Solution2.py
1,062
4.21875
4
# Code that compute the squares and cubes for numbers from 0 to 5, # each cell occupies 20 spaces and right-aligned numbers = [ 0, 1, 2, 3, 4, 5] place_width = 20 header1 = 'Number' header2 = 'Square' header3 = 'Cube' print('\nSolution 1\n') print(f' {header1: >{place_width}} {header2: >{place_width}} {header3: >{pl...
c821e39bc221e03539208265d97d55689c14e92a
mrjordan69/basic_python
/tic_toe.py
2,849
3.921875
4
#structure of game board=["-","-","-", "-","-","-", "-","-","-",] #display the game def structure(): print(board[0],"|",board[1],"|",board[2]) print(board[3],"|",board[4],"|",board[5]) print(board[6],"|",board[7],"|",board[8]) #function to check who won def check_o_win(): i...
d20dd77fc72be55621e1d8cbc1e58274496e95cc
thatSunshineKid/Artificial_Intelligence
/search/temp.py
1,237
3.75
4
def breadthFirstSearch(problem): "Search the shallowest nodes in the search tree first. [p 81]" "*** YOUR CODE HERE ***" frontier = [] visited = [] start = problem.getStartState() # [(int, int), "string", int] start = (start, "none", 0) # current_node = start frontier.insert(0, star...
c09a46583fbf4f523364afe7c41a0b5ac59eea7d
solalatus/orderbook
/orderbook/src/common/order.py
3,929
3.578125
4
import sys class Order(object): def __init__(self, order_type, order_id, order_price, order_size, order_peak_size=None): self.type = order_type self.id = order_id self.price = order_price # public size visible through the book self.peak_size = order_size if order_peak_size...
646d3759c43e1c2c1386e80b8e74b2ea15a4fab8
tjcai/CS10A_FINAL_SPR2020_Team_Hotpot
/final/Deck.py
1,085
3.96875
4
""" Deck is a standard deck of 52 playing cards """ import random from Card import Card class Deck: """ this represents a deck of cards """ def __init__(self): self.cards = self._createDeck() self.discards = [] def _createDeck(self): cards = [] for suit in "Hearts Spades Di...
f3b84982a8e3ba598ef6e4c593ee529957ebbeb0
mariosky/fulltext-search
/flaskr/title_search.py
1,448
3.546875
4
from bs4 import BeautifulSoup def get_title_content(html_content) -> dict: """Gets a partial html document generated by GitHub from a markdown files and returns a dictionary with the titles included in the html with the contents below them until a new title is found. Parameters ---------- htm...
3038de685700029287deef9ee5d442d65b36fad5
Sumeets2597/Artificial-Intelligence
/Maps/find_luddy.py
3,768
3.71875
4
#!/usr/local/bin/python3 # # find_luddy.py : a simple maze solver # # Submitted by : [Name:SUMEET SARODE # Usename:ssarode] # # Based on skeleton code by Z. Kachwala, 2019 # import sys import json # Parse the map from a given filename def parse_map(filename): with open(filename, "r...
28ac73367f502e5b61231985a9341fc8cd53b1c4
dogac00/Google-Interview-Questions
/jumping-numbers.py
963
3.890625
4
# Given a positive number x, print all Jumping Numbers smaller than or equal to x. # A number is called as a Jumping Number if all adjacent digits in it differ by 1. # The difference between ‘9’ and ‘0’ is not considered as 1. All single digit numbers are considered as Jumping Numbers. # For example 7, 8987 and 4343...
97487de5d1453d0b4e54528d31abb58ddddc97a9
hihumi/mymathpy
/es/tests/test_even_for_range.py
520
3.59375
4
#!/usr/bin/env python3 import unittest import even_for_range class TestEvenForRange(unittest.TestCase): def test_even_for_range(self): self.assertEqual(even_for_range.even_for_range(10), even_for_range.even_for_range(10)) print() def t_e_f_r(x): for i ...
46e586c84e21275f181cf0374f9a16239b5af65c
hihumi/mymathpy
/es/divisor_of_8.py
808
4.09375
4
#!/usr/bin/env python3 """算数問題: 約数: 約数とは、整数xを割り切ることができる整数xのこという。 例えば、8の約数は、1とその数自身である8も含まれる。 8の約数をすべて求めなさい。 """ def divisor_of_8(): """8の約数をすべて出力する関数。 引数: なし 返り値, 戻り値: なし 例: divisor_of_8() 実行結果: 8の約数: [1, 2, 4, 8] 単体テスト: doctest: >>> divisor_of_8() 8の約数:...
bb0dce9a0a6c06a33bddd80174554650466a8240
hihumi/mymathpy
/es/common_multiple_4_8.py
902
3.828125
4
#!/usr/bin/env python3 def common_multiple_4_8(four = 25, eight= 50): """4の倍数と8の倍数と公倍数を出力する関数。 問い: 4と8の倍数を求め、公倍数を見つけなさい。 """ multiple_of_4 = [i for i in range(1, four) if i % 4 == 0] multiple_of_8 = [j for j in range(1, eight) if j % 8 == 0] print('4の倍数: {0}'.format(multiple_of_4)) print('...
ae182b7a768163c9129f20b0601b09a336443403
hihumi/mymathpy
/es/multi_of_6_from_1_to_100.py
603
3.796875
4
#!/usr/bin/env python3 def multi_of_6_from_1_to_100(x = 100): """1から100までの整数から6の倍数を出力する関数 問い: 1から100までの整数に6の倍数は何個あるか。 """ """ for文 res = [] for i in range(1, x + 1): if i % 6 == 0: res.append(i) print(res) print(len(res)) """ res1 = [i for i in range(1, x ...
1df19a736a7187e04c90bb4b6ebd566cf67e7b32
losvaldote/Programas-Python
/invertir_arreglos.py
436
3.59375
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 6 10:00:12 2017 @author: LuisOsvaldo """ import numpy as np print('Ingrese números separados por espacios: ') arreglo = input() new = arreglo.split(' ') n = len(new) #print(new) #print(n) i = n-1 while i>=0: print(new[i]) i -= 1 #Ahora lo hare...
e865da8f0fca653d92128f7a515645feb473df19
JamieTurrin/Keras-Convolutional-Neural-Network
/CNN_keras.py
6,232
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 30 10:47:27 2017 @author: James Convolutional Neural Network (CNN) implemented using keras package. See https://keras.io/models/model for documentation on keras. Keras is a high-level framework for building deep neural networks quickly and can run on top of T...
afc9db7e5c606ef7456e0f55d447faa1614a252f
mayukuner/HITCS
/python programming language/EXP/EXP3.py
1,530
3.59375
4
def checkFormat(blocks): if len(blocks) != 4: #check if there are 4 blocks seperated by '-' return False; for i in xrange(4): #check if the number of characters of each block is optimal if len(blocks[i]) == 0: return False if len(blocks[3])!=1: #check if the number of the charact...