blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
45a2201a6a7220306492cf1baaf47d68f4595d13 | nicholasrokosz/python-crash-course | /Ch. 4/animals.py | 145 | 3.765625 | 4 | animals = ['parrot', 'raven', 'bald eagle']
for animal in animals:
print(f"A {animal} is a pretty cool bird.")
print("And all of them can fly!") |
da5a646c0a2caecadb60485bf3d02d8c0661960b | nicholasrokosz/python-crash-course | /Ch. 8/user_albums.py | 572 | 4.25 | 4 | def make_album(artist, album, no_of_songs=None):
album_info = {'artist': artist, 'album': album}
if no_of_songs:
album_info['no_of_songs'] = no_of_songs
return album_info
while True:
artist_name = input("Enter the artist's name: ")
album_title = input("Enter the album title: ")
no_of_songs = input("Enter the n... |
d684985ffbb5d2889c1a4449c497b4255f33fba2 | nicholasrokosz/python-crash-course | /Ch. 3/changing_guest_list.py | 825 | 3.90625 | 4 | guests = ['Bertrand Russell', 'Elon Musk', 'Claude Shannon']
print(f"Dear Mr. {guests[0]}, are you available to attend a dinner at my home this weekend?")
print(f"Dear Mr. {guests[1]}, are you available to attend a dinner at my home this weekend?")
print(f"Dear Mr. {guests[2]}, are you available to attend a dinner at ... |
72e6fb8ef93a3874f3fedd4814e264f37a36ff14 | nicholasrokosz/python-crash-course | /Ch. 3/seeing_the_world.py | 381 | 3.75 | 4 | destinations = ['Oslo', 'Edinburgh', 'Copenhagen', 'London', 'Stockholm']
print(destinations)
print(sorted(destinations))
print(destinations)
print(sorted(destinations, reverse=True))
print(destinations)
destinations.reverse()
print(destinations)
destinations.reverse()
print(destinations)
destinations.sort()
print(dest... |
6b492cfcbb3103babf24f542e10168773ef5a2a1 | nicholasrokosz/python-crash-course | /Ch. 2/personal_message.py | 164 | 3.625 | 4 | # Nick Rokosz 06/17/20
# simple program using variables and an f-string
name = "Nick"
message = f"Hello {name},would you like to learn some python today?"
print(message) |
883496ed245b3f4248700a9253e60324a4fdffb3 | nicholasrokosz/python-crash-course | /Ch. 10/cats_and_dogs.py | 218 | 3.5625 | 4 | def read_file(filename):
try:
with open(filename) as f:
content = f.read()
print(content.strip())
except FileNotFoundError:
print(f"We couldn't find {filename}")
read_file('cats.txt')
read_file('dogs.txt') |
120d2294baa8ccfd2155952cf695ee74cd8fade6 | EmreBio/StructureFold | /header/write_file.py | 1,519 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def write_t_file(out_file, a):
with open(out_file, 'w') as h:
if type(a) is list:
for i in range(len(a)):
if type(a[i]) is list:
if len(a[i])>1:
for j in range(le... |
dd2a8c8533a753c3a60df4c438728208300a7ca2 | YashYadav-github/project59 | /Exercise3.py | 608 | 3.953125 | 4 | x = 74
num_of_guesses = 1
print("Welcome to guess the number")
print("Number of guesses is limited to only 6 times: ")
while (num_of_guesses <= 6):
guess_number = int(input("Guess the number :\n"))
if guess_number < 74:
print("Please Increase the number")
elif guess_number > 74:
print("Pleas... |
fa96e104a2fede922275517586cbc44e026ba202 | sirenkov/ising | /ising.py | 2,668 | 3.96875 | 4 | #!/usr/bin/env python
import numpy as np
import math as m
import random
import matplotlib.pyplot as plt
import ising_functions as isf
#FOR 2-D SQUARE LATTICE
#code implementing Metropolis algorithm
#user inputs size (n) and temperature (T)
#code outputs T, M, E, X, C, S at equilibrium
#we have to run export PYTHONPATH... |
d9b5e57a5ae65532d0837b82c0bf624e189a4cc5 | mumarkhan999/UdacityPythonCoursePracticeFiles | /24_class_object.py | 830 | 3.875 | 4 | #self is like this pointer in C ,C# , java
#it is the object itself whose for the method is
#called
class student:
#constructor
#automatically call whenever we create an object of
#the class
#used to initialize the object
#parametraised constructor
def __init__(self,name,roll,age):
... |
e2a6910a80bbaf913eb4bb912a263214caa8267b | mumarkhan999/UdacityPythonCoursePracticeFiles | /19_file_rename_remove.py | 279 | 3.8125 | 4 | #before running this code make "b.txt" file and "a.txt" file
#in files folder as it will be deleted in this code
#renaming or removing a file
#os.rename ( oldName , newName)
#os.remove( fileName )
import os
os.rename("files/a.txt" , "files/aaa.txt")
os.remove("files/b.txt")
|
8acf2d209472782794a6c01a189b356056cca591 | mumarkhan999/UdacityPythonCoursePracticeFiles | /30_changing_size_position_of_window.py | 506 | 3.65625 | 4 | from tkinter import *
my_gui = Tk()
my_gui.title("Hello")
#500x500 is the height and width
#+100+100 are the coordinates where the
#window should be loacted
#you can just give height and width like
#my_gui.geometry("500x500")
my_gui.geometry("500x500+300+100")
#the following method is to sustain the
#created window w... |
96645d773bd8d26aa377f4d060f7e3fb4e7d28ed | mumarkhan999/UdacityPythonCoursePracticeFiles | /6_factorial.py | 293 | 4.09375 | 4 | #calculating factorial of a number using while loop
num = int(input("Enter any number:\n"))
if(num < 0):
print("It's a negative number.")
else:
fact = 1
while(num > 0):
fact = fact * num
num = num - 1
print("Answer:\t",fact)
input("Press any key to quit...")
|
af5ab9aad7b047b9e9d061e22ab7afe7e64a4b01 | mumarkhan999/UdacityPythonCoursePracticeFiles | /9_exponestial.py | 347 | 4.5 | 4 | #claculating power of a number
#this can be done easily by using ** operator
#for example 2 ** 3 = 8
print("Assuming that both number and power will be +ve\n")
num = int(input("Enter a number:\n"))
power = int(input("Enter power:\n"))
result = num
for i in range(1,power):
result = result * num
print(result)
input("... |
a6fc7a95a15f7c98ff59850c70a05fdb028a784f | mumarkhan999/UdacityPythonCoursePracticeFiles | /8_multi_mulTable.py | 208 | 4.25 | 4 | #printing multiple multiplication table
num = int(input("Enter a number:\n"))
for i in range (1, (num+1)):
print("Multiplication Table of",i)
for j in range(1,11):
print(i,"x",j,"=",i*j)
|
c5ca14c217ef69d939e703af6b6874ae5ad83a48 | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week3/assignment/problem_1.py | 962 | 3.9375 | 4 | """
Task: The goal in this problem is to find the minimum number of coins needed to change
the input value (integer) into coins with denominations of 1, 5, 10.
Input format: single integer m. (1<=m<=10^3)
Output: minimum number of coins with denominations 1, 5, 10 that changes m.
"""
def greedy_strategy(m, print_dist... |
b7cd7e0d5126c9232909b35170173b1dec9fa535 | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week3/assignment/problem_3.py | 1,225 | 3.765625 | 4 | # python3
"""
Maximizing Revenue in Online ad placement.
You have n ads to place on a popular internet page. For each
ad, you know how much is the advertiser willing to pay for one
click on this ad. You have set up n slots on your page and
estimated the expected number of clicks per day for each slot.
Now your goal is ... |
162b0739cda0d6fba65049b474bc72fecf547f3d | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week4/assignment/problem_4.py | 2,492 | 4.21875 | 4 | # Uses python3
"""How close a data is to being sorted
An inversion of sequence a0, a1, .. an-1 is a pair of indices 0<= i < j< n
such that ai < aj. The number of inversion of a sequence in some sense measures
how close the sequence is to being sorted. For example, a sorted (in non-decreasing
order) sequence contains n... |
8513907fa4d6fc28ef69ea6e63e9d6c80fad2dbc | dodgeviper/coursera_algorithms_ucsandeigo | /course1_algorithmic_toolbox/week3/assignment/problem_6.py | 2,306 | 3.5 | 4 | # python3
from functools import cmp_to_key
import random
# n = int(input())
# numbers = list(map(int, input().split()))
def compare_two_numbers(x, y):
if x == y:
# I don't check two same numbers till the very end.
return x - y
str_x = str(x)
str_y = str(y)
if str_x[0] != str_y[0]:
... |
962786e444b2c6b67be7f319dd294e9b700d59a3 | waigani/simplepy | /count.py | 214 | 3.546875 | 4 | # Python 3
def main():
count = 1
# Code block 1
while count < 11:
print(count)
count = count + 1
# Code block 2
if count == 11:
print('Counting complete.')
if __name__ == "__main__": main()
|
96f76b3b40a51e3ac9f01cf8d7669f6dc14b8d55 | project-alchemist/ACIPython | /alchemist/Parameter.py | 2,596 | 3.703125 | 4 | class Parameter:
name = []
datatype = []
value = []
datatypes = {"BYTE": 33,
"SHORT": 34,
"INT": 35,
"LONG": 36,
"FLOAT": 15,
"DOUBLE": 16,
"CHAR": 1,
"STRING": 46,
"... |
7526485b8bf02efe669c97fc521151785679c682 | talhaahmed884/AI-Chess | /chess_rafay/minimax_test.py | 8,104 | 3.75 | 4 | '''
This is UNIVERSITY KA CODE
YOU CAN SKIP THIS BAISHAK CLOSE THIS SECTION CUZ IDK KHAIR COULD BE USED FOR HELP
'''
'''
import copy
import math
import random
import sys
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
... |
8c41e6813d5e137bf3acbe883b08d269d9cb7d7b | Smellly/weighted_training | /BinaryTree.py | 1,813 | 4.25 | 4 | # simple binary tree
# in this implementation, a node is inserted between an existing node and the root
import sys
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(s... |
5f5f35f563656072b345ad7752970759b12de47d | ShuhengWang/530-391-13 | /readwrite.py | 341 | 3.640625 | 4 | def read():
f=open("input",'r')
#read a
line=f.readline()
split=line.split()
print(split)
a=float(split[2])
#read b
line=f.readline()
split=line.split()
print(split)
b=float(split[2])
#read c
line=f.readline()
split=line.split()
print(split)
c=float(split[2])
#clean up
f.close()
#return a, ... |
6a4fbb6594b38db7b23c3de89aedbe166bae0ae2 | pastrouveedespeudo/ste-fois-c-la-bonne | /imageimage1.2/outils_main.py | 927 | 3.578125 | 4 | class outils_main:
def pos_liste_traitement(self, liste, liste_main, compteur):
self.liste = liste
self.compteur = compteur
self.liste_main = liste_main
c = 0
for i in range(self.compteur + 1):
for i in self.liste_main:
... |
b7fcd7060e743f687f37a49b33cb7edf0e78b9f2 | pastrouveedespeudo/ste-fois-c-la-bonne | /imageimage/essais.py | 682 | 3.90625 | 4 | liste = [['le', 'Article défini', 'None', 'prénom'],
['chien', 'Nom commun', 'None', 'pas prénom'],
['noir', 'Article défini', 'None', 'pas prénom']]
c = 0
for i in liste:
if liste[c][3] == "prénom" and liste[c][1] == "Article défini"\
or liste[c][1] == "Article indéfini... |
a5f8cf2de38a252d3e9c9510368419e5a763cf74 | TheFibonacciEffect/interviewer-hell | /squares/odds.py | 1,215 | 4.28125 | 4 | """
Determines whether a given integer is a perfect square, without using
sqrt() or multiplication.
This works because the square of a natural number, n, is the sum of
the first n consecutive odd natural numbers. Various itertools
functions are used to generate a lazy iterable of odd numbers and a
running sum of them,... |
5a4252b8e3fb28d08b328634902434343b172875 | itroot/projecteuler | /lib/PythagoreanTriples.py | 460 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
http://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples
"""
pairMN=(2, 1)
def nextLevel(pairMN):
(m, n)=pairMN
return ((2*m-n, m), (2*m+n, m), (m+2*n, n))
def MN2ABC(pairMN):
(m, n)=pairMN
return (m**2-n**2, 2*m*n, m**2+n**2)
def traverse(pairMN, condition):
... |
ecb7b0ddcbcc020b2ef0ccf52375a5079e141c1f | itroot/projecteuler | /solved/level-1/14/solve.py | 1,655 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Tail:
def __init__(self, number, length):
self.number=number
self.length=length
def __repr__(self):
return self.__str__()
def __str__(self):
return "(%d, %d)" % (self.number, self.length)
class Sequence:
def __init__... |
0bdb2ec8f43ae4ac159422ad8a6c4743772e26cf | itroot/projecteuler | /lib/SequenceNumber.py | 819 | 3.875 | 4 | # -*- coding: utf-8 -*-
class SequenceNumber:
def __init__(self):
self.__n=0
def advance(self):
self.__n+=1
def n(self):
return self.__n
class TriangleNumber(SequenceNumber):
def generate(self):
n=self.n()
return n*(n+1)/2
class SquareNumber(SequenceNumber):
... |
4f98a689da42bbf1cfd4eaf975ae171d0044512a | itroot/projecteuler | /solved/level-1/04/solve.py | 391 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def isPalindromic(number):
s=str(number)
if (0!=len(s)%2):
return False
halfLen=len(s)/2
return s[0:halfLen]==s[halfLen:][::-1]
palindromic=[]
for num1 in range(900, 999):
for num2 in range(900, 999):
num=num1*num2
if isPalind... |
d6621b45b61e1dc72d8e336dde42f02281fff1e8 | itroot/projecteuler | /solved/level-4/78/solve.py | 738 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://en.wikipedia.org/wiki/Partition_(number_theory)#Generating_function
"""
def pentagonal(n):
return n*(3*n-1)/2
cache=[1]
def p(n):
result=0
if n<0:
pass
elif n==0:
result=1
else:
k=0
while True:
v... |
4e4cc7f028fc3c91d5c3c634767d703e2f78a0f0 | itroot/projecteuler | /solved/level-2/39/solve.py | 799 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# FIXME copy-paste from #09
import math
tripletSum=1000
def is_square(number):
sqrtNumber=int(math.sqrt(number))
return sqrtNumber*sqrtNumber==number
def verifyFirstTwoNumbers(first, second):
sumOfSquares=first**2+second**2
if is_square(sumOfSquares):... |
cc7e18c5de2b5850b830c808c13cc68f86f8aceb | itroot/projecteuler | /solved/level-3/62/solve.py | 399 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
upperLimit=10000;
hash2numberList={}
for number in range(0, upperLimit):
hash="".join(sorted(str(number**3)))
if not hash in hash2numberList:
hash2numberList[hash]=[]
numberList=hash2numberList[hash]
numberList.append(number)
if (len(numberLi... |
56a38618d02c94538519c056cca65d409714f1e1 | itroot/projecteuler | /solved/level-4/100/solve.py | 981 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
see: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Pell.27s_equation
"""
"""
Let A be number of blue discs, B - number of all discs
Than, (A/B)*((A-1)*(B-1) == 1/2 -> 2*A**2-2*A == B**2 - B
Than, B**2 - 2*A**2 == B - 2*A
Than, (2*B-1)**2 - 2*(2*A-1)... |
ad6c98d8748b42d2ec0eaffd2e40708888f02e96 | kingyau991319/python_learning-W- | /rename_file.py | 1,325 | 3.5625 | 4 | # this prgoram is for rename the file in windows
# because windows does not support with the bash shell
# -> made on 20-7-2021
import os
import pathlib
def renameFile(dir_path = None, out_path = None):
# to 2get the filelist of the current inputing dir
file_paths = os.listdir(dir_path)
file_lens = len(f... |
3672c7869cb913068693ba8bb90b402efbbe9f49 | JKayathri/Part-of-my-Brain | /binary to decimal.py | 174 | 3.84375 | 4 | n=int(input("Enter the binary value"))
count=-1
sum=0
while(n!=0):
r=n%10
n=int(n/10)
count=count+1
sum=sum+(2**count)*r
print("Decimal value is "+ str(sum))
|
b09d81da93681e8f4e40dac4d70673b32f694ac1 | sully90/dp-search-service | /src/main/python/modules/ONS/text_processing.py | 1,926 | 3.5625 | 4 | from gensim.utils import lemmatize
from nltk.corpus import stopwords
def get_stopwords():
return set(stopwords.words('english')) # nltk stopwords list
def get_bigram(train_texts):
import gensim
bigram = gensim.models.Phrases(train_texts) # for bigram collocation detection
return bigram
def build_te... |
85c2f479e4b060f19627fb529a86fdf67e8b8a63 | UdalovPS/Coach-book-v1 | /Widtext/head_main.py | 498 | 3.75 | 4 | """
This module return text for widget for main window.
Text depends about choice language.
"""
def main_text(language='eng'):
if language == 'eng':
text = {'title': 'Coach Book', 'database': 'Database',
'training': 'Training'}
if language == 'rus':
text = {'title': 'Книга трене... |
705face115e3e0a175693d6c21e4ccf2895c4dd6 | SUHAYB-MACHINELEARNING-FULL-STACK/Twaiq-Python-Project | /Twaiq-Python-project.py | 387 | 3.9375 | 4 | info = {
"1212121212":"mohammed" # For Example
}
Input = input('Your Name Or Phone Number: ').lower()
print("Sorry, The number is not found" if Input not in info.keys() and Input not in info.values() else "This is invalid number" if len([i for i in Input if i in "0123456789"])!=len(Input) else [i for i in info.keys()... |
ec04bfd6ff4eec392140b68f911dee0974598c88 | reikolaski/BootCamp2018 | /ProbSets/Comp/ProbSet1/shut_the_box.py | 1,317 | 3.65625 | 4 | import box, sys, time, random
if len(sys.argv) != 3:
print("Three command line arguments required.")
else:
start = time.time()
name = sys.argv[1]
time_limit = float(sys.argv[2])
remaining = list(range(1, 10))
def lose():
print("Game Over!\n")
print("Score for player ", name, ": ", sum(remaining), " points")
p... |
30da914f2d9e223617fe71e51f7036db05dcac23 | OliValur/Forritunar-fangi-1 | /1september.py | 1,424 | 4.09375 | 4 | # upto = int(input("Input an int: ")) # Do not change this line
# for num in range(0,upto):
# print(num)
# highest = int(input("Input an int: "))
# for num in range(1,highest+1):
# if num % 3 == 0:
# print(num)
# max_days = int(input("Input max number of days: "))
# target = int(input("Input doll... |
959fc6191262d8026e7825e50d80eddb08d6a609 | OliValur/Forritunar-fangi-1 | /20agust.py | 2,173 | 4.28125 | 4 | import math
# m_str = input('Input m: ') # do not change this line
# # change m_str to a float
# # remember you need c
# # e =
# m_float = float(m_str)
# c = 300000000**2
# e = m_float*c
# print("e =", e) # do not change this line)
# Einstein's famous equation states that the energy in an object at rest equals i... |
53e13545217802aaaaf8109eeccbb6d31ab1748a | zoomzoomTnT/DataLab379k | /lab1/problem1.py | 561 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
@author: Josh M, Zhicong Z
"""
import numpy as np
import matplotlib.pyplot as plt
# Mean Calculation
def mean(n):
return float(sum(n))/max(len(n),1)
mu, sigma = -10, 5
s = np.random.normal(mu, sigma, 1000)
mu2, sigma2 = 10, 5
s2 = np.ra... |
7cfc1bf5b32ba019052f824ae10df73541da2ff5 | Barnettxxf/DateStructureAndAlgorithm | /example/huffmantree.py | 608 | 3.5 | 4 | # -*- coding: utf-8 -*-
from DateStructureAndAlgorithm.bintree import BinTree, BinTNode, PrioQueue
__author__ = 'barnett'
class HTNode(BinTNode):
def __lt__(self, othernode):
return self.data < othernode.data
class HuffmanPrioQ(PrioQueue):
def number(self):
return len(self._elems)
def huf... |
fc19470b4215bec744c797d5600c1e562fab08c6 | VicFinistere/macgyver | /item.py | 1,091 | 3.65625 | 4 | """
Item Class : Where you can resize the ability of Mac Gyver to get Swiss Army Knives
"""
import os
import pygame
from config import ASSETS_DIR
from random import randint
class Item(pygame.sprite.Sprite):
"""
This class is handling properties and methods for all kind of item
:returns any player without... |
8973081798e44e438007c5537e05e6d2a6f1b825 | Dhiraj3108/myfirstcode | /9917103154_Assignment1_Stack.py | 530 | 4 | 4 | stack = []
def pushit():
ch = 'y'
while (ch == 'y'):
inp = input("Enter some character")
stack.append(inp)
ch = input("Do you want to enter more values? Enter y/n")
def popit():
if len(stack) == 0:
print('Cannot pop from an empty stack!')
else:
print('R... |
6fb7db8a66df18d4b501c64cf22b34e739226bda | id774/sandbox | /python/math/stats.py | 5,398 | 3.546875 | 4 | from math import sqrt, exp, log, pi, ceil, floor
from functools import reduce
import re
import random
def add(x, y):
"""足し算"""
return x + y
def average(l):
"""算術平均を求める"""
return reduce(add, l, 0.0) / float(len(l))
def standard_deviation(l):
"""標準偏差を求める"""
avg = average(l)
l2 = [(x - avg) ... |
7f948cb92a2de44ce96485a83b6b2c44ae0c36ff | id774/sandbox | /python/math/gaussian-function.py | 430 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ガウス関数
# http://en.wikipedia.org/wiki/Gaussian_function
# 正規分布における確率密度を示す関数
import math
def gaussian(dist, sigma=10.0):
exp = math.e ** (-dist ** 2 / (2 * sigma ** 2))
return (1 / (sigma * (2 * math.pi) ** .5)) * exp
# print gaussian(0.1)
# print gaussian(1.0)
... |
23b6ffcb6352e7c045387c2d3c385c300e4cf7e0 | id774/sandbox | /python/math/dice.py | 543 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def dice(v1, v2):
numerator = sum([c in v2 for c in v1])
denominator = len(v1) + len(v2)
return 2 * float(numerator) / denominator if denominator != 0 else 0
if __name__ == '__main__':
v1 = {"ほげ": 1, "ふが": 2, "ぴよ": 3}
v2 = {"ほげ": 2, "ふが": 1, "ほへ": 2}
... |
d425b27c817f89239b47a90e38b577af89484663 | id774/sandbox | /python/math/prime.py | 228 | 3.640625 | 4 | from itertools import count
def prime_generator():
g = count(2)
while True:
prime = next(g)
yield prime
g = filter(lambda x, prime=prime: x % prime, g)
for pr in prime_generator():
print(pr)
|
82b6fd6d60e1501c70df693a70257c63f5d5173f | id774/sandbox | /python/list.py | 747 | 3.546875 | 4 | import sys
class List(list):
def head(self):
return self[0]
def tail(self):
return self[1:]
def init(self):
return self[0:-1]
def last(self):
return self[-1]
def shift(self):
try:
return self.pop(0)
except IndexError:
retur... |
87c2f162f60d1ae47ea420fbb33e890518ef471e | id774/sandbox | /python/machine-learning/poisson-distribution.py | 539 | 3.6875 | 4 | # -*- coding:utf-8 -*_
import matplotlib.pyplot as plt
import numpy as np
import math
def poisson(lambd):
def f(x):
return float(lambd ** x) * np.exp(-lambd) / math.factorial(x)
return f
N = 8
L = []
score_mean = 0.8
f = poisson(score_mean)
L.append([f(k) for k in range(N + 1)])
for prob in L:
... |
11070e9df380011576950b7fb7ee24d666bc182a | id774/sandbox | /python/shufflesequence.py | 719 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pprint import pformat
import random
def randomize(items):
randomized = []
while 0 < len(items):
idx = random.randint(0, len(items) - 1)
popped = items[idx]
del items[idx]
randomized.append(popped)
return randomized
if __name_... |
73374d322193bbc0263446af998b4c8ad7853811 | NamanBhoj/PlotlyDash | /plotlydash/plotlytuts/barchart.py | 982 | 3.953125 | 4 | import plotly.graph_objects as go
import plotly.express as px #read data
#plot data
from plotly.offline import plot
import os
import pandas as pd
# DIRECTORY_PATH = os.path.abspath(os.path.dirname(__file__))
# data_path = os.path.join(DIRECTORY_PATH , '/data/csv/', 'aggregated_score.csv')
#reading data
data ... |
9077eea0e23378ce9768dfb7e7126cbd25e33081 | SilentThorns/Basic-Python-Projects | /DiceRollingSimulator.py | 772 | 3.9375 | 4 | import random
max=1
min=6
print("Heres your roll!",end=" ")
print(random.randint(max,min))
yesno = input("Reroll? Y/N: ")
while yesno == 'Y' or yesno== 'y':
pass
print("Heres your roll!",end=" ")
print(random.randint(max,min))
yesno = input("Reroll? Y/N: ")
print("Heres your roll!",end=" ")
whil... |
bf33705f0a6af867dfd505807e2387a5f740eaa5 | aptro/codeme | /Problems/coincount.py | 1,156 | 3.5625 | 4 | import sys
sys.setrecursionlimit(10000)
#dynamic testing fibonnaci
def fib(n):
if n <= 1:
return 1
else:
return fib(n-1) + fib(n-2)
def coincount(l):
if l[2] == 0:
return 1
if l[2] < 0:
return 0
if (l[1]<=0 and l[2]>=1):
return 0
return coincount([l[0], l... |
d0e02d65fe7d8c42f6cdf51f003a071cd5f2f60c | aptro/codeme | /Problems/pythonutility.py | 222 | 3.734375 | 4 | import os
def printdir(dir):
filenames=os.listdir(dir)
for filename in filenames:
print filename
print os.path.join(dir, filename)
print os.path.abspath(os.path.join(dir, filename))
|
355a495c5cb9d403ad1b8f960919d211c3810479 | saxsoares/IA-Python | /problem-5/knn.py | 2,980 | 3.5625 | 4 | import math
import random
#import matplotlib.pyplot as plt
# Retorna a media das respostas das k entradas mais proximas ao novo_exemplo
# 1) Calcula a distancia euclidiada (sqrt(sum((x - y)^2))) entre novo_exemplo e cada uma das entradas
# 2) Monta uma tupla (distancia, resposta)
# 3) Ordena as tuplas, da menor... |
0f3e6670dc78b9115b61a2eaca34f81bb8f09ed9 | saxsoares/IA-Python | /codes-Professor/meuknn_reg.py | 3,333 | 3.65625 | 4 | # carrega e mistura
import math
import random
import matplotlib.pyplot as plt # required for plotting
from mpl_toolkits.mplot3d import Axes3D
# Retorna a media das respostas das k entradas mais proximas ao novo_exemplo
# 1) Calcula a distancia euclidiada (sqrt(sum((x - y)^2))) entre novo_exemplo e cada uma das entrad... |
0837151d119a5496b00d63ae431b891e405d11cb | Shubham1744/Python_Basics_To_Advance | /Divide/Prog1.py | 249 | 4.15625 | 4 | #Program to divide two numbers
def Divide(No1,No2):
if No2 == 0 :
return -1
return No1/No2;
No1 = float(input("Enter First Number :"))
No2 = float(input("Enter Second Number :"))
iAns = Divide(No1,No2)
print("Division is :",iAns);
|
8bb3ca89be52df473d6b8b1a296c124c6094493d | Shubham1744/Python_Basics_To_Advance | /Reverse_Range/rev_range.py | 196 | 4.21875 | 4 | # Program to print 5 to 1 numbers on screen.
def DispRev(int n):
for i in range(n,0,-1): #range(start,stop,increment/decrement)
print(i)
n = int(input("Enter Number"))
DispRev()
|
ddc72147f7844b39ff06a73ffea009d96e8de69d | Scorcherfjk/practicas-en-Python | /hecho_en_el_trabajo/manejo_de_strings/encontrar_mayusculas.py | 366 | 3.609375 | 4 | def mayusculas(cadena):
letras = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
coincidencias = ''
for x in cadena:
for y in letras:
if x == y:
coincidencias = coincidencias + x
return coincidencias
cadena = input("Introduce una cadena de texto")
print("Se han encontrado {} mayusculas y estas fueron las letras {}.".format... |
8f02e78c31165d76db121a3ff54e5604e2c36e54 | Osabutey/Azubi_time_tracking_Faith_Emma_assignment | /Time_tracking_Faith_Emma.py | 1,541 | 3.78125 | 4 | #!/usr/bin/python
from datetime import datetime
datearr=[] #create an array to store date
wage_per_hour = 5
client_name = input("Name of client: ")
task_name = input("What is the name of this task?: ")
started = input("When did "+task_name+" start? (YYYY-MM-DD HH:MM): ")
datearr.append(started)
#end = input("When did ... |
b57b724347cc8429c3178723de6182e741940b16 | DarioDistaso/senai | /logica_de_programação/sa4etapa1.py | 1,614 | 4.15625 | 4 | #Disciplina: [Logica de Programacao]
#Professor: Lucas Naspolini Ribeiro
#Descricao: SA 4 - Etapa 1: PILHA
#Autor: Dario Distaso
#Data atual: 06/03/2021
pilha = []
def empilhar(): # opção 1
if len(pilha) < 20:
produto = str(input("Digite o produto: ")).strip()
pilha.append(produto)
print(... |
d2c3755214d8cd933f7e687f1e804d2f7fadcc83 | iNSDX/AI | /Practise2/búsqueda_espacio_estados.py | 6,693 | 3.5 | 4 | import collections
import heapq
import types
class ListaNodos(collections.deque):
def añadir(self, nodo):
self.append(nodo)
def vaciar(self):
self.clear()
def __contains__(self, nodo):
return any(x.estado == nodo.estado
for x in self)
class PilaNodos(ListaNod... |
af96e03ed2f237582cab288b6dd423ea09857039 | lovecure/py_test | /day2.2-var.py | 982 | 3.546875 | 4 | # -*- coding: utf-8 -*-
n = 123
f = 456.789
s1 = 'Hello,world'
s2 = 'Helo,\'Adam\''
s3 = r'''Hello,
Lisa!'''
s4 = 'Hello,"Bart"'
print(n)
print(f)
print(s1)
print(s2)
print(s3)
print(s4)
print ('True is:',True)
print ('False is:',False)
print('3>2 is:',3>2)
print('3>5 is:',3>5)
print('True and True is:',True and True... |
b37606444c1fb9f60ca5efbcec093ccc10946ed8 | UMassPlecprep/ShoppingCart | /backups/auto_corrector.py | 1,120 | 3.84375 | 4 | # Being built...
# Slightly better correcting
# Rather than just finding letter similarities, it looks for substring similarities
def advancedGuessing(list_of_people, name):
confidence = {prof : 0 for prof in list_of_people}
# Find common substrings
for prof in list_of_people:
name_iterator = iter(... |
3b64db7db4ec638a168afd5ba896b113ff466907 | AbhishekBhattacharya/Python-MOOC | /matrixmultiply.py | 468 | 3.640625 | 4 | def matmult (A, B):
rows_A = len(A)
cols_A = len(A[0])
rows_B = len(B)
cols_B = len(B[0])
if cols_A != rows_B:
return
# Create the result matrix
# Dimensions would be rows_A x cols_B
C = [[0 for row in range(cols_B)] for col in range(rows_A)]
for i in... |
4aa8c209c3b54723b198b405cdb2fff6d78c5a07 | kandura/logicaprogramacao | /prova2.py | 327 | 3.828125 | 4 | def nota_do_aluno():
print("Média do aluno é:")
primeiranota = (input(7))
segundanota = (input(6))
terceiranota = (input(8))
return (primeiranota + segundanota + terceiranota) / 3
nota_do_aluno()
N = int(input(7))
lista = [4,5,2,8,6,3,7]
def funcao_da_lista():
i = 0
while i < N:
num = input(7)
... |
c35d93f5359f710db0bb6d3db7f4c8af1724b1e9 | umberahmed/hangman- | /index.py | 586 | 4.25 | 4 | # This program will run the game hangman
# random module will be used to generate random word from words list
import random
# list of words to use in game
list_of_words = ["chicken", "apple", "juice", "carrot", "hangman", "program", "success", "hackbright"]
# display dashes for player to see how many letters are in... |
aa9010cbb6ecdcec92ba34816ceb8c6bd15cea73 | mihalyvaghy/tdd_katas | /calculator/src/calculator.py | 1,250 | 3.8125 | 4 | import re
def find_delimiter(numbers):
if len(numbers) > 0:
if re.match("//(?P<delimiter>.)\n\d+(?:(?P=delimiter)\d+)*", numbers):
return numbers[2], numbers[4:]
elif re.match("//(?P<delimiter>\[.*\])\n\d+(?:(?P=delimiter)\d+)*", numbers):
first_newline = numbers.find("\n")
... |
993385aca8c15768b4815cc7cddef93fde3c74a3 | yangzhoudeni/day01 | /src/21.while.py | 480 | 3.71875 | 4 | '''
while: 负责不固定次数的循环
while 条件:
xxxx
'''
# 制作 猜数字游戏:
import random
# 0-1000之间 随机获取数字
target = random.randint(0, 1000)
count = 0
while True:
count += 1
num = input('请猜测一个数字(0-1000):')
num = int(num)
if num == target:
print('恭喜您, 猜对了, 共猜了%s次' % count)
break
if num < target:
... |
40378be4bb95c0670ebc830730efea465be5b0b2 | yangzhoudeni/day01 | /src/14.san.py | 201 | 3.84375 | 4 | # 三目运算符
# 条件 ? 真值 : 假值
# python坚持 语义化特点: 外国人习惯倒装语法
# 真值 if 条件真 else 假值
married = False
print('已婚' if married else '未婚')
|
10016492cba7d82dae2866612a5540686d810f43 | gsliu/python | /foo.py | 462 | 3.75 | 4 | #!/usr/bin/python
def in_the_fridge() :
try:
count = fridge[want_food]
except KeyError:
count = 0
return count
fridge = {"milk" :1, "banana" :2, "apple":3}
want_food = "aaa"
c = in_the_fridge()
print c
A = 1
B = 2
C = 3
if (A == 1 and
B == 2 and
C == 3) :
print('spam'*3)
while... |
600cf2ecb0e69dd2b30f582f097d34af8cf0408c | gsliu/python | /checkpara.py | 356 | 3.96875 | 4 | #!/usr/bin/python
def check ( para={"aaa":1, "ccc":2}):
if type(para) == type( {}):
print "dict"
elif type(para) == type ([]):
print "list"
elif type(para) == type (""):
print "string"
else:
print "I don't know this type"
a = {"aaa":1, "bbb":2}
b = [1,2,3]
c = "jjjj"
... |
8bcc479bb3a9fa632e730b052ffbf0cedc945195 | OlehPalka/Second_semester_labs | /labwork7/task345/4/document.py | 5,693 | 4.375 | 4 | """
This module contains classes which will help you to edit document.
"""
class Document:
"""
This class allows you to control editing of a basic document.
>>> doc = Document()
>>> doc.filename = "test_document"
>>> doc.filename
'test_document'
>>> doc.insert('h')
>>> doc.insert('e')... |
1db2c36a281249ea00fa1328903ef8910a521845 | OlehPalka/Second_semester_labs | /labwork12/2/stack_to_queue.py | 824 | 3.71875 | 4 | """
Stack to queue converter.
"""
import copy
from arraystack import ArrayStack # or from linkedstack import LinkedStack
from arrayqueue import ArrayQueue # or from linkedqueue import LinkedQueue
def stack_to_queue(stack):
"""
This function returns queue from stack.
"""
stack_copy = copy.deepcopy(... |
4896af0a999d2e29edcc559326c52a9efea0ca19 | OlehPalka/Second_semester_labs | /labwork10/2.py | 10,852 | 3.890625 | 4 |
import ctypes
class LifeGrid:
"""
Implements the LifeGrid ADT for use with the Game of Life.
"""
# Defines constants to represent the cell states.
DEAD_CELL = 0
LIVE_CELL = 1
def __init__(self, num_rows, num_cols):
"""
Creates the game grid and initializes the cells to de... |
046cf121410bcf4d686768c851facb314b9fa666 | OlehPalka/Second_semester_labs | /labwork5/5task/game.py | 3,528 | 4.21875 | 4 | """
This module contains classes for game.
"""
monst_count = 0
class Room:
"""
this class creates rooms in a game
"""
def __init__(self, name: str):
self.list_of_rooms = list()
self.name = name
self.descr = ""
self.character = None
self.room_item = None
de... |
69612c6e4aaf8674e47d8b074dbb22ddb6e996a8 | OlehPalka/Second_semester_labs | /labwork6/bird.py | 6,679 | 3.71875 | 4 | # class Bird:
# def __init__(self, name):
# self.name = name
# self.eggs = []
# def __repr__(self):
# if len(self.eggs) == 1:
# return f"{self.name} has {len(self.eggs)} egg"
# return f"{self.name} has {len(self.eggs)} eggs"
# def count_eggs(self):
# re... |
774c04ecf2f74710147affadfbf180c0c53332af | OlehPalka/Second_semester_labs | /labwork5/3-4task/cache_webpage.py | 2,777 | 3.5625 | 4 | """
This is module which contains two classes for cashing data from the webpage.
"""
import doctest
from datetime import datetime
from urllib.request import urlopen
from time import time
clean = open("date_note.txt", 'a')
clean_1 = open("cash_note.txt", 'a')
with open("date_note.txt") as file:
if file.readlines()... |
03e54e71a1ec4850263d789762e38b8230da3e5d | zhuguangxiang/LeetCode | /Topological Sort.py | 1,523 | 3.859375 | 4 | def topological_sort(unsorted_graph):
'''
idea from http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/
deal with a node only if all it's children are sorted, in other words, start from the latest appeared nodes, build
from there. A cycle is defined when in any iteration, none o... |
191b74137d4b0636cbf401c865279f8c33ef69b0 | zyavuz610/learnPython_inKTU | /python-100/104_numbers_casting.py | 1,147 | 4.46875 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Python 100 - Python ile programlamaya giriş
Python 101 - Python ile Ekrana Çıktı Yazmak, print() fonksiyonu
Python 102 - Değişkenler ve Veri Türleri
Python 103 - Aritmetik operatörler ve not ortalaması bulma örneği
Python 104 - Sayılar, bool ifadeler ve tür dönüşüm... |
d9dd950f5a7dd35e1def63114c2f65ad6c2fb3da | zyavuz610/learnPython_inKTU | /python-100/113_while-loop.py | 1,322 | 4.28125 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
python-113: while döngüsü, 1-10 arası çift sayılar, döngü içinde console programı yazmak
Döngüler, programlamada tekrarlı ifadeleri oluşturmak için kullanılır.
türleri
for
while
döngülerin bileşenleri: 4 adet döngü bileşeni
1. başlangıç
2. bitiş (döngüye devam... |
bfdbff1ee6bfcad011283793b55052eafddd8375 | zyavuz610/learnPython_inKTU | /zylibs/zylib.py | 1,228 | 3.671875 | 4 | def isPrime(n):
if n <= 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
#-----------------------------------------------
def allPrimes(n):
for i in range(2, n):
if isPrime(i):
yield i
#######################################... |
36e6d2c05203975cc1c98d54921dcb92edf2960f | zyavuz610/learnPython_inKTU | /python-100/122_infinite-loop_examples.py | 778 | 4.03125 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Önceki dersler:
değişkenler ve operatörler
koşul ifadeleri: if,else
veri yapıları: string, liste
döngüler: for, while, iç içe döngüler
fonksiyonlar, fonksiyon parametreleri, örnekler
modüller, kendi modülümüzü yazmak
datetime, math
Python - 122 : yuzy... |
db985b8f58b3c1ba64a29f48c8b1c1620a22629f | zyavuz610/learnPython_inKTU | /python-100/131_set-intro.py | 1,266 | 4.21875 | 4 | """
Seri: Örneklerle Python Programlama ve Algoritma
Önceki dersler:
değişkenler ve operatörler
koşul ifadeleri: if,else
döngüler: for, while, iç içe döngüler
fonksiyonlar, modüller
veri yapıları:
string,
list,
tuple
...
set *
dict
Python - 131 : Set (Küme) Veri Yapısı
Set(s... |
fa78bebb898f6de38d40a7b6c91798bfe03c2589 | kschultze/Learning-Python | /Assignment_1/assn_pt_2.py | 1,091 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 17 21:50:33 2016
@author: Schultze
first crack at computing the nth prime number
optimized for simplest code, not fastest run time
"""
#guess = 2
#
#n = 1
#while n < 1000:
# guess = guess + 1
# test = 1
#
# rem = 1
# while rem != 0:
# rem = guess%... |
5c7aeb4928ee50fafc67f0e7075b88af0971af83 | kschultze/Learning-Python | /Assignment_2/diaphantene2_rev1.py | 1,267 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
07/26/16
@Schultze
Script to calculate chicken nuggets combinations
If nuggets are sold in packs of 6, 9, and 20, what combinations are required to
get exactly n nuggets. AKA, all solutions to the diopnantene equation:
6A + 9B + 20C = n for a given n
This is an update to diahpantene_... |
91677c621750609fdb858b0db7617e604707e125 | kschultze/Learning-Python | /Misc/polackPoker.py | 5,130 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 24 17:34:25 2017
@author: kschultze
"""
import numpy
import random
import copy
def rollDice(player, playerNames, numPlayers, quarters):
"""
prompt user to input the roll and adjust everyone's quarters
inputs
player - int = index of player rolling... |
7a8acb8640e52e9c22c80aaa2ecfab7c2619d30c | groovyspaceman/algo_training | /temp/pair_of_elements_with_sum_x.py | 336 | 4 | 4 | """
Given an integer X and a list L, find the first pair in L whose sum is X
"""
def find_pair_with_sum(X, l):
"""
Returns a tuple with indexes of both elements or None if there is no pair
"""
return (0, 1)
l = [3, 34, 4, 12, 5, 2]
X = 5
print ("In the list {} items {} sum {}".format(l, find_pair_wi... |
420932cc759072920300246b5c0b9720dd629b0e | petr-tik/lscc | /mars_kata.py | 1,531 | 3.84375 | 4 | #! usr/bin/env python
"""
from london software craftsmanship group meetup on python katas
"""
from collections import deque
import unittest
import random as rnd
class Rover(object):
def __init__(self, x, y, direction, min_val, max_val, num_obstacles):
self.x = x
self.y = y
self.direction = ... |
8cd0e8f2fa5f4af240a800f9a0da13725f2989b7 | tuw-robotics/tuw_geometry | /test/test_cases.py | 924 | 3.5 | 4 | #!/usr/bin/env python
import unittest
import tuw_geometry as tuw
class TestPoint2D(unittest.TestCase):
def runTest(self):
p = tuw.Point2D(3,2)
self.assertEqual(p.x, 3, 'incorrect x')
self.assertEqual(p.y, 2, 'incorrect y')
self.assertEqual(p.h, 1, 'incorrect h')
p = tuw.Poi... |
33f3c44f5558e7f6af212ddeef9022d1b582b0ee | JanikaScheuer/Janika | /aufgabe_1.py | 1,240 | 3.59375 | 4 | def encode(message, key):
# static variables
msg_len = len(message)
alfa = 'abcdefghijklmnopqrstuvwxyz'
out_message = ''
for letter in message:
if letter.lower() not in alfa:
print('invalid letter')
break
if letter == letter.lower():
# search letter posi... |
026a13ce0636a032257396aa79b6d91e98331300 | akashraut1/PYTHON | /Basic Python/file open read.py | 417 | 3.59375 | 4 | fo = open("Akash.txt", "rw+")
#print ("Name of the file: ", fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
print ("Read Line: %s" % (line))
# Again set the pointer to the beginning
fo.see... |
300c0fb47e6201cc6480159b11cd7f12a39320b8 | robertDurst/huffman_compression | /huffman.py | 5,248 | 3.734375 | 4 | # @robertDurst @ 2020
# Implementation of Huffman Coding:
# https://en.wikipedia.org/wiki/Huffman_coding
from collections import Counter
from utils import encodeASCII, decToBin, binToDec, writeBytesToFile, readBytesFromFile, Node
"""
A completely compressed file is formatted as so:
[padding length][hea... |
25ece7125e51196b3eb866a06f6cea0910357f81 | genetica/pylator | /testScripts/textTest.py | 1,879 | 3.75 | 4 | ###############################################################################
# Tests to see if string concatenation is slower or faster than
# the .format function.
#
# Conclusion.
# Using variables does slow string creation down(+-5%) but the difference
# between concatenation and .format function is not stati... |
a462d5adc2feb9f2658701a8c2035c231595f81e | kristinejosami/first-git-project | /python/numberguessing_challenge.py | 911 | 4.3125 | 4 | '''
Create a program that:
Chooses a number between 1 to 100
Takes a users guess and tells them if they are correct or not
Bonus: Tell the user if their guess was lower or higher than the computer's number
'''
print('Number Guessing Challenge')
guess=int(input('This is a number guessing Challenge. Please enter your ... |
2fb684421bc670eaeea15e5c73cb997ce7aa3f04 | ardKelmendi/rf_codingtask | /models.py | 1,383 | 3.890625 | 4 | #Class contains 3 classes that are used to store the data
class Product:
def __init__(self, id, name, unit, quantity, category, measurement_unit):
self.id = id
self.name = name
self.unit = unit
self.quantity = quantity
self.category = category
self.measurement_unit =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.