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
ffed9fc80afa668d1d3f7546f3069f2e11b762cc
vup1120/ReDiBackEnd
/homework_01_extra.py
2,139
4
4
def check_length(key): if len(key) >= 8: return True else: return False def check_uppercase(key): if sum([i.isupper() for i in key]) > 0: return True else: return False def check_digits(key): if sum([i.isdigit() for i in key]) > 1: return True else: ...
11c4f4c43084d073ad9293e27640eb979023d898
rootprophecy/grimoire
/wordparser.py
191
3.59375
4
import sys if len(sys.argv) != 2: print("Specify file to parse") exit(0) filename = sys.argv[1] w = open("wordlist.txt", "w") for word in filename.split(): w.write(word+"\n") w.close
e3f75b248da72151068bf8707e1216e33ec03f57
AnandCodeX/Beginner-to-Advanced-python-List-of-Programs
/Python/L8/pr2.py
480
4.21875
4
#waoopp class circle #radius #display() #area() #circumference() class circle: def __init__(self,r): self.radius=r def show(self): print("radius = ",self.radius) def area(self): ans=3.14159*self.radius**2 print("radius = ",round(ans,2)) def circumference(self): a...
063c19859a5ced43154772a838f685749e30b582
AnandCodeX/Beginner-to-Advanced-python-List-of-Programs
/Python/L4/pr5.py
280
4.0625
4
# wapp to read srting and display the number of letters,digits and other char s1=input("enter string") lc,dc,oc=0,0,0 for s in s1: if(s.isalpha()): lc=lc+1 elif(s.isdigit()): dc=dc+1 else: oc=oc+1 print("letters=",lc,"digits=",dc,"others",oc)
70cf198da982e0a26c83fdc794f7749832dc8d25
AnandCodeX/Beginner-to-Advanced-python-List-of-Programs
/Python/L2/pr7.py
142
4.375
4
#wapp to read int no to find if its even or odd n1=int(input("enter a number")) if (n1%2==0): print("no is even") else: print("no is odd")
0819dfb39de3fa2440693832325482c90a5f20b4
AnandCodeX/Beginner-to-Advanced-python-List-of-Programs
/Python/L14/pr2.py
544
3.703125
4
import pandas as pd import matplotlib.pyplot as plt data=pd.read_csv("petrol_prices.csv") month=data['MONTH'].tolist() mumbai=data['MUMBAI'].tolist() delhi=data['DELHI'].tolist() chennai=data['CHENNAI'].tolist() plt.plot(month,mumbai,label='Mumbai',linewidth=3,marker='o',markersize=10) plt.plot(month,delhi,label='Del...
3ff469a4f6136543626af2e55bda1b56fc795992
AnandCodeX/Beginner-to-Advanced-python-List-of-Programs
/Python/L9/pr4.py
271
3.6875
4
class Book: def __init__(self, nop): self.nop = nop def __add__(self, other): res = self.nop + other.nop return Book(res) def __str__(self): msg = 'nop=' + str(self.nop) return msg b1 = Book(100) b2 = Book(200) b3 = Book(300) r1 = b1 + b2 + b3; print(r1)
cdf618d95d1d4e99aeccf6e67df08a96a7f812a7
RSnoad/Python-Problems
/Problem 7.py
588
4.125
4
# Find the 10,001st prime number from math import sqrt # Function to find the nth prime in list using the isPrime function below. def nthPrime(n): i = 2 primeList = [] while len(primeList) < n: if isPrime(i): primeList.append(i) i += 1 print(primeList[-1]) # Brute force m...
94ddb4c5088d5ff8e6ee352d1e3cd044d4faaa0b
ZachMarcus/python-utils
/Network/Pinger.py
2,548
3.5
4
import multiprocessing import subprocess import os class Pinger(object): """ Class to Ping all IP addresses on a given subnet, but quickly. Was developed for a basic server operation for a hackathon, but the speed is useful. Takes in a base IpString, e.g. '192.168.1' or '130.0.1.' and pin...
f6d334d898596783e7385ae495ff7f2c4a035553
micku/chess
/chess/piece.py
3,793
3.96875
4
"""Module that contains all the pieces logic""" import itertools class Piece(object): """Interface for the pieces""" def iter_threats(self, board_size, position): """Iterator for all the possible positions in the board that can be reached by the piece :param board_size: Size of the ...
685452c53ea915107f3f2a2ec2ef020a1702f132
isaac-friedman/lphw
/ex20-2.py
1,661
4.6875
5
#### #This file combines what we've learned about functionwas with what we've #learned about files to show you how they can work together. It also #sneaks in some more info about files which you may or may not know depending #on if you did the study drills. #### from sys import argv #In some of my versions of the stud...
21e7a38cfa5194e6b321693cbe24008421ff0974
isaac-friedman/lphw
/ex13-3_calc.py
1,129
4.6875
5
#### #More work with argv #This time we will use argv to collect two operands and then use raw input to #ask for an arithmetic operation to perform on them. Effectively, we've just #made a basic calculator #### from sys import argv #### #See how we aren't checking to make sure the arguments are numbers? That is a ...
d1c8dbc2a8c9ba6edff5ff330a826997c5c019dc
isaac-friedman/lphw
/ex15.py
1,390
4.5
4
#### #This script prints a specified file to the screen. More specifically, it #prints to something called "standard output" which is almost always the screen #but could be something else. For now, think of 'print' as 'printing to the #screen' and 'standard output' or 'stdio' etc as "the screen." It's easier and #pret...
239ac580ced3c97a6e7fcd967b76f52cd0f17906
isaac-friedman/lphw
/ex8.py
466
3.703125
4
formatter = "%r %r %r %r" #using the formatter for digits print formatter %(1, 2, 3, 4) #and now strings print formatter %("one", "two", "three", "four") #bools print formatter %(True, False, True, False) #And you can even put a formatter in a formatter!! print formatter %(formatter, formatter, formatter, formatter) #...
b4a2cf2fbc2dce67f6913441d6b7f26b8e630400
JosiahRegencia/cs271a-admu
/homework/tree_view.py
1,129
4.0625
4
class TreeView: def __init__(self): self.zero = list() self.one = list() self.two = list() self.three = list() self.four = list() self.five = list() def add_node(self, level): if level == 0: self.zero.append(level) elif level == 1: self.one.append(level) elif level == 2: self.one.append(le...
26048adc17798ee814fed45935d634cf56dbb4a1
dlangheiter-tgm/sew5-currency-converter
/src/api/ApiResponse.py
1,009
3.578125
4
from typing import List from api.CalculatedRate import CalculatedRate class ApiResponse: """ Class to represent the api response """ def __init__(self, amount: float, base: str, date: str, rates: List[CalculatedRate] = None): """ Constructor :param amount: Amount in base cur...
80eaa8d80e3c8a9430d1623898c5c3889889dd53
UnsupervisedDotey/Leetcode
/数组/189_rotate-array.py
810
3.6875
4
class Solution: def rotate(self, nums, k) -> None: """ Do not return anything, modify nums in-place instead. 替换list里面的原位置数据,用nums[:] 卧槽我是sb吧,你看人家这个多简单 k = k % len(nums) nums[:]= nums[len(nums)-k:] + nums[0:len(nums)-k] """ k = k % len(nums) ...
db1143e720d5235473f01ca94cc39b6ef14e92fd
UnsupervisedDotey/Leetcode
/栈/155.py
1,464
4.5625
5
# 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 class MinStack: def __init__(self): """ initialize your data structure here. """ self._the_min = [] self._data = [] def push(self, x: int) -> None: self._data.append(x) if len(self._the_min) == 0: ...
e9d31d593df6de783550d8108e406f04e447aa71
UnsupervisedDotey/Leetcode
/数组/11_maxArea.py
1,160
3.59375
4
"""import math class Solution(object): def maxArea(self, height): :type height: List[int] :rtype: int center = int(math.ceil(len(height) / 2)) most = 0 for left in range(len(height)): for right in range(left, len(height)): # print("left: ", le...
bf6290da5d55fae82011d9626b24016490662560
UnsupervisedDotey/Leetcode
/栈/1047.py
620
3.5
4
class Solution: def removeDuplicates(self, S: str) -> str: chars = set(S) sign = 1 res = S # print(S, chars) while True: # print(res, sign) for c in chars: res = res.replace(c + c, "") sign = 1 for c in char...
9659ac3187233a29e9e81717b67d4daa557f53cb
UnsupervisedDotey/Leetcode
/链表/142_LinkedListCycle2.py
813
3.765625
4
# Definition for singly-linked list. class Node(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ fast = slow = q = head while fast and ...
c2aa5b9fa4000d5b1428c8ed4989146407a4b28a
UnsupervisedDotey/Leetcode
/数组/33_SearchInRotatedSortedArray.py
341
3.8125
4
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target not in nums: return -1 else: return nums.index(target) sol = Solution() print(sol.search(nums=[4, 5, 6, 7,...
0ecf89f8aaf190c1b98a908282977dd1e05bc10d
UnsupervisedDotey/Leetcode
/动态规划/70_climbStairs.py
502
3.5625
4
# import pysnooper class Solution: # @pysnooper.snoop() def climbStairs(self, n: int) -> int: if n <= 0: res = 0 elif n == 1: res = 1 else: _1 = 1 _2 = 1 res = 0 for stair in range(2, n+1): res =...
01bf4279fd1952a0d0051e012601ec41a22c6928
hyunoh-bong/python_Lecture
/190404.py
1,186
3.890625
4
''' person=input('Enter your name: ') print('Hello', person) yes_votes=23_453_457 no_votes=65_463_454 percentage=yes_votes/(yes_votes+no_votes) print('{:-9,} YES votes {:2.2%}'.format(yes_votes,percentage)) import math print(f'Thevalue of pi is approximately {math.pi:.5f}.') animals='eels' print(f'My ho...
fc243d78fb1deb4a8f7f6f9b00e609aa676f023c
imcdonald2/Python
/tool.py
1,156
4.03125
4
def get_id(): while True: try: ID = int(input("What is the user ID?\n")) except ValueError: print("Not an integer.") continue if len(str(ID)) < 6: print("Not a valid ID") continue else: return ID def roleID(): ...
32969801992fefeeb0f6d49ce23b1cd6defc67ea
imcdonald2/Python
/9-7_admin.py
1,193
4.125
4
class User(): """User info""" def __init__(self, first_name, last_name, age): """User first name, last name, and age""" self.first = first_name self.last = last_name self.age = age def describe_user(self): print('First name: ' + self.first.title()) print('Las...
9b7aadcf4f67030937d8c1b176ff664aa56bd4f5
imcdonald2/Python
/restaurant.py
412
3.703125
4
class Restaurant(): """Restaurant open signs""" def __init__(self, restaurant_name, cuisine_type): """Initialize name and cuisine.""" self.name = restaurant_name self.food = cuisine_type def describe_restaurant(self): print(self.name.title() + " serves delicious " + self.foo...
facb0b1ed0d16cf1d668bac3eeda640c7268c3be
Fiorella14/Ejercicios-Python-Basico
/Reemp_ult_elem_lista.py
259
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 20 18:49:30 2021 @author: fiore """ a = [1, 3, 5, 7, 9, 10] b = [2, 4, 6, 8] d=[] for i in range(0, len(a)): if i < len(a)-1: d.append(a[i]) for l in range(0, len(b)): d.append(b[l]) print(d)
e7d81c38b00d581099d1587831670380b5fb56f9
Fiorella14/Ejercicios-Python-Basico
/CalculaElRadioDelCirculo.py
1,144
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 17 11:02:04 2021 @author: fiore """ #Función ingresarradio, que permite al usuario ingresar el radio del círculo #Parametro de entrada: No tiene #Parametro de salida: radio, es el radio del círculo ingresado por el usuario y es del tipo float def ingresarradio(...
209880bc58394e1b26637a150f957699452642e9
gabcruzm/Basis-Python-Projects
/loops/loop_through.py
493
4.40625
4
#Loop through a string with For def run(): # name = input("Write your name: ") # for letter in name: #For letters in the name it will print each letter in each loop. # #letter is the variable that will represent each character in each repetition in the for loop. The characters are taken from the name w...
e471cb0845e9550d954db99e807ac0adebd115c0
maimoneb/dsp
/python/q8_parsing.py
1,295
4.3125
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program t...
8cfe8ca238011b6791f8062faef84ba2d82a909c
irenexychen/Design-Patterns
/Singleton.py
1,664
3.578125
4
__author__ = 'Xiang-Yi' #key-value pair example with **kwargs def greet_me(**kwargs): if kwargs is not None: for key in kwargs: print ("%s == %s" %(key, kwargs[key])) greet_me(name="yasoob", age="18",year="2017") #iterations --> which item to call first is uncertain, defined by th...
0683ce9759ee5bea2dd997fcff5441d67c5c3aea
Petr-Pan/Python-playground
/Lekce 5/HomeW/Domaci projekty 4/Ukol 4-20.py
133
3.703125
4
cislo = int(input("Zadej číslo: ")) if cislo % 2 == 0: print("Číslo je sudé.") else: print("Číslo není sudé.")
2383c812319d352ebea33f998236c4417a31c37a
prasadks747/myNewRepo
/Divisors.py
112
3.734375
4
nm = int(input("Enter Number:")) for e in range(1,nm-1): if (nm % e)==0: print(e, "devides by", nm)
c460e7ade24b2f7fb38c1b4d59c579d892d3d562
vijaysharma1996/Basic-PYTHON-programs
/pg4.divisible by 3 and not by 2.py
184
3.78125
4
list=[] for item in range(1,10): if(item%3==0): if(item%2!=0): list.append(item) #please don't cancel my pull request .i am learning hot to pull request.
ecb24c77dc387442b63e4ec2a02da391e7e2b2a8
SimaoFernandes/Py_Tkinter_UI_01
/RockPaperScisor/process.py
479
3.625
4
def process(userInput, choice): ppt = ['pedra','papel','tesoura'] if userInput not in ppt: return 'Palavra Invalida' if userInput != choice: if ppt.index(userInput) - 1 == ppt.index(choice) or (ppt.index(userInput) == 0 and ppt.index(choice) == 2): return 'Ganhou' ...
1b4ee4a492b308e79a07255c9ff5a030f7060491
pbexe/CM1103-Python
/questions_1_and_2.py
6,401
4.15625
4
# -*- coding: utf-8 -*- """ The various implementations for questions 1 and 2. To run the code for question 2, run the file. To run the code for question 1, import and run the corresponding modules from an external python script/interpreter. """ import csv import math import random import matplotlib.pyplot as plt i...
e2c640b9c08048967126cec8e4bd9dd9a12c6d6c
jiaxukang/ShootingGame
/ship.py
1,648
3.578125
4
# _*_ coding: utf-8 _*_ # @Time : 2017/9/14 15:22 # @Author : Ligb # @File : ship.py import pygame from pygame.sprite import Sprite class Ship(Sprite): """飞船相关""" def __init__(self, ai_settings, screen): """初始化飞船并设置其初始位置""" super().__init__() self.screen = screen ...
f04988a0428707ad0482071ed7deafdc86aa7b7c
BostonPython/fingertools
/attendees.py
4,301
3.6875
4
"""Print a list of attendees for a meetup event.""" # http://www.meetup.com/meetup_api/ import argparse, pprint, random, sys, time from collections import defaultdict from meetup import meetup from keys import GROUP_ID the_encoding = sys.stdout.encoding or 'utf8' def list_events(**kwargs): """Return a list of ...
d41d7829c94108115d63a1e9317174d16c5380d9
fazli1702/Chess
/piece.py
8,660
3.78125
4
import pygame from constant import * class Piece: def __init__(self, col, row, colour): self.row = row self.col = col self.colour = colour self.selected = False self.move_num = 0 def get_pos(self): return (self.col, self.row) def get_pos_nota...
cb1d8456df820627a2f96684171dee91766935f0
pratikv06/python-tkinter
/Grid.py
291
4.03125
4
from tkinter import * root = Tk() myLabel1 = Label(root, text="Hello Python!") myLabel2 = Label(root, text="Hello TKinter!") myLabel1.grid(row=0, column=0) myLabel2.grid(row=1, column=1) Label(root, text="Directly using grid with Label").grid(row=2, column=2) root.mainloop()
72e7171a13387c6fcd77caf8c2c3b03ddf82c155
pratikv06/python-tkinter
/Entry.py
520
4.1875
4
from tkinter import * root = Tk() # Define a function for button4 to perform def myClick(): msg = "Hello, " + e.get() + "..." myLabel = Label(root, text=msg) myLabel.pack() # Create a entry i.e. input area # setting width of the entry # changing border width of the entry e = Entry(root, widt...
e98f694aa29d3d58fb86cc94c0ec6ed2070b0bc2
bohyun2020/DataScience_learning
/DataScience/01_dataquest/202007_Fundamentals/01_Course_Mission/20200729_Functions_Fundamentals.py
10,207
4.5
4
# 1. Functions """ It takes in an input. It does something to that input. It gives back an output. we could use what we've learned to write code that manages to perform the same task as len() does. This should give us some insight into how the len() function counts the length of a list """ ""...
522bc16624f91b18656e9d3d065b4733b541197b
bohyun2020/DataScience_learning
/DataScience/01_dataquest/202008_Intermediate/01_Course_Mission/20200820_Working_Dates_and_times_TimeClass.py
5,939
4.34375
4
""" 7. The Time Class we're going to analyze presidential appointment times. To achieve this, we're going to use the datetime.time class. datetime.time(hour=0, minute=0, second=0, microsecond=0) """ """ # 1) Sample import datetime as dt two_thirty = dt.time(14, 30) print(two_thirty) five_sec_after_8a...
5964c3962b023f985f9efaa721bd5782da874b29
janduy/pythonProjects
/eletronica.py
586
3.578125
4
import RPi.GPIO as GPIO #importa a biblioteca das GPIO import time #biblioteca de tempo PIN=16 def acao_detectada(): print ("cadeado produzido") GPIO.setmode(GPIO.BOARD) #configura o modo de definicao de pinos como BOARD GPIO.setwarnings(False) #destiva avisos GPIO.setup(PIN,GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #re...
cbf1805dda8f954f21722b10c4bb500933a94b13
Chloemartin99/PythonSem1
/Sessions/Sess11_12/homework_ex4.py
247
3.546875
4
# generate 100 numbers, print only the prime ones import random for i in range(100): num = random.randint(0, 1000) for j in range (2, num//2): if num%j ==0: break if j == (num // 2) - 1: print(num)
0888b4af09c5696b567086eeb468693386a38675
Chloemartin99/PythonSem1
/Sessions/Sess23_24/datavisualization1.py
971
3.6875
4
from matplotlib import pylab as plt #first step series1 = [] series2 = [] series3 = [] for i in range(0,30): series1.append(i) series2+=[i*i] series3+=[i**3] plt.plot(list(range(0,30)), series1) plt.plot(list(range(0,30)), series2) plt.plot(list(range(0,30)), series3) #plt.show() #first improvement: us...
3c8a52e0692e27e7e07a8c63fceb721025480944
Chloemartin99/PythonSem1
/Sessions/Sess11_12/ex2_sol.py
477
3.859375
4
#Determine the average of 4 random numbers def avg(list_numbers): sum = 0 for i in list_numbers: sum = sum + i average = sum/len(list_numbers) return average 'This is just a function' 'Ask the user for 4 numbers' i = 0 numbers_list = [] while (i<4): try: n = input('give me a number...
df86f9eee1e136f4bd70ae07d43dc3d6c7474095
Chloemartin99/PythonSem1
/Sessions/Sess7_8/homework.py
341
3.59375
4
s = "azcbobobegghakl" current = "" longest = "" for i in s: if current=="": current = i if i< current[-1]: if len(current) > len(longest): if s[0]==current[0]: current = current[1:] longest = current current = i else: current = curr...
ade65ba1b20ac058bfc4d12f7773146e547bd9a0
EvanLerner/pychess
/gameBoard.py
5,064
3.5
4
import absPiece from pieces.bishop import Bishop from pieces.king import King from pieces.knight import Knight from pieces.nopiece import NoPiece from pieces.pawn import Pawn from pieces.queen import Queen from pieces.rook import Rook class Board(): def __init__(self): self.board = [[], [], ...
61b16a103e8621f46ac2c29dd2b157e2fa0f6b0e
SandraHYQ/Week7_Lecture_Code
/Weeks/A1/a1b.py
2,060
3.6875
4
# Import csv module import csv #Define variables regions = [] regions_revenue = {} regions_units = {} current_regions = "" current_revenue = 0.0 current_units = 0 total_units = 0 total_rev = 0.0 # Import input file with open("500000 Sales Records.csv", "rt") as Sales_Records: # Read input file reader = csv...
fd2b47202dad2002013153f2128ef28840a9a15d
muneef97/Basic_String_Programs
/decryption.py
193
3.65625
4
string1 = "1a1b1a2g" arr = [] for i in range(len(string1)): if(string1[i].isdigit()==True): for j in range(int(string1[i])): arr.append(string1[i+1]) print("".join(arr))
5a718022823666bae2b532585794cf3b513183de
muneef97/Basic_String_Programs
/pyramid pattern.py
134
3.78125
4
n = 5 for i in range(n): print("\t" * (n-i),end = " ") for j in range(i+1): print("*", "\t"*2,end=" ") print("\n")
21cae5cdc5b43d27e62d161e20d46712ae3d7282
mdelite/Exercism
/python/guidos-gorgeous-lasagna/lasagna.py
1,467
4.34375
4
"""Functions used in preparing Guido's gorgeous lasagna. Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum """ EXPECTED_BAKE_TIME = 40 PREPARATION_TIME = 2 def bake_time_remaining(elapsed_bake_time): """Calculate the bake time remaining. :param elapsed_bak...
2acbc3961f418cd587dd708bb8652277ec160b84
IshitaTakeshi/Algebra
/galois/polynomial.py
9,351
3.78125
4
from util import decimal_to_base_n modulus = 0 modulu_polynomial = None def set_modulus(modulus_, polynomial): """ modulus_ : int polynomial : list """ global modulus, modulus_polynomial modulus = modulus_ modulus_polynomial = Polynomial(polynomial) class Element(object): def __ini...
005caff6642f033050c48ade78de440cdbef4747
MacccLiu/Python_Learning-PythonInterviewBible
/py_code/cpy.py
558
3.875
4
''' CPython: 把频繁使用的整数对象用一个叫small_ints的对象池缓存起来造成的。 small_ints缓存的整数值被设定为[-5, 256]这个区间,也就是说, 在任何引用这些整数的地方,都不需要重新创建int对象, 而是直接引用缓存池中的对象。如果整数不在该范围内, 那么即便两个整数的值相同,它们也是不同的对象。 ''' a, b, c, d = 1, 1, 1000, 1000 print(a is b, c is d) def foo(): e = 1000 f = 1000 print(e is f, e is d) g = 1 print(g is a) foo...
9e5ae7d0144593d8b812b64c0c68c9f5814e3303
05Prakhar/Python-Projects
/URLShorten.py
131
3.578125
4
import pyshorteners url = input("Enter URL") s = pyshorteners.Shortener() print("Your shortened URL is : ", s.tinyurl.short(url))
1216602668067d9a17e4dd59c896d8fe2250be54
sssmrd/pythonassignment
/38.py
238
4.28125
4
#program to add member(s) in a set. l=input("Enter some elements=").split(); s=set(l); print(s) c=int(input("How many elements to enter=")) for i in range(0,c): n=input("Enter the element to be added in set=") s.add(n); print(s)
8c3b67205aa8673696b2bf7bdcf6f36b3b331c1d
sssmrd/pythonassignment
/16.py
74
3.53125
4
#program to sum all the items in a list. l=[1,2,3,4,5,4.5] print(sum(l))
ad8911c58b30f00dfa1400ce7b23c67efb5ef584
shreeyamaharjan/AssignmentIII
/A_i.py
421
3.9375
4
def towerHanoi(n, source, destination, temporary): if n == 1: print("Move disk {} from {} to {} ".format(n, source, destination)) else: towerHanoi(n - 1, source, temporary, destination) print("Move disk {} from {} to {} ".format(n, source, destination)) towerHanoi(n-1, temporary...
ca6341a13308ff63dc68f4546802e8f70b3db014
shreeyamaharjan/AssignmentIII
/A_a.py
534
4.125
4
def bubble_sort(nums): for i in range(n - 1): for j in range((n - 1) - i): if nums[j] > nums[j + 1]: temp = nums[j] nums[j] = nums[j + 1] nums[j + 1] = temp print(nums) else: print(nums) print("\...
55b8617e66a268c69ef5e2e14861dcc494034b11
edwardyulin/sit_project
/sit_il/utils/moving_average.py
623
4.15625
4
import numpy as np def moving_average(data: np.ndarray, window_size: int) -> np.ndarray: """Return the moving average of the elements in a 1-D array. Args: data (numpy.ndarray): Input 1-D array. window_size (int): The size of sliding window. Returns: numpy.ndarray: Moving average...
cd456888d6b2c66a472f4d26427e6943e8264174
horacn/test_python
/test/systemutil/test_collections.py
3,181
4.46875
4
# collections | collections是Python内建的一个集合模块,提供了许多有用的集合类。 # namedtuple | namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x) print(p.y) # 这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属...
6d58304013c5d7e44900822c71a65f897230eaf1
horacn/test_python
/test/test3.py
1,430
3.8125
4
# !/usr/bin/env python3 # -*- coding:utf-8 -*- import sys import os # 条件判断 # 获取用户输入 # ageStr = 12 ageStr = input('请输入年龄: ') try: age = int(ageStr) #python 没有块级作用域 参考:http://python.jobbole.com/86465/ except: print('年龄输入错误') # os._exit(0) sys.exit(0) # sys.exit()的退出比较优雅,调用后会引发SystemExit异常,可以捕获此异常做...
d2fe3863a6a60da3094c4589ab71da539481602e
horacn/test_python
/test/test1.py
4,693
4.03125
4
# !/usr/bin/env python3 # -*- coding:utf-8 -*- ''' Python3 中有六个标准的数据类型: Number(数字) String(字符串) List(列表) Tuple(元组) Sets(集合) Dictionary(字典) ''' counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 # 删除对象的引用 del counter ''' Python3 支持 int、float、bool、complex(复数)。 注意:在 Python2 中是没有布尔型的,它用数字 0 表示 False,用 1 ...
a22d42a4081f48353c741c7f3cbf273a8b41e4a6
horacn/test_python
/test/except/test20.py
757
3.9375
4
# 抛出异常 raise #自定义异常类型 class FooError(ValueError): pass def foo(s): n = int(s) if n==0: raise FooError('invalid value: %s' % s) return 10 / n # foo('0') # 先捕获异常,打印相关信息后又抛出去 print('====================================') def foo(s): n = int(s) if n==0: raise ValueError('invali...
b5aa438957ab34145e3e8228f28ffddc91251e80
joshisujay1996/OOP-and-Design-Pattern
/oop/employee_basic.py
1,049
4.3125
4
""" Basic OOD Example In python everything is derived from a class and they have their own methods, like List, tuple, int, float, etc Everything is an Object in PY and they have there own methods and attributes we create instance out of the list class or tuple or etc pop, append,__str__, remove are methods of th list...
a8e2571bf5b600f229c6bc9a8451626bfbf485e1
rupafn/leetcode
/easy/SearchInBinaryTree.py
836
3.90625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def searchBST(self, root, val): if(val == root.val): return root search = [] while(root is not None): ...
a14c7d272f5e44c21e54e66fe2fea870d39091e5
rupafn/leetcode
/medium/removeNthNodeFromaList.py
1,190
3.53125
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head, n): next = head arrs = [] i = 0 while(next.next): arrs.append(next.val) next = next.next arrs.append(next.val) ...
6d706fdad1853e98c9c07ddb3c941aefcbd81fe4
rupafn/leetcode
/easy/uglyNumber.py
1,039
3.75
4
class Solution: def isPrime(self,n): i = 2 while(i*i<=n): # print(n,i,n%i) if(n%i==0): return False i+=1 return True def getPrimeFactors(self,i): listt = [] j = 2 while(j*j<=i): if( i%j==0): ...
8120f825e8c960f977f8d3926090f980844acc2b
rupafn/leetcode
/binarySort.py
104
3.75
4
nums1 = [1,3] nums2 = [2] l = nums1+nums2 newl = [0]*len(l) print(newl) for i in range(0,len(l)):
3278aabcc79d1faf37acbb3b96d9c4beacbea8b2
wildered/Python
/Project_Euler_Python/Problems101-149/Euler121.py
915
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 23 13:20:01 2016 @author: Home """ #Recursive function counting the chance of winning #Note that having 8 blue discs implies a certain win, and 8 red a loss. #Time: 20ms from math import gcd from datetime import datetime def func(blue, red, depth, disks, chance_a, cha...
9a905e9d3e462727ae9144285e87d360830270ab
wildered/Python
/Project_Euler_Python/Problems076-100/graph_module_v2.py
4,054
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 27 00:03:01 2016 @author: Home """ class node: def __init__(self, name): self.name = name self.edges = [] self.checked = 0 self.out = [] def add_edge(self, edge_new): self.edges.append(edge_new) self.o...
e4d66635148c04efc8d1392db015321817cf793e
wildered/Python
/Project_Euler_Python/Problems076-100/Euler80.py
669
3.578125
4
# -*- coding: utf-8 -*- from datetime import datetime startTime = datetime.now() #print datetime.now() - startTime #python modules... from math import sqrt from decimal import Decimal from decimal import getcontext getcontext().prec = 105 def digitSum(number): temp = int(sqrt(number)) b = Decimal(number).sqr...
88dc2883e6def1d0f333fb36f398f6588f155737
wildered/Python
/Project_Euler_Python/Problems101-149/Euler112.py
2,318
3.734375
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 11 21:21:20 2017 @author: Home """ #Once a bouncy subsequence is found, we can just skip over the remaining #digits as they'll form bouncy numbers as well and count these. #In order not to skip over the target, we only increment by one should we #exceed the target. Howe...
6bc9f20c20940fec6f28c2412d73050d5b9fe9d4
wildered/Python
/Project_Euler_Python/Problems026-050/Euler28.py
326
3.59375
4
# -*- coding: utf-8 -*- from datetime import datetime start = datetime.now() value = 1 res = 1 for extra in range(2,1001,2): #width of sides excluding corners for i in range(4): #4 numbers in square to add, each "extra" apart value += extra res += value print res print datetime.now()-...
d20c9d25b9146e5be0b8b83feaca4d111772ea7f
wildered/Python
/Project_Euler_Python/Problems076-100/Euler90.py
1,666
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 11 15:02:32 2016 @author: Home """ #it works from datetime import datetime startTime = datetime.now() #print datetime.now() - startTime def test(arr1, arr2): if (0 in arr1 and 1 in arr2) or \ (1 in arr1 and 0 in arr2): if (0 in arr1 and 4 in arr2) or \...
7daff79106aac44ca29cf45eacd81304187b3452
wildered/Python
/Project_Euler_Python/Problems026-050/Euler29.py
233
3.78125
4
# -*- coding: utf-8 -*- from datetime import datetime start = datetime.now() res = set([pow(a,b) for a in range(2, 101) for b in range(2, 101)]) print len(res) print datetime.now()-start #computation time: 15ms
0f7a68129bc538c740a6eaf6cc61578f6bb7adc7
khalid-khg/Python1
/wjileloop.py
398
3.875
4
num_of_tries = 0 while num_of_tries != 3: username = input('please insert your username: ') password = input('please insert your password: ') if username == 'khalid' and password == '1234' : print('Welcome') unm_of_tries = 0 exit() else: print('error') num_of_trie...
02036b74755314bfa61c61221a4a9e968d0145cb
realy-qiang/project
/finally/swiper/qdz/Swiper/libs/test.py
1,002
3.65625
4
# class myIteration(object): # def __iter__(self): # self.x = 0 # return self # def __init__(self, n): # self.n = n # def __next__(self): # if self.x < self.n: # self.x += 1 # return self.x # else: # raise StopIteration # my_iteration = myIteration(5) # for i in my_iteration: # print(i) impor...
9f4d1a070426905e871c302e17de9324a2cf0810
Emilleopold/PHYTON
/UDEMY_Python_for_Beginners_from_Alex_Bowers/Python-learnprogram/LearnPython/list_overview.py
264
3.71875
4
list = [1,2,3,4,5,6,7,8,9,10,11] length = len(list) print(list[3]) # Started mit 0 von links print(list[-2]) # Started nit -1 von rechts print(list[length-2]) # Das gleiche, wie vorige Zeile print(list[4:8:2]) print(list[:4:2]) print(list[4::2]) print(list[:4:2])
ad7adb3b5c7479447ab016e1107edb760236884f
Emilleopold/PHYTON
/UDEMY_Python_for_Beginners_from_Alex_Bowers/Python-learnprogram/LearnPython/for_loop.py
319
3.84375
4
for a in [0,1,2,3,4]: print(type(a),a) for s in 'String': print(type(s),s) for key,data in enumerate('strings'): if key % 2 == 0: print('The letter {} is in an even location'.format(data)) for i in range(1,10): print('This is i = {} with type of {}'.format(i, type(i)))
26660dbb32762205e356bdf7c73043bc23b03459
noelevans/sandpit
/bayesian_methods_for_hackers/stock_loss_function_example_ch05.py
1,024
3.625
4
from matplotlib import pyplot as plt import numpy as np def stock_loss(true_return, yhat, alpha=100.): if true_return * yhat < 0: # opposite signs, not good return alpha * yhat ** 2 - np.sign(true_return) * yhat \ + abs(true_return) else: return abs(true_return - yhat) de...
7a7f7a7da20f360d26e9859af09d434ba183e180
noelevans/sandpit
/simulated_annealing.py
3,622
3.84375
4
""" Implementing Einstein's Fish riddle explained here: http://blog.pluszero.ca/blog/2016/07/17/ using-simulated-annealing-to-solve-logic-puzzles/ """ from __future__ import division import numpy as np # house 1 2 3 4 5 animals = ['bird', 'dog',...
77f0d6bc1a4ef56336d14c6cfca328b8ec261a23
noelevans/sandpit
/euler/triangle_num_divisors_q12.py
856
3.828125
4
import math import time def triangle(n): return int(n * (n + 1) / 2.0) def divisors(n): lowers = [i for i in range(1, math.ceil(math.sqrt(n)) + 1) if n % i == 0] uppers = [int(n / low) for low in reversed(lowers)] return len(set(lowers + uppers)) def divisor_count(stop): i = 1 while True: ...
71766d92cad2337d85f8d9f01f4eb8c89c76443c
noelevans/sandpit
/wordsnake/recurseproblem.py
444
3.5
4
#!/usr/bin/env python def flattern( inTree ): result = inTree.keys() for elem in inTree.values(): elemValues = flattern( elem ) result.extend( elemValues ) return result print flattern( {'ciao':{'giraffe':{}}} ) print flattern( { 'hi': { 'ciao': { 'giraffe': {} } }, ...
a28b69c200ec094afbd9e1c3fd0cce47d47ddf77
ezequielbrilhantedev/curso_python_cod3r
/list_comprehension/comprehension_v1.py
178
3.75
4
# [ expressão for item in list ] dobros = [i * 2 for i in range(10)] print(dobros) # list "comum" dobros = [] for item in range(10): dobros.append(item * 2) print(dobros)
6f560a2089d58fd99719a20eade4ba9ba95ada73
sumitpdeshmukh/DataAnalysisWithPython
/Assignment 3/py files/Q2_Part_2.py
1,439
3.53125
4
# coding: utf-8 # In[1]: import pandas as pd import os df = pd.read_csv("Data/employee_compensation.csv") # In[2]: # Filtering records containing Calendar only df = df[df['Year Type'] == 'Calendar'] # In[3]: # Keeping only required columns in this part df = pd.concat([df['Job Family'], df['Employee Identifier...
5684b65bffc0298d0e4cad5fceba57c9e6880308
lhcbranco/Problemas-URI-Online-Judge-Iniciante
/1160.py
468
3.640625
4
if __name__=="__main__": o=int(raw_input()) for i in range(0,o): anos=0 a,b,c,d=raw_input().split() a=int(a) b=int(b) c=float(c) d=float(d) while(a<=b): a+=round(((a/100)*c)) b+=round(((b/100)*d)) anos+=1...
83a8fc34167403d5657d8f8999b97e441ce12746
lhcbranco/Problemas-URI-Online-Judge-Iniciante
/1040.py
693
3.8125
4
if __name__ == "__main__": a,b,c,d = raw_input().split() a=float(a) b=float(b) c=float(c) d=float(d) e=((a*2)+(b*3)+(c*4)+d)/10 if e<5: print "Media: %.1f" % e print "Aluno reprovado." elif e>7: print "Media: %.1f" % e print "Aluno aprovad...
1b06463ea17ed1d3644910611895179f6450464c
lhcbranco/Problemas-URI-Online-Judge-Iniciante
/1118.py
926
3.921875
4
def entradas(): while True: a=float(raw_input()) if a<0 or a>10: print "nota invalida" continue else: break while True: b=float(raw_input()) if b<0 or b>10: print "nota invalida" continue els...
d563512c0ecd378dc49dbf923d4d6075c9a2fd44
lhcbranco/Problemas-URI-Online-Judge-Iniciante
/1048.py
941
3.8125
4
if __name__=="__main__": a=float(raw_input()) if a>=0 and a<=400.00: print "Novo salario: %.2f" % (a+(a/100)*15) print "Reajuste ganho: %.2f" %((a/100)*15) print "Em percentual: 15 %" elif a>=400.01 and a<=800.00: print "Novo salario: %.2f" % (a+(a/100)*12) pr...
816e10969060a9a76311bac894499276e2d45238
kohn1001/CrackingTheCode
/compress_str.py
543
3.671875
4
from collections import Counter def compress(str_to_compress): # hist = dict((c, str_to_compress.count(c)) for c in str_to_compress) #creating histogram = dicitionary for each character we hold # the number of occurrences (the below is exactly as the above occurrences = Counter(str_to_compress) lst = sorte...
096f487f392b7f7c1b4c7b69b93bed281be7230e
smartpraveen/python-programming
/beginner/alphabet or not.py
198
4.1875
4
flag = 1 while(flag==1): ch=input("enter the character:") if (ch>="a" or ch>="A") and (ch<="z" or ch<="Z"): print("Alphabet") else: print("Not Alphabet") flag =1
2ca885dc7068a0392aa811fb608981113873fdeb
smartpraveen/python-programming
/natural numbers.py
125
3.90625
4
a=5 if a<0: print("enter the number") else: g=0 while(a>0): g+=a a=a-1 print("the sum is",g)
6ba03485a3507321fc7f407c4de89489ecc819e5
brahim024/LinkedList-1
/main.py
562
3.984375
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def printList(self): temp=self.head while temp: print(temp.data) temp=temp.next if __name__ =='__main__': llist=LinkedList() llist.head=Node(1) second=Node...
9d8d92fc2e55c20249dd984394faac14af74064e
TusharKanjariya/python-practicles
/8.py
252
4.15625
4
str1 = input("enter string") str2 = input("enter string") if len(str1) != len(str2): print("Length Not Equal") print(tuple(zip(str1, str2))) for x, y in zip(str1, str2): if x != y: print("Not Equal") else: print("Equal")
5b0d75ecbaebe98998a91200d2cb95d667a7d8d6
dhobson21/python-practice
/practice.py
1,794
4.1875
4
# 11/19/19-------------------------------------------------------------------------------- """Jaden Smith, the son of Will Smith, is the star of films such as The Karate Kid (2010) and After Earth (2013). Jaden is also known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known ...
be84c9b8539564845868ee6130bbe5d2d2d90071
Frantz680/P3_MacGyver
/frontend/graphic.py
7,070
3.796875
4
""" This class allows you to place images and objects randomly """ from random import randint from backend.init_pygame import pygame, window from backend.constants import CASE_L, CASE_H, \ WINDOW_L, WINDOW_H, POSITION_PIXEL_RECEPTION, WALL, \ GUARDIAN, STARTING, NEEDLE, SYRINGE, ETHER, FREE, \ POSITION_PI...
3f6e0eb93c6644e668473e01eddcce1806fe9741
syfiawoo/Lab_Python_02
/Lab03_2.py
312
4.09375
4
number=input("Enter number to send: ") num_copy=number new_num=0 i=0 reverse=0 while num_copy>0: digit=num_copy%10 new_num=((digit+7)%10)*(10**i)+ new_num num_copy=num_copy/10 reverse=(reverse*10)+new_num/(10**i) i=i+1 print "Encryption process:",number,"==>",new_num,"==>", reverse