blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
641bcff1d29d729c02dd635d00a5147dcdd09b09 | junyi1997/TQC_Python | /New code/class2/PYA201.py | 132 | 4.25 | 4 | # -*- coding: utf-8 -*-
a=int(input())
if a % 2 == 0:
print(a,"is an even number.")
else:
print(a,"is not an even number.")
|
f7f087df978a4ae9689f0f9fdc168eca63b27827 | junyi1997/TQC_Python | /New code/class5/PYA507.py | 570 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def compute():
num=int(input())
if num == 1:
print("Not Prime")
elif num == 2:
print("Prime")
elif num < 0:
print("Not Prime")
elif (num-1)%2==0:
print("Prime")
else:
print("Not Prime")
co... |
6e2bd284d218a64c2fb0dcf76fb54059c1adde78 | junyi1997/TQC_Python | /New code/class5/PYA508.py | 247 | 3.625 | 4 | # -*- coding: utf-8 -*-
def compute():
a=input()
c=a.split(",")
x=int(c[0])
y=int(c[1])
f=min(x,y)
j=0
for i in range(1,f):
if (x % i == 0) and (y % i == 0):
j=i
print(j)
compute() |
47cfc7c67fa826ec9c14ddd64c649c2d0ce7068b | junyi1997/TQC_Python | /New code/class1/PYA104.py | 189 | 4.03125 | 4 | # -*- coding: utf-8 -*-
import math
r=eval(input())
a=r*r*math.pi
Per=2*math.pi*r
print("Radius = {:.2f}".format(r))
print("Perimeter = {:.2f}".format(Per))
print("Area = {:.2f}".format(a)) |
dbd8fd8e4a12e01a76879e339d906b303e54f51e | junyi1997/TQC_Python | /5.第五類/PYD503.py | 226 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:14:48 2018
@author: user
連加計算
"""
def compute(a,b):
sum=0
for i in range(a,b+1):
sum+=i
print(sum)
a=int(input())
b=int(input())
compute(a,b) |
34c86b7d39e91a5d1ef1be8acf95ad1a931f7978 | junyi1997/TQC_Python | /New code/class1/PYA107.py | 884 | 3.625 | 4 | # -*- coding: utf-8 -*-
#a=[]
#for i in range(5):
# a.append(eval(input()))
#
#sum=0.0
#for j in range(5):
# sum=sum+a[j]
#aver=sum/len(a)
#print(a[0],a[1],a[2],a[3],a[4])
#print("Sum =",sum)
#print("Average =",aver)
a=eval(input())
b=eval(input())
c=eval(input())
d=eval(input())
e=eval(input())
sum=a+b+c+d+e
av... |
b250cd826d2aa5bf307c8397318b6a242af3ba8a | stzstzstzaa/isdhw | /01/main.py.py | 133 | 3.546875 | 4 | for i in range(9,0,-1):
for j in range(i,0,-1):
print(j,"*",i,"=",i*j," ",'\t',end="")
print(end='\n')
|
6a7b513bd5aab6929fde4b6141f9a4fa89bdabfc | Rameshtech17/Python_Assignment | /1.py | 447 | 4.21875 | 4 | """
1.Printing Star sequence (take n=4). The Program should be able to print for any number (n - 5,6,7, etc..)
* * * *
* * *
* *
*
"""
i = int(input("Enter The i Value:"));
n = 1
for j in range(i, 0, -1):
for l in range(1, n, 1):
print(" ", end="")
for k in range(j):
print(" *", end="")... |
06f5975da29b11d7643e7eabb1bda582379260ba | WuLC/show-me-the-code | /0004/count_words.py | 1,018 | 4.4375 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2016-04-27 22:37:47
# @Last modified by: WuLC
# @Last Modified time: 2016-04-28 09:04:33
# @Email: liangchaowu5@gmail.com
# @Function: count the words in a English File
import re
import os
def count_words(file_path):
"""count the number of occurance for each w... |
8ac8a69080272b4592eb88ec2f4639946d813ef1 | adolbashian/MTEC2280 | /hello.py | 831 | 3.953125 | 4 | var = 1
var1 = "hello"
var2 = "1"
var3 = 2
#print(hello)
print ("hello world")
print(var - var3)
print(var * var3)
print(var / var3)
print(var + var3)
print("HELLO")
print("World")
print(type(var))
print(type(var1))
print(type(var4))
print(type(var5))
# adding integer and float
# 1 + 2.0
print(var1 + var... |
4f637a9953f0000f1e3b84b8b49a1e6ee7272366 | bfyxzls/planet | /教程/lesson1.py | 162 | 3.65625 | 4 | a=1
b="hello"
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print ("dict['Age']: ", dict['Age'])
arr=[1,2,3,5]
set_a={"a","b","c","d"}
tuple_a=(1,1)
|
57f82990bc34ae02d2e0287af69f3f3d6db32d6a | RRFHOUDEN/competitive-programming | /AtCoder/ABC155B.py | 280 | 3.609375 | 4 | n = int(input())
a = list(map(int, input().split()))
ans = "APPROVED"
for i in a:
if i % 2 == 0:
if i % 3 == 0 or i % 5 == 0:
continue
else:
ans = "DENIED"
break
if ans == "DENIED":
break
print(ans) |
f896a626bf6c55faccef38343190f5c4b5b1aba5 | RRFHOUDEN/competitive-programming | /LeetCode/200.py | 1,289 | 3.53125 | 4 | while 1:
def numIslands(grid):
cnt = 0
check = 1
if len(grid) == 0:
return 0
for i in range(len(grid)):
grid[i] = ["0"] + list(grid[i]) + ["0"]
grid = [["0" for _ in range(len(grid[0]))]] + grid + [["0" for _ in range(len(grid[0]))]]
d... |
a49aedb5f7d5b1ac3de3860d3a081fab9791c5d3 | RRFHOUDEN/competitive-programming | /AtCoder/pp2020C.py | 169 | 3.515625 | 4 | import fractions
a, b, c = map(int, input().split())
if (c - a - b) < 0:
print("No")
elif 4 * a * b < (c - a - b) ** 2:
print("Yes")
else:
print("No") |
a0d02695e621fb03f8894f82d3a33adc214cd90f | RRFHOUDEN/competitive-programming | /AtCoder/asdfadf.py | 340 | 3.671875 | 4 | s = list(input())
cnt = 0
for i in range(len(s) - 2):
if s[i:i + 3] == ["A", "B", "C"]:
s[i:i + 3] = ["B", "C", "A"]
cnt += 1
#print(i)
for i in range(len(s) - 1, 1, -1):
if s[i - 2:i + 1] == ["A", "B", "C"]:
s[i - 2:i + 1] = ["B", "C", "A"]
cnt += 1
#print(i... |
d1a2cae03a70155cc72a4428853c14eef55411c4 | omervered0708/HW2 | /data.py | 1,639 | 3.859375 | 4 | import pandas
class Data:
def __init__(self, path):
"""
the function loads the data from the csv file
:param path: the path to the csv file
:return: none
"""
df = pandas.read_csv(path)
self.data = df.to_dict(orient="list")
def get_all_districts(self):... |
e0c023194d2810bee6c71052f5e3c9a553129ca0 | seriouspig/weekend_hw_rps_20210312 | /app/models/game.py | 1,131 | 3.5 | 4 | from app.models.player import *
class Game():
def __init__(self, name, choice):
self.player1 = player1
self.player2 = player2
def game_result(player1, player2):
if player1.choice == player2.choice:
return "Draw", "draw"
elif player1.choice == "rock":
if... |
30de4cbc160806eb75f943a2dbb1e0393723f18d | AlexKryshtop/OptimizationMethods | /secant_method.py | 2,326 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
def plotter(func, a, b, root):
arg = np.linspace(a, b)
values = [func(x) for x in arg]
plt.plot(arg, values, label='f(x)')
plt.plot(arg, np.zeros(50), label='x = 0')
plt.scatter(root, func(root), linewidths=5, label='root')
plt.xla... |
1e4cfe09b8eacf69b2dc503064aeab0528132616 | rajamong/in-class-activity-unittest-pytest | /wordcountunittest.py | 801 | 3.828125 | 4 | # imports unittest functionality
import unittest
# imports wordcount1 class from wordcount1 program
from wordcount1 import wordcount1
class testCase(unittest.TestCase):
def setUp(self):
self.wordcount = wordcount1()
# tests the word counting functionality with a string input
def test1(se... |
ef51d239d1f10543d3c915e4029fe5d053fc798c | raulgniubo/snake_game | /snake_game_PyCharm_Project/food.py | 646 | 3.859375 | 4 |
from turtle import Turtle
import random
COLORS = ["blue", "red", "yellow", "purple"]
SHAPE = "turtle"
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape(SHAPE)
self.penup()
self.shapesize(stretch_len=0.8, stretch_wid=0.8)
self.set_random_color()
... |
bec0c47dad43baa1d8fbdc5948567d51e7047b95 | dedededede/demo | /1116-打印零与奇偶数.py | 1,167 | 3.84375 | 4 | import threading
class ZeroEvenOdd:
def __init__(self, n):
self.n = n + 1
self.Zero = threading.Semaphore(1)
self.Even = threading.Semaphore(0)
self.Odd = threading.Semaphore(0)
# printNumber(x) outputs "x", where x is an integer.
def zero(self, printNumber):
for i... |
c57a66abcb8e76fb9d031563c64837d372eafe72 | dedededede/demo | /9. Palindrome Number.py | 783 | 3.546875 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x < 10:
return True
length = len(str(x))
if length == 1 or length == 0:
return True
return self... |
d15abf529587a535a37525f3170a5a41a6b2c8df | ShaikHakeemSabirMusheera/program | /exp_add.py | 333 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
n=10
x=[]
for i in range(n):
a=np.exp(i)
x.append(a)
print(x)
y=[]
for i in range(n):
b=np.exp(i)
y.append(b)
print(y)
z=[]
for i in range(n):
s=x[i]*y[i]
z.append(s)
print(z)
plt.subplot(311)
plt.plot(x)
plt.subplot(312)
plt.plot(y)
plt.subplot(313)
plt.plot(z)
... |
822cc122962b6dd35f2278e801c639a74fae826a | laveesingh/Competitive-Programming | /spoj/classicals/archive/JAVAC.py | 1,261 | 3.734375 | 4 | import sys
def isCap(a):
for s in a:
if s.isupper():
return True
return False
def sp(a):
if a[0].isdigit():
return True
if a[0] == "_" or a[-1] == "_":
return True
for i in xrange(len(a)):
if not (a[i].isalpha() or a[i].isdigit() or a[i] == "_"):
return True
return False
def isError(a):
if sp(a)... |
3a7644bf2927f81d7df510f16d022898e2b0b502 | laveesingh/Competitive-Programming | /spoj/classicals/archive/IITKWPCD.py | 359 | 3.640625 | 4 | from itertools import combinations
from math import sqrt
def area(a, b, c):
s = (a+b+c)/2.0
areasquare = s*(s-a)*(s-b)*(s-c)
area = sqrt(areasquare)
return area
def area_sum(a):
assert len(a)%3 == 0
return sum([area(*a[i:i+3]) for i in xrange(0,len(a),3)])
def solve():
n=input()
a = map(int, raw_input().sp... |
9d2028776b9ffdbe3d3f2c9b004105d5c78e0341 | laveesingh/Competitive-Programming | /hackerrank/contests/programming-camp-smvdu/baahubali-and-water-jars.py | 202 | 3.546875 | 4 | from fractions import gcd
def solve():
a, b, c = map(int, raw_input().split())
print "YES" if ((c <= a or c <= b) and c%gcd(a, b) == 0) else "NO"
for _ in xrange(input()):
solve()
|
7f63cf920183e5f2c386782882e4115fb6061c91 | laveesingh/Competitive-Programming | /codeforces/problems/832/b.py | 645 | 3.640625 | 4 |
def match(pat, txt):
diff = len(txt) - len(pat)
if diff < -1:
return False
pat = pat.replace('*', '#' * (diff+1))
if len(pat) != len(txt):
return False
for i in xrange(len(pat)):
if pat[i] == '?':
if txt[i] not in goodset:
return False
eli... |
69f6267cef42fdcd3fed14fcb07329d07ff908e6 | laveesingh/Competitive-Programming | /codechef/contests/SNCKPB17/SNDISCUS.py | 1,263 | 3.515625 | 4 |
class Snake:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def horizontal(self):
return self.y1 == self.y2
def vertical(self):
return self.x1 == self.x2
def dist(self, x, y):
if self.horizontal():
... |
305deb391f931b07c13f640edca7902241af8f1d | laveesingh/Competitive-Programming | /hackerrank/practice/archive/segmented_sieve.py | 1,206 | 3.65625 | 4 | from math import sqrt
def primes_upto_sqrt(n):
l = int(sqrt(n)+1.5)
primes = [0]*l
primes[0] = 1
primes[1] = 1
for i in xrange(4, l, 2): primes[i] = 1
for i in xrange(3, int(sqrt(l)+1.5), 2):
if not primes[i]:
for j in xrange(i*i, l, i):
primes[j] = 1
return [i for i in xrange(len(primes)) if not prime... |
454d65dad7a9d875a970b506de7ea0dd08a49fff | laveesingh/Competitive-Programming | /spoj/classicals/archive/PT07Z.py | 648 | 3.609375 | 4 | from collections import defaultdict
tree = defaultdict(list)
depths = defaultdict(list)
def set_depths(node=1):
if (depths[node]): return
if len(children(node)) == 0:
depths[node].append(0)
else:
for s in children(node):
set_depths(s)
depths[node].append(max(depths[s])+1)
def children(node):
if tree.g... |
8e258bd3d918c3b11a22ffba36f160d99a6939fd | laveesingh/Competitive-Programming | /hackerrank/practice/archive/sherlock_and_the_beast.py | 288 | 3.609375 | 4 | for _ in range(input()):
n = input()
count1 = n
count2 = 0
while count1 >= 0:
if count1 % 3 == 0:
break
else:
count2 += 5
count1 -= 5
if count1 < 0:
print "-1"
else:
print count1*'5'+count2*'3' |
47cb29c724b1938c8f28eeacfa28f5b5315bb459 | shayde-rnd/cluster_and_classify | /cluster_k_means.py | 4,827 | 3.953125 | 4 | """
TF-IDF vector is a numeric representation of text - a vector in the size of the curpus where for each word
we have a weight: 1/(#number of occurrence of the word in the text) - each index in the vector represent a specific word
for instance, the following text:
"Hi there, yes yes yes there"
under the assumption... |
1f5e9f114866090845f53984d018164cdf02db5a | HussainAther/neuroscience | /neural/kinematics.py | 2,459 | 3.546875 | 4 | import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
"""
In neuroscience, we use kinetmatic transformations to determine sensory-motor questions
of how the nervous system can choose a single configuartion of body parts (such as arms and legs) in space.
We can use mathematical methods... |
51f74e01197a2adb69cc8fb0b6aa1d139541ef88 | HussainAther/neuroscience | /spike/sta.py | 486 | 3.5 | 4 | import matplotlib.pyplot as plt
import numpy as np
def compute(stim, rho, steps):
"""
Compute the spike-triggered average (STA) from a stimulus and spike-train.
stim is the stimulus time-series, rho is the spike-train time series, and
steps is the number of timesteps.
"""
sta = np.zeros(steps)... |
5e1729900cdf47de591d95a7e14c84994602d62c | HussainAther/neuroscience | /spike/euclidian.py | 1,511 | 3.609375 | 4 | """
Euclidian (euclidean) spike classifier. To quantify how well a spike train discriminates
stimulus patterns, one first needs to estimate the optimal stimulus feature
for eliciting spikes. Here, we describe the application of a Euclidian pattern
classifier to this problem. First, the spike train x and stimulus s a... |
0e5bad08cf4c82560554efe457136c2cdadc98fb | HussainAther/neuroscience | /synaptic/plasticity.py | 3,550 | 3.671875 | 4 | import numpy as np
from sklearn import make_blobs
"""
Synaptic plasticity with Hebbian Learning. Using neurons of the brain as processing units
using cable theory as extensions, we can simulate models of neurons firing using action potentials
that deliber chemical siganls (neurotransmitters) as ion channels open and ... |
385be9b042cbda67ec96523871a30bec0d60a2f5 | drbernal47/python-challenge | /PyBank/main.py | 3,379 | 4.0625 | 4 | import os
import csv
# Path to collect data from the Resources folder
bank_data_csv = os.path.join('Resources', '02-Homework_03-Python_Instructions_PyBank_Resources_budget_data.csv')
# Read in the CSV file
with open(bank_data_csv, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, de... |
d2a6266061b9b19e1c305d753e9a950d8a231e83 | zhuojunq/leetcode | /001.TwoSum/Solution.py | 440 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 4 13:02:16 2018
@author: zhuoj
"""
#Python solution using hash
class Solution:
# @return a tuple, (index1, index2)
# 8:42
def twoSum(self, num, target):
map = {}
for i in range(len(num)):
if num[i] not in map:
map... |
7440b8085cf097982f939ed2a3f7bab9a5acd031 | jart/cosmopolitan | /third_party/python/Tools/demo/markov.py | 3,685 | 3.53125 | 4 | #!/usr/bin/env python3
"""
Markov chain simulation of words or characters.
"""
class Markov:
def __init__(self, histsize, choice):
self.histsize = histsize
self.choice = choice
self.trans = {}
def add(self, state, next):
self.trans.setdefault(state, []).append(next)
def p... |
6df6b68dde62778862362f0805b84cdee235872e | jart/cosmopolitan | /third_party/python/Lib/turtledemo/lindenmayer.py | 2,427 | 4.40625 | 4 | #!/usr/bin/env python3
""" turtle-example-suite:
xtx_lindenmayer_indian.py
Each morning women in Tamil Nadu, in southern
India, place designs, created by using rice
flour and known as kolam on the thresholds of
their homes.
These can be described by Lindenmayer systems,
which can easily be implemented ... |
f925021ec03938fb4269d5e310992a9f1ea83353 | jart/cosmopolitan | /third_party/python/Lib/pyclbr.py | 13,558 | 3.859375 | 4 | """Parse a Python module and describe its classes and methods.
Parse enough of a Python file to recognize imports and class and
method definitions, and to find out the superclasses of a class.
The interface consists of a single function:
readmodule_ex(module [, path])
where module is the name of a Python modu... |
39173d3b73a3ceac0f5c3f90ea0d0f5cb6df5ebd | jart/cosmopolitan | /third_party/python/Tools/demo/vector.py | 1,452 | 4.5 | 4 | #!/usr/bin/env python3
"""
A demonstration of classes and their special methods in Python.
"""
class Vec:
"""A simple vector class.
Instances of the Vec class can be constructed from numbers
>>> a = Vec(1, 2, 3)
>>> b = Vec(3, 2, 1)
added
>>> a + b
Vec(4, 4, 4)
subtracted
>>> a... |
efcd72eeab3eeb6503e8f411f2f97f8ca312e9ca | jart/cosmopolitan | /third_party/python/Lib/idlelib/redirector.py | 6,875 | 4.125 | 4 | from tkinter import TclError
class WidgetRedirector:
"""Support for redirecting arbitrary widget subcommands.
Some Tk operations don't normally pass through tkinter. For example, if a
character is inserted into a Text widget by pressing a key, a default Tk
binding to the widget's 'insert' operation i... |
f26335f0e36c8f1eea42249caa29b4559059fac0 | jart/cosmopolitan | /third_party/python/Lib/xml/sax/_exceptions.py | 4,699 | 3.796875 | 4 | """Different kinds of SAX Exceptions"""
# ===== SAXEXCEPTION =====
class SAXException(Exception):
"""Encapsulate an XML error or warning. This class can contain
basic error or warning information from either the XML parser or
the application: you can subclass it to provide additional
functionality, or... |
c8f97dbb5bd108a337ecdad79239e3bf7bd378c8 | TanishhBhajnik/ChooseYourAdventure | /Choose your adventre/main.py | 2,187 | 4.28125 | 4 | # This is an choose adventure game! You will be given in a certain situation you have to find your way out alive!
import time
def main():
#Asking user's name
name = input("Enter your name: ")
print(f"Welcome {name} to this adventure!")
time.sleep(1)
print("WARNING! This game is very dangerou... |
83a9777990115394dff991dc4e5059b9b141bc40 | Swordling1/Advent-of-Code | /Day 2/Day 2.py | 1,365 | 3.640625 | 4 | from pathlib import Path
raw = Path('Day 2\input.txt').read_text()
raw = raw.strip()
raw = raw.split("\n")
length = len(raw)
for i in range(length): raw[i] = raw[i].split(":")
for i in range(length): raw[i][1] = raw[i][1].strip()
raw2 = []
for i in range(length): raw2.append(raw[i][0].split(" "))
passwords = []
fo... |
cb5283d270664b09a9ae0478b1ea1b1107cd66a2 | ashishmauryagithub/Cracking-the-coding-interviews | /E-15 prints all fibonacci but stores previously calculated value in arr.py | 358 | 4.09375 | 4 | # Time complexity: O(n) why ? Because of memoization technique
def fib(n,memo):
if n<=0: return 0
if n==1: return 1
elif memo[n]>0: return memo[n]
memo[n] = fib(n-1,memo)+fib(n-2,memo)
# print(memo,memo[n])
return memo[n]
def allfib(n):
memo = [0]*(n+1)
for i in range(1,n+1):
p... |
c9a7cc6dda4ac63bcb35e54bc68a6412bc560843 | lgutie16/Python | /Search_Algorithms/linear-search.py | 271 | 3.515625 | 4 | #O(n)
def linear_search(x,y):
n = len( x )
iaux = 0
position = 0
for i in x:
if i == y:
position = iaux
iaux = iaux + 1
return position
def main():
arr = [int(i) for i in raw_input().split()]
trgt =int( input())
print linear_search(arr, trgt)
main() |
1ba476d8cd9e65642bb18ce633d594fd05f95215 | kNosek1618/x_o_game | /test2.py | 430 | 3.75 | 4 |
x = 1
y = 2
round = 1
while round < 10:
if x == 1 or y == 0:
if x == 2 or y == 2:
while round % 2 == 0:
round += 1
print("player1")
while round % 2 != 0:
round += 1
print("player2")
else:
print("pl... |
8906f446085853237ea2655fae28283ac70ec099 | Rohithv07/python-oops | /abstractbaseclass.py | 427 | 3.984375 | 4 | import abc,six
from abc import ABCMeta,abstractmethod
@six.add_metaclass(abc.ABCMeta)
class Shape():
@abc.abstractmethod
def area(self):
return 0 #abstract cant have any object
class Square:
side=4
def area(self):
print(self.side**2)
class Rect:
width=5
length=10
def... |
a4fc866ee67b4520ab379b35d67d5556ba41f538 | Rohithv07/python-oops | /multilevelinheritance.py | 303 | 3.984375 | 4 | class Animal:
name="tiger"
class Species(Animal):
family="cat"
class Place(Species):
def __init__(self):
if self.name is "tiger" and self.family is "cat":
print("multilevel inhertance example is confirmed using {} and {}".format(self.name,self.family))
place=Place()
|
9540de804c110866377c61287a32d9a4073f5931 | kazuohirai/HackBulgaria | /Programming101/Week0/Monday/nanExpand.py | 500 | 3.828125 | 4 | from countSubstrings import count_substrings
def nan_expand(times):
nan = '"'
if times == 0:
return '""'
elif times == 1:
return '"Not a NaN"'
else:
for i in range(0, times):
nan += "Not a "
nan += 'NaN"'
return nan
def iterations_of_nan_expand(exp... |
b15146bbd298a310ddc80e72a62ee946a5a666ca | Anubharil/Supreme | /mycalc.py | 3,376 | 3.875 | 4 | from Tkinter import *
from math import*
import math
root=Tk()
root.title("MY CALC")
e=Entry(root,width=16,font='Arial 30 bold',bd=7,bg='grey',justify='right')
e.grid(row=0,column=0,columnspan=4)
def add_entry(x):
e.insert(16,x)
def result(y):
e.delete(0,16)
e.insert(16,y)
def clear():
e.del... |
ad3ede3e87f9f5707a865e4992c0b1e364a4f792 | visr2941/Communication_DSP | /Communication_Lab_Git/Lab1/sine100.py | 1,403 | 3.78125 | 4 | # File: sine100.py
# Ask for sampling frequency fs and then generates and plots
# differential and integral value of sine wave and rectangular wave.
#/usr/bin/python3
from pylab import *
#fs = float(input("Enter the sampling frequency: "))
fm = 100 # frequency of the signal
tlen = 0.05 # time for 5 period of... |
aac79e4fd8cb144599aaa8b4e21ab3325a69194a | fockbomber/hacktoberfest | /DES3.py | 486 | 3.59375 | 4 |
#DES3 CIPHER
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad,unpad
plain_text = b"12345678"
key = b"3498723894723498"
#encryption part
des3_object = DES3.new(key,DES3.MODE_ECB)
ct = des3_object.encrypt(pad(plain_text,DES3.block_size))
print("Encrypted text is : ",ct)
print("Key Size: ",len(key... |
c439c8c270e7faa2f2c6086fdf0ffe4630122db3 | JasonQiu21/brute_force_zip | /brute_unzip.py | 1,141 | 3.703125 | 4 | import zipfile
import sys
import os
cwd = os.getcwd()
#get zip file
try:
Zip = input("Zip file location: ")
except FileNotFoundError:
print("Error: can't open zip.")
sys.exit()
if Zip.startswith("/"):
pass
else:
Zip = cwd + "/" + Zip
try:
myZip = zipfile.ZipFile(Zip)
except zipfile.BadZip... |
3b519197e388e67b2468501640e60ca97c443bd0 | aldoivan999/Equipo1Act.1 | /Crud/Personas.py | 285 | 3.734375 | 4 | class Personas:
id = 0
nombre = ""
direccion = ""
def __init__(self, id, nombre, direccion):
self.id = id
self.nombre = nombre
self.direccion = direccion
def __str__(self):
return "Id: {} Nombre: {}".format(self.id, self.nombre)
|
f6bd56c49a2f7468cc0476768cf8ecc7d633699e | algorithm003/algorithm | /Week_04/id_17/LeetCode_64_17.py | 853 | 3.71875 | 4 | # 64. 最小路径和
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
dp = []
for i in range(len(grid)):
dp.append([0 for i in range(len(gr... |
725ee3f4906eb1c8624b6ae3ae77407e78ae2e71 | algorithm003/algorithm | /Week_01/id_2/LeetCode_26_2.py | 770 | 3.8125 | 4 | from typing import List
"""
@author: Merlin 2019.06.23
26.Remove Duplicates from Sorted Array
思路: 因为数组本身是排好序的,并且要求是原地算法(即空间复杂度为O(1))
1.用快慢指针,i为慢指针,指向元素重复项的第一个元素。j遍历每个元素。
2.当遇到nums[j] != nums[i],跳过重复项的运行已经结束,因此把nums[j]的值赋给nums[i+1]
3.重复相同过程直到j到达数组末尾
time: O(n) space: O(1)
"""
class Solution... |
60a6ab77746ef011e0315dbfd18c663d84d8241a | algorithm003/algorithm | /Week_04/id_27/LeetCode_212_27.py | 1,503 | 3.796875 | 4 | import collections
class TrieNode:
def __init__(self):
self.children = collections.defaultdict(TrieNode)
self.isEndingChar = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for i in word:
node = node.... |
578ecfa7f5dab1254a723859d2ebcdc7b924db78 | algorithm003/algorithm | /Week_02/id_26/LeetCode_98_26.py | 605 | 3.734375 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
def traverseBetweenSpan(root: TreeNode, lowLimit = float('-inf'), upperLimit = float('inf')):
if not root:
return True
... |
9468cf4c3fba292114dd46adf327c56dbfde4ed3 | algorithm003/algorithm | /Week_04/id_27/LeetCode_720_27.py | 547 | 4.09375 | 4 | class Solution(object):
def longestWord(self, words):
words.sort()
words_set, longest_word = set(['']), ''
for word in words:
print (word, word[:-1], words_set)
# print ()
if word[:-1] in words_set:
words_set.add(word)
if l... |
0a522be1f7afc07653c832e157810722ee1beff8 | algorithm003/algorithm | /Week_01/id_2/LeetCode_24_2.py | 633 | 3.765625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
@author: Merlin 2019.06.23
24.Swap Nodes In Pairs
思路: 用两个指针不断交换元素,并移动指针到下一组要交换的元素即可
例子: 交换相邻两个节点,1->2->3->4->5,交换后得2->1->4->3->5
time: O(n) space: O(1)
"""
class Solution:
def swapPairs(self, head):
... |
9a9dbfe5c6549fb2f794c7b97ab7cd2fa9eb1982 | algorithm003/algorithm | /Week_04/id_17/LeetCode_198_17.py | 1,394 | 3.640625 | 4 | # 198. 打家劫舍
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def rob(self, nums):
"""
... |
66c24f7df3a36f62439e2416d30cb01a19f1c4c4 | algorithm003/algorithm | /Week_02/id_1/LeetCode_101_01.py | 1,231 | 4 | 4 | # @Author:kilie
# @lc app=leetcode id=101 lang=python3
# [101] Symmetric Tree
# https://leetcode.com/problems/symmetric-tree/description/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
DFS:
构建dfs函数:
... |
00b22e7500b2ce3aef240979425a564d98170a9a | algorithm003/algorithm | /Week_01/id_27/LeetCode_49_27.py | 624 | 3.6875 | 4 | class Solution:
'''
字母异位词分组,也是通过hashMap将拥有同样字母的设为key,将相同字母的单词放入由数组组成的value中
最后返回dict.values组成的数组即可
关键点在于key,这里用了''.join(sorted(st)),就是将单词重新排序后作为一个key
'''
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict = {}
for st in strs:
key = ''.join(sorted(st))... |
88dc839d119ccee11e26a8e56e3c1518fbe5546c | algorithm003/algorithm | /Week_02/id_1/LeetCode_236_01.py | 1,440 | 3.71875 | 4 | # @Author:Kilien
# @lc app=leetcode id=236 lang=python3
# [236] Lowest Common Ancestor of a Binary Tree
# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = N... |
8ae0188e562335c45ac864608fd6d4ae67c62112 | Satak/aoc-2020 | /2/2.py | 1,078 | 3.5625 | 4 | import os
import re
data_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data.txt')
with open(data_file) as f:
data = f.read().strip().split('\n')
def get_min_max(line):
min_count, max_count = re.search(r'^\d+-\d+', line).group(0).split('-')
return int(min_count), int(max_count)
def... |
d17a7fd563199f1dfa6177ab8f396cbeed4a4108 | zhao13233065692/myproject | /day02/1-100.py | 176 | 3.8125 | 4 | if __name__ == '__main__':
st=range(0,101)
for i in st:
i=str(i)
print(i.rjust(3," "),end=" ")
i=int(i)
if i%10==9:
print()
|
ba77877d3117f107265014f28c7a611be2567d2e | zhao13233065692/myproject | /day03/mypr1.py | 745 | 3.609375 | 4 | import random
if __name__ == '__main__':
sts = input("请输入年月日")
st =int(sts)
Y = st//10000
M = st//100%100
D = st%100
print("这是{0}年中的第{1}".format(Y,((M-1)*30+D)))
ss =input("请输入第一人的出生月份")
yy = input("请输入第二人的出生月份")
dd = int(ss)
ff = int(yy)
print(type(dd))
print(type(ff))
if dd % ff==1:
print(... |
40dc143175ff4df3654d794b8a6aeb8198985072 | zhao13233065692/myproject | /day04/myexception5.py | 690 | 3.71875 | 4 | print("输入两个数,计算除法")
print("输入q退出")
while True:
print("\t")
fnum = input("First number:")
if fnum=="q":
break
snum = input("Second number:")
if snum=="q":
break
#捕获异常,如果发生则进入异常的分支代码块
try:
res = int(fnum)/int(snum)
#异常分支代码块
#在代码中处理异常
#注意此处的代码只有一个pass
#表示... |
9825835516edf0031103ba38914784f0dca54b84 | Suiname/grokkingAlgorithms | /recursive_sum.py | 171 | 3.734375 | 4 | def sum(arr):
if len(arr) == 0:
return 0
elif len(arr) == 1:
return arr[0]
else:
return sum(arr[1:]) + arr[0]
test_array = [2,4,6]
print(sum(test_array) |
db2f6b627f6e2d0c8eccd24ab56e81417f130b32 | DillonWard/Jupyter-Worksheet | /fishers-data-reader.py | 4,399 | 3.71875 | 4 | # Read in the CSV Fisher's Iris data set and store it into a numpy array
# Author: Dillonward2017@gmail.com
# Date: 24/10/17
# (1) Adapted from https://matplotlib.org/users/customizing.html
# (2) Adapted from https://stackoverflow.com/questions/332289/how-do-you-change-the-size-of-figures-drawn-with-matplotlib
# (3) Ad... |
84013e12af14a32075bf512ca9da002236b8239f | aaditjain-official/Pythonproject | /functionsbasic.py | 804 | 3.953125 | 4 | #l=[1,2,3,4,5,6,7,8,9]
#m=[10,20,30,40,50,60,70,80,90]
#max_num=max(m)
#min_num=min(m)
#print("The Maximum number in the list : ",max_num)
#print("The Minimum number in the list : ",min_num)
#square = {2: 4, -3: 9, -1: 1, -2: 4}
#print(max(square)) # prints the maximum key
#print(max(square.values())) # pri... |
ad5407bf2dd312e5d764acf2241d66a6837df9a8 | juansedev/holbertonschool-higher_level_programming | /0x0A-python-inheritance/11-square.py | 649 | 4.125 | 4 | #!/usr/bin/python3
""" In this module it create a Class Squere that inherits
from r"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
"""This a class Rectangle"""
def __init__(self, size):
"""Initialize an instance of Square
Arguments:
size: value ... |
9c4cf2cae786f3af20469d1d94f9a99e189e53d4 | juansedev/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 931 | 3.90625 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""[summary]
Args:
unittest ([type]): [description]
"""
def test_empty_list(self):
"""Empty list case"""
self... |
dac3c6a2af214dbbca9b7bd1cf115a43f6f5982c | juansedev/holbertonschool-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 868 | 4.21875 | 4 | #!/usr/bin/python3
""" In this module it create a Class Rectangle"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""This a class Rectangle"""
def __init__(self, width, height):
"""Initialize an instance of Rectangle
Arguments:
width:... |
d668213cc81630a41cf669857149b729c412c456 | juansedev/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 272 | 3.53125 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
new_matriz = [i[:] for i in matrix]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
new_matriz[i][j] = matrix[i][j] ** 2
return new_matriz
|
762bf20e3caba990ea1ac3dd75da5010b4c34356 | juansedev/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,118 | 3.78125 | 4 | #!/usr/bin/python3
"""[summary]
"""
def matrix_divided(matrix, div):
"""[summary]
Arguments:
matrix {[type]} -- [description]
div {[type]} -- [description]
"""
message1 = "matrix must be a matrix (list of lists) of integers/floats"
message2 = "Each row... |
65932a966df6267a13994ce017d1787464a9b13b | ZahirSholgami/Rock-Paper-Or-Scissors-Python | /main.py | 1,210 | 4.21875 | 4 | import random
options = ["Rock", "Paper", "Scissors"]
cpu_score = 0
player_score = 0
while True:
player= input("Rock, Paper or Scissors? To end the game please type in End").capitalize()
cpu = random.choice(options)
##The conditions of the game
if player == cpu:
print("DRAW!")
elif player ... |
08a2d6988dcc420e8b38208fecf4eaf4e8cb060e | adityamangal1/DSA-questions | /puzzles/prac.py | 170 | 4.125 | 4 | def isPower(x, y):
if (x == 1):
return (y == 1)
pow = 1
while (pow < y):
pow = pow * x
return (pow == y)
print(isPower(2, 8))
# pow = 8 |
27ce80214fe66fbc5a024b75ffcd2df8919ed35e | ujasmandavia/mit6.006 | /lecture18/singletarget.py | 1,166 | 4.03125 | 4 | """
Lecture 18: Speeding Up Dijkstra's
Single-Targer Dijkstra's Algorithm
----------------------------------
This program contains an implementation of
Dijkstra's algorithm which halts when it finds
the shortest path to a given destination vertex.
It then returns the path to that vertex from
the source vertex and the c... |
8da113cf203c6829275f7a8c05fe68b0c6a8500f | ujasmandavia/mit6.006 | /lecture03/insertionsort.py | 636 | 4.25 | 4 | """
Lecture 3: Sorting
Insertion Sort
--------------
This program contains two implemenations
of the insertion sort algorithm.
"""
def insertion_sort(L):
"""
Insertion sort implementation
Complexity: O(n ** 2)
"""
for i in range(1, len(L)):
for j in range(0, i):
if L[i - j] < L[i - j - 1]:
... |
48484dd79f05208a01590f2c0997f5f006a3abe8 | ujasmandavia/mit6.006 | /lecture13/bfs.py | 2,101 | 4.125 | 4 | """
Lecture 13: Breadth First Search
--------------------------------
An implementation of BFS on the
binary search tree implemented in
lecture 5
An implementation of the BFS demonstrated
in the lecture
"""
from collections import deque
def add_graph_node(adjacency_list, val):
"""
Add a node to a graph, adjac... |
f5ae7c62ddeb6f816ea76fe21ed8ba459d16b99e | ujasmandavia/mit6.006 | /lecture08/hashtable.py | 3,826 | 4.25 | 4 | """
Lecture 8: Hashing
------------------
This program contains an implementation
of a hash table which uses chaining to
handle collisions.
"""
from random import randint
def is_prime(n):
"""
Miller-Rabin primality test
for n < 2 ** 64
"""
test_vals = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
if n i... |
958bb7e31ae69861412f94d968986f441ddee61c | bpgallagher/inforet | /sheet-13/viterbi.py | 7,307 | 3.546875 | 4 | # Copyright 2018, University of Freiburg,
# Chair of Algorithms and Data Structures.
# Author: Claudius Korzen <korzen@cs.uni-freiburg.de>.
import sys
import numpy as np
class NamedEntityRecognition:
"""
A simple Named Entity Recognition engine using the Viterbi algorithm.
"""
def __init__(self):... |
20fe6b0a64f7fee093cd6dfacb6426f61bd4f569 | pablomiralles22/minimize-afd | /jflap/Transiciones.py | 1,844 | 3.640625 | 4 | '''
Created on 11 may. 2018
@author: Adri
'''
class Transiciones(object):
'''
Clase que contiene las transiciones de cada estado
Atributos privados
------------------
transiciones: dict
Diccionario con las transiciones de salida desde el estado
La clave es el sim... |
f287bf253ddbc5c639013bb3a9905aadae960eda | FudgeMunkey/adventofcode-2020 | /src/day-16/solution-2.py | 2,792 | 3.65625 | 4 | # It doesn't work, I'm not sure why not..
def read_input():
# Read input
f = open("puzzle_input.txt", "r")
raw_data = f.read().split('\n')[:-1]
clean_data = []
# Extract fields
clean_data = raw_data
return clean_data
def extract_fields(input_data):
fields = {}
for row in input_d... |
28ba3ad50364f6d7819b751e310ff686aca11e79 | FudgeMunkey/adventofcode-2020 | /src/day-03/solution-2.py | 864 | 3.9375 | 4 | def read_input():
# Read input
f = open("puzzle_input.txt", "r")
raw_data = f.readlines()
clean_data = [x[:-1] for x in raw_data] # Remove \n char
return clean_data
def check_slope(right, down):
# Iterate through each row (down)
# Move the index across RIGHT each time (right)
trees =... |
48bb62b347804538529314c1110f610b056af46b | FudgeMunkey/adventofcode-2020 | /src/day-07/solution-1.py | 1,676 | 3.703125 | 4 | def read_input():
# Read input
f = open("puzzle_input.txt", "r")
raw_data = f.read().split('\n')
clean_data = []
# Clean Data
clean_data = raw_data[:-1]
return clean_data
def process_rules(rules):
ret_rules = {}
# Process all of the rules
for i in range(len(rules)):
... |
dd5e40c5bf304e7455ba9e9bf2669e2b8dc98c1a | FudgeMunkey/adventofcode-2020 | /src/day-09/solution-2.py | 758 | 3.5 | 4 | def read_input():
# Read input
f = open("puzzle_input.txt", "r")
raw_data = f.read().split('\n')
clean_data = []
# Clean Data
clean_data = [int(rd) for rd in raw_data[:-1]]
return clean_data
if __name__ == "__main__":
data = read_input()
# Solve problem
target = 1639024365
... |
fbb429c09a7fdac0cd88dd3cb897fe0e63cc664f | thoros2018/Python_Challenge-Homework-3 | /PyBank/main.py | 1,311 | 3.546875 | 4 | import os
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline='') as budgetdata:
csvreader = csv.reader(budgetdata, delimiter=',')
csv_header = next(budgetdata)
#assign lists:
TotalList1 = []
TotalList2 = []
change = []
changem... |
3e9e9119550d83ea72882d6be7b0139597fdc7de | toticavalcanti/uri_online_judge | /1169_trigo_no_tabuleiro.py | 394 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 24 00:21:26 2018
@author: toti.cavalcanti
"""
n = int(input())
for i in range(n):
board_houses = int(input())
double = [1]
for i in range(1, board_houses):
double.append(double[i - 1] * 2)
total = sum(double)
total_gram = total / 12
tota... |
a5c23009450ffe2f77a8a1fc2d2729eca78274cc | toticavalcanti/uri_online_judge | /1069_diamante_e_areia.py | 426 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 23 13:45:06 2018
@author: toti.cavalcanti
"""
n = int(input())
for i in range(n):
line = input()
if line == '':
continue
op = 0
diamonds = 0
for char in line:
if char == '<':
op += 1
elif char == '>':
i... |
bdcd379a4db4945e3a35dfeb7ab48a04579227c3 | toticavalcanti/uri_online_judge | /1110_jogando_cartas_fora.py | 517 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 23 17:15:55 2018
@author: toti.cavalcanti
"""
while True:
n = int(input())
if n == 0 :
break
remaining = []
for i in range(1,n+1):
remaining.append(i)
discarded = []
while len(remaining) > 1:
discarded.append(remaining.pop... |
bd4db3ec228d266a4ab43cd8fb4a9ecc86f8dafa | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex11/ex11.4.py | 541 | 4 | 4 | #!/usr/bin/env python3
"""
Exercise 11.4.
If you did Exercise 10.7, you already have a function named has_duplicates
that takes a list as a parameter and returns True if there is any object that
appears more than once in the list.
Use a dictionary to write a faster, simpler version of has_duplicates.
Solution: http:/... |
9586d3f11e2f646b0a876a51cf04488135b2f2af | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex9/ex9.7.py | 1,317 | 4.0625 | 4 | #!/usr/bin/env python3
"""
Exercise 9.7.
This question is based on a Puzzler that was broadcast on the radio program
Car Talk (http://www.cartalk.com/content/puzzlers):
Give me a word with three consecutive double letters. I’ll give you a couple of
words that almost qualify, but don’t. For example, the word committee... |
371c1675642f882a2ece6dbe0bc32520b90ceac3 | adwanAK/adwan_python_core | /think_python_solutions/Think-Python-2e/ex6/ex6.5.py | 768 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Exercise 6.5.
The greatest common divisor (GCD) of a and b is the largest number that divides
both of them with no remainder.
One way to find the GCD of two numbers is based on the observation that
if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r).
As a base case, we ... |
048cdde2185c6c62f01b23149156298ff3488673 | adwanAK/adwan_python_core | /solutions/labs_w1_w2/05_Functions_03.py | 824 | 4.09375 | 4 | '''
Write a program with 3 functions. Each function must call
at least one other function and use the return value to do something.
'''
import random
def open_fridge():
is_open = random.choice([True, True, False])
return is_open
def get_ingredient():
if open_fridge():
ingr = random.choice(["but... |
ca3d3a70db4b080af3bd93e96ed3857c98812985 | adwanAK/adwan_python_core | /think_python_solutions/chapter-12/exercise-12.2.py | 992 | 4.125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
exercise-12.2.py
Modify book's code example to tie-break between words of equal length using the "random" module
Created by Terry Bates on 2013-01-29.
Copyright (c) 2013 http://the-awesome-python-blog.posterous.com. All rights reserved.
"""
import cPickle
import random
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.