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 |
|---|---|---|---|---|---|---|
55a020c712e83905693aff8190f4f74317bb775f | obioma-Nwosu/MLearning | /matplotlib.py | 3,893 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
visualization in matplotlib
Created on Thu Jul 8 13:37:03 2021
@author: Obioma Nwosu
use ctrl + I to check documentation for package
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
year = [2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020]
temprature ... |
d12d1b14b0eda6d40299e74425cf569be7c6dcdf | Haabb/pwnfork | /pwn/crypto/util.py | 5,917 | 3.84375 | 4 | """
Collection of various utility functions for cryptoanalysis.
"""
from functools import wraps
from itertools import *
import freq
# The expected index of coincidence value for English text
ic_english = 0.065
def index_of_coincidence(frequencies, n):
"""
Calculate the index of coincidence of a frequency
... |
b22a50bf89958bf5eeb248ede32801ad6fbfaf44 | ZafiraC/Zafira-Chairunnisa_I0320115_Andhika_Tugas4 | /I0320115_soal 2.py | 177 | 3.5625 | 4 | # SOAL NO 2
a = int(input("bilangan bulat pertama: "))
b = int(input("bilangan bulat kedua: "))
# operasi floor division //
hasil = a // b
print(a,'//',b,'=',hasil)
|
b3aa41fd7401c792af4cd40dda05693a508404b6 | whxhxx/PythonAmmoBox | /Demo/Demo_unit_test/basic_test_ground.py | 1,334 | 3.75 | 4 | import unittest
# import the testee
from my_math import *
class TestInstance(unittest.TestCase):
"""
the test unit
"""
# 1. basic functions for test
def test_add(self):
"""
the test functions MUST name started with "test"
"""
expected = 6
result = add(2,4... |
394ba208b4acb377368917f33d4c7d5b34aaed62 | sehgalromal/proj_5409_tasks | /Fibonacci/fibonacci_numbers.py | 1,448 | 3.671875 | 4 | import time
import random
def generate_random_integers(N):
with open("input_numbers.txt", "w") as gen_integer_file:
fact_numbers = []
for number in range(1, N):
fact_numbers.append(number)
random.shuffle(fact_numbers)
for num in fact_numbers:
... |
f48e553ec4413d45486baf565559604897b89c67 | yiboliu26/yibopython | /guestlist.py | 1,473 | 3.703125 | 4 | guest = ['guilin', 'flora', 'jay', 'taylor']
message = "I would like to invite " + guest[0].title() + " to our dinner on Sat night!"
print(message)
guest[1] = 'will'
print(guest)
unattended = guest.pop(1)
print("I feel sad since " + unattended.title() + " is unable to come today")
del guest[1]
print(guest)
guest.append... |
afd1a5dc6d85d64c9a6300a420a8253fb9d8d6e9 | yiboliu26/yibopython | /practice83.py | 1,630 | 4.15625 | 4 | def city_country(city_name, country_name):
"""show_city_info"""
city = city_name + ', ' + country_name
return city.title()
place = city_country('santiago', 'chile')
print(place + "!")
place = city_country('tokyo', 'japan')
print(place + "!")
place = city_country('beijing', 'china')
print(place + "!")
place... |
3aa6175a1f704fdbfea19855a617762cbdc185fc | yiboliu26/yibopython | /practiceifclause.py | 1,162 | 3.890625 | 4 | #5.3
alien_color = 'green'
if 'green' in alien_color:
reward = 5
print("You have been rewarded with "+ str(reward) +"pt! ")
if 'red' in alien_color:
print("You have not been rewarded. Keep playing!")
#5.4
alien_color = 'green'
if 'green' in alien_color:
reward = 5
print("You are rewarded for " + str(re... |
ff16ff6e38e43e11a96be94e4c3f673dfb6b0d43 | yiboliu26/yibopython | /conditionaltest.py | 689 | 3.6875 | 4 | #1
pizza = 'pepperoni'
print("Is pizza == 'sausage'? I predict False.")
print(pizza == 'sausage')
print("Is piza == 'pepperoni'? I predict True.")
print(pizza == 'pepperoni')
#2
fruit = 'tomato'
print("Is fruit == 'tomoto'? I predict True.")
print(fruit == 'tomato')
print("Is fruit == 'potato'? I predict False.")
print... |
f7120b30693afa50deee14f632cdcd585121469c | favourokezie/python-study-group | /assessment/assessment_3/Favour_Okezie/2(4).py | 698 | 3.96875 | 4 | import random
list1=random.sample(range(1,100),20)
print('The random list is: ',list1)
average=sum(list1)/len(list1)
print('The average of the list is: ',average)
max_no=max(list1)
print('The largest number in this random list is: ', max_no)
min_no=min(list1)
print('The smallest number in this random li... |
0b280769744c61753d5fb26c777fe99ac24dacee | inglesp/monsters | /monsters10.py | 2,217 | 3.8125 | 4 | class Monster(object):
def __init__(monster, name):
monster.name = name
monster.species = type(monster).__name__
monster.hit_points = monster.initial_hit_points
def describe(monster):
if monster.is_alive():
print('{} is a {} with {} hit points'.format(monster.name, m... |
b3779af6e4315e20706c208612b4a079709c2df2 | wrobelcarter1/CS-126 | /Chapter 9/Lock_Composition.py | 9,476 | 4.375 | 4 | __author__ = "Dr. Vanderberg"
'''
Plan for a single lock digit
(1) Draw the UML
(2) Constructor (__init__) sets locked_value
- how do we initialize the locked value?
- remember it should only be 0-9
(3) Method that changes the self.locked_value --> updateValue(self,newValue)
- only update self._value if sel... |
b7eea9d81b79f157e26a4d06dcbd4b2443c1bba4 | wrobelcarter1/CS-126 | /Chapter 5/Chapter_5_Problems.py | 3,943 | 4.15625 | 4 | # Carter Wrobel
# 9/21/17
# CS #186
# Section 1
'''
This program will go throguh the chapter... |
fb798c3f825ce3ba38968309c565b2c95dea5db0 | wrobelcarter1/CS-126 | /Labs/Lab 12/lab10_Answer_Key_MV.py | 6,131 | 4.40625 | 4 | class Card:
'''
This is the header for the class Card.
Any new card objects created will use the Card(card_num) method, which will be used
to create card objects with a suit, rank, and value. Cards start facing down.
'''
# class member variables - shared by all objects.
suits = ["Spad... |
70b254fb707d92e6cb51d223409993fe57f4adea | wrobelcarter1/CS-126 | /Chapter 9/class_objects_practice.py | 2,833 | 3.625 | 4 | # Carter Wrobel
# CS126L
# Section 1
# 11/7/17
'''
This will go through a s... |
854300cb49d11a58f9b72f1f3a59d4a12012cd9c | jb3/aoc-2019 | /day-3/python/wire.py | 1,486 | 4.15625 | 4 | """Structures relating to the wire and points on it."""
import typing
from dataclasses import dataclass
@dataclass
class Point:
"""Class representing a point in 2D space."""
x: int
y: int
def right(self: "Point") -> "Point":
"""Return a new point 1 unit right of the point."""
return ... |
a5ba0a665361e4785e4fcfe344e66fc00a23d0b7 | xuwangme/huffmanTree | /HuffmanTree.py | 4,466 | 3.71875 | 4 | """
# @author: xuwang
# @function: huffman Tree的相关类
# @date: 2017/11/20 16:14
"""
import abc
# 定义HuffmanTree节点抽象类
class HuffmanNode(object):
__metaclass__ = abc.ABCMeta
# 返回当前节点权重
@abc.abstractmethod
def getWeight(self):
return
# 返回当前节点是否为叶子节点
@abc.abstractmethod
def isLeafNode(se... |
73a87fc5f5a3607fa71fd0088339c208d25a0e46 | rubskuy/labspy03 | /Latihan2.py | 194 | 3.9375 | 4 | a = int()
b = int()
while a>= 0:
a=int(input("Masukkan Bilangan:"))
if a == 0:
break
if a > b:
b = a
print("Bilangan terbesar adalah",b)
print("Selesai")
|
137fcef39b99efd4d1086f6377494965a775c7e8 | thecreatorsir/DailyDSA | /linkedLists/decimal-equivalent-of-binary-linked-list.py | 324 | 3.578125 | 4 | def decimalValue(head):
MOD=10**9+7
# Code here
res1 = ""
if head == None:
return 0;
while head!=None:
res1 += str(head.data)
head = head.next
res1 = res1[::-1]
res2 = 0
for i in range(len(res1)):
res2 = (res2 + int(res1[i])*(2**i))%MOD
return res2 ... |
236f6fa78e09d53e460c712e0666e1b892aba5f8 | AnushSomasundaram/Anush_Python_projects | /chap4_fuctions/pass.py | 445 | 3.6875 | 4 | #the pass keyword can be used to leave areas of the code empty so that they can be worked on later
bool=True
if bool==True:
print("Python in Easy steps")
else:
pass
#if the pass keyword was not inserted after else and a set of commands were also not present then the
#program would have displayed a syntax e... |
3a0f7eeff64a22b7cdfffd613eccf1b9e63f735a | AnushSomasundaram/Anush_Python_projects | /chap3_making_statements/for.py | 481 | 3.84375 | 4 | # A a for keyword loops over all items in any list specified to the in keyword
chars=["A","B","C"]
fruit=("Apple","Banana","Cherry")
dict={'name':"mike","ref":"Pyhton","sys":"Win"}
print("\nElements:\t",end=" ")
for i in chars:
print(i,end=" ")
for item in enumerate(chars):
print(item ,end=" ")
print("... |
3fa1e3b95e4e747286d7907e7a3c3aec57e6ef96 | AnushSomasundaram/Anush_Python_projects | /chap9_building_interfaces/tk_listbox.py | 517 | 3.75 | 4 | from tkinter import *
import tkinter.messagebox as box
window=Tk()
window.title("List box Example")
frame=Frame(window)
listbox=Listbox(frame)
listbox.insert(1,'HTML5 in easy steps')
listbox.insert(2,'CSS3 in easy steps')
listbox.insert(3,'JavaScript in easy steps')
def dialog():
box.showinfo('Selection','You... |
647d1d36759511e86ef6434c8a59daf7b345e888 | AnushSomasundaram/Anush_Python_projects | /Anush_assignments/1st_sem/python/first assignment/area_of_triangle.py | 221 | 4.15625 | 4 | #Write a program to find the area of triangle given
# base and height.
def area_of_triangle(height,base):
area = 0.5*height*base
print("The area of the given trianle is ",area,"units.")
area_of_triangle(1,6)
|
b3364195e03e446c40dc0f3d0ccc8c093062e897 | AnushSomasundaram/Anush_Python_projects | /compsci_with_python/chap2/swapvalue.py | 304 | 3.84375 | 4 | first="Jimmy"
second="Jhony"
print("The first variable before swapping is",first,"\n")
print("The second variable before swapping is",second,"\n")
temp=first
first=second
second=temp
print("The first variable after swapping is",first,"\n")
print("The second variable after swapping is",second,"\n")
|
1c527311d782ceeec6e04e27d6f4b70e0532f9e4 | AnushSomasundaram/Anush_Python_projects | /chap4_fuctions/lambda.py | 458 | 4.25 | 4 | #lambda functions are just inline functions but specified with the keyword lambda
def function_1(x):return x**2
def function_2(x):return x**3
def function_3(x):return x**4
callbacks=[function_1,function_2,function_3]
print("\n Named Functions")
for function in callbacks:
print("Result:",function(3))
callbacks=\
... |
8a80e8418fbdd6c59ee687ab91e2f74d6c2cd625 | AnushSomasundaram/Anush_Python_projects | /chAP2_OPERATIONS/Arithmetic.py | 282 | 3.921875 | 4 | # initialize two variables
a,b=8,2
print("Addition-> a + b =",a+b)
print("Subtraction-> a - b =",a-b)
print("Multiplication -> axb = ",a*b )
print("Floor division -> a//b",a//b)
print("division -> a/b",a/b)
print("modulus(remainder)->a%b",a%b)
print("exponent a^b->",a**b)
|
3b9a3df013329cc99b8ac392ca6d1f2c1bbcbcde | AnushSomasundaram/Anush_Python_projects | /compsci_with_python/chap2/largestword.py | 310 | 4.125 | 4 | length= int(input("Enter the number of elements in the list"))
words=[]
for i in range (0,length):
print("Word no.",i,":-")
words.append(str(input()))
longest=0
for i in range (1,length):
if len(words[i])>len(words[longest]):
longest=i
print("longest word is :-",words[longest])
|
88c885dcf5f5981e8763689aece31ac3f8cdcf54 | AnushSomasundaram/Anush_Python_projects | /chAP2_OPERATIONS/precedence.py | 604 | 3.859375 | 4 | #precedence means the condition of being considered more important than someone or
# something else; priority in importance, order, or rank.
a=2
b=4
c=8
print("\nDefault order \t ",a,"*",c,"+",b ,"=",a*c+b)
print("\nForced order:\t ",a,"*","(",c,"+",b,") =",a*(b+c))
print("\n In default order\t",c,"//",b,"-",a,"="... |
cb7875e93bb7619218691f2beba46a87f691d96c | AnushSomasundaram/Anush_Python_projects | /Anush_assignments/1st_sem/python/first assignment/operations.py | 598 | 4.125 | 4 | """Write a Python program that allows the user to enter two integer values,
and displays the results when each of the following arithmetic operators are applied. For example,
if the user enters the values 7 and 5, the output would be,
7+5=12
7-5=2 and so on."""
number1=int(input("Please enter the first integer:-"))
... |
a6e9e4c64cc35e4cdc07e85ea8a127217b35b957 | SmartSoftwareAcademy/Assignment-1 | /List/lists/main.py | 379 | 4.09375 | 4 |
def numbers():
mylist=[6, 8, 5, 9, 7, 2]
mylist.sort()#sorting values in ascending order
print(mylist)
mylist.sort(reverse=True)#reverse sorting
print(mylist)
mytuple=(4, 5,6,('egg'))#Creating tuple and printing its contents
print(mytuple)
if __name__ == '__main__':
numbers()
# S... |
e45ce37c2a90ceb5f2cc462c9f78056c3bbada9b | renatopivessofranzin/Estudo_inicial_de_redes_neurais | /neural_003_perceptron_or.py | 3,303 | 4.3125 | 4 |
# Projeto:
# Estudo de implementação de uma rede neural artificial em Python
# Autor: Prof. Ms. Renato Pivesso Franzin
# Objetivos:
"""
* Aprender passo a passo todos os cálculos matemáticos que envolvem redes
neurais artificiais;
* Entender conceitos como perceptron, funções de ativação,
backpro... |
d50b0f192d8e7fc0c0d0c9e21a79ba1a496fae7c | MithilRocks/python-homeworks | /lists/sort_and_merge.py | 1,085 | 4.09375 | 4 | # HW: Wap to accept two lists from user, sort them using bubble sort and then merge them in sorted manner
def my_sort_bubble(a):
swap = True
while swap:
swap = False
x = 0
while x < (len(a) - 1):
if a[x] > a[x+1]:
swap = True
a[x], a[x+1] = a... |
76d43d9bc8db00125fde1eb88ffb25d7546b43c8 | MithilRocks/python-homeworks | /bitwise_homework/divisible_by_number.py | 399 | 4.3125 | 4 | # hw: wtp to check if a number is multiple of 64
def divisible_by_number(num):
if num & 63 == 0:
return True
else:
return False
def main():
number = 128
if divisible_by_number(number):
print("The number {} is divisble by 64".format(number))
else:
print("The number {}... |
4b7e3e0c667bcbb8026aa0fa24c03709defe8837 | MithilRocks/python-homeworks | /triangle_programs/diamond.py | 319 | 3.875 | 4 | def diamond_triangle(the_limit):
y = (the_limit - 1) // 2
for x in range(1, the_limit + 1, 2):
print(" " * y + "*" * x)
y -= 1
y = 1
for z in range(x - 2, 0, -2):
print(" "*y + "*" * z)
y += 1
def main():
diamond_triangle(10)
if __name__ == "__main__":
main() |
ee9f2b7959e4e2c17cd47a5e7584efe1604d7382 | MithilRocks/python-homeworks | /lists/class_programs.py | 1,133 | 4.0625 | 4 | # wap to write an append function of our own
def my_append(a, b, position):
return (a[:position] + b + a[position:])
# wap to print the indexes of all the occurences of the data in the list
def all_indexes(a, value):
indexes = []
x = 0
while x < len(a):
if a[x] == value:
indexes.ap... |
373479920c8d08c0f3bbc958cda30c2c2e11372f | RomarioNzenguele/shinobi | /changevar/App.py | 178 | 4.03125 | 4 | #Declaracao e atribuicao
x = input('x: ')
y = input('y: ')
#Troca dos valores
x, y = y, x
#Imprimindo o resultado
print("\n**** Valores trocados\nx: " + x + "\ny: " + y+"\n")
|
aed00211cfa9f953ca0f85961c2e5f2a853cdb00 | Hariharan2/hari | /vocon1.py | 101 | 3.890625 | 4 | num=(input(""))
state='a','e','i','o','u'
if num in state:
print("Vowel")
else:
print("Consonant")
|
1b3a9058ce0d91a8f7929c06d08c51ca937637a1 | barabanme/pythonhillel | /practic-30-2018.py | 3,017 | 3.53125 | 4 | import itertools
import logging
# Formated Out
a = 2
asd = f"{a}"
print(asd)
###############################################################
var_1 = input("Var_1:")
var_2 = input("Var_2:")
def check_int(var):
try:
tmp = int(var)
return True
except ValueError:
return False
if check_i... |
393f2076b91c9dc16d08d66534042cd4ca545b58 | Nithin-rep/Python | /string_basic_operations.py | 345 | 4 | 4 | def method(new_string):
upper_case=new_string.upper()
print(upper_case)
Lower_case = new_string.lower()
print(Lower_case)
split1 = new_string.split("_")
print(split1)
split2 = new_string.split(" ")
print(split2)
print("indexing", new_string[::1])
method( inp... |
060c880167b1e28a10cb7c1a0afe6e6c1d1c4be7 | TravisMoleski/ObjectFollow | /PID.py | 2,033 | 3.53125 | 4 | from threading import Thread
import time
import threading
class PID:
"""
Discrete PID control
"""
def __init__(self, P=2.0, I=0.0, D=1.0, Derivator=0, Integrator=0, Integrator_max=500, Integrator_min=-500,set_point = 0,value = {}):
self.value = value
self.Kp=P
self.Ki=I
self.Kd=D
self.Derivator=Derivat... |
8c725a7a053e8d451f67792cf20d1f4c986678d0 | noisegain/Algorithms_and_DS | /python/sort/merge_sort.py | 586 | 3.546875 | 4 | # merge sort with cnt of inversions
def merge(a, b):
rev = i = j = 0
c = []
while i < len(a) or j < len(b):
if i == len(a) or (j != len(b) and b[j] < a[i]):
c.append(b[j])
j += 1
else:
c.append(a[i])
rev += j
i += 1
return c, r... |
6f2e84f470f4b95386caa347ba3f98a6c34b662a | Marian4/Praticando-python | /Exercício funções/Questão6.py | 286 | 3.609375 | 4 | def AM(horas,minutos):
if horas > 12:
horas -= 12
minutos = minutos
else:
horas = horas
minutos = minutos
return horas,minutos
hora = eval(input("hora:"))
minuto = eval(input("minuto:"))
h,m = AM(hora,minuto)
print("Converso\n P.M - %i:%i\n A.M - %i:%i "%(hora,minuto,h,m)) |
80e8927d83d48e930a96ac9d6a2efcd06904fee8 | Marian4/Praticando-python | /Exercício funções/Questão5.py | 273 | 3.5 | 4 | custo = eval(input("qual o custo do item(R$)?"))
taxaImposto = eval(input("qual a taxa do imposto(%)?"))
def somaImposto(custo,taxaImposto):
custoTotal = custo +((custo/100)*taxaImposto)
return custoTotal
print("o custo total de R$%.2f"%somaImposto(custo,taxaImposto)) |
0880f00fcc0cda49c2cbd4de54e5ed0969156f3b | MYadnyesh/Aatmanirbhar_program | /Week 1/add.py | 512 | 4.15625 | 4 | #Program 1:- Addition of 2 numbers
def add(x,y):
print("The addition is : ")
return x+y
while True:
print(add(int(input("Enter 1st number: ")),int(input("Enter 2nd number: "))))
a=input("Do you want to continue (Press Y to continue)")
if(a=='y' or a=='Y') is True:
continue
else:
... |
b45735562a84f066be681ba592a610118e6da06c | MYadnyesh/Aatmanirbhar_program | /Week 1/primeIntr.py | 633 | 4.1875 | 4 | #Program 2 :- To print all the Prime numbers in an given interval
lower = int(input("Enter a starting number"))
upper = int(input("Enter a ending number "))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num ... |
8d9867e541bdcf3401bd36179b6e25f09aa55965 | Leticiamkabu/python | /globalexe2.py | 173 | 4.125 | 4 | import math
r = int( input("Enter your radius:"))
pi = math.pi
sa = 4 *(pi)*(r**2)
print("surface area is :",sa)
vs= 4/3 * pi *r*r*r
print("vlume of a sphere is :",vs)
|
7f766d2cb1b7523e8f414ebeb025e0a474980935 | ECS153/final-project-group-7 | /babychain/backend/sat.py | 3,038 | 3.78125 | 4 | import random
from pysat.solvers import Solver
class Sat:
@staticmethod
def generate_problem(num_vars: int = 3, num_clauses: int = 10) -> str:
"""
Generates and returns a SAT problem in kCNF form, where k=self.num_vars
Parameters:
num_vars: number of unique variables
... |
92b7f25f4ed592029eb50df944cc0d89466ce9fd | alchemistsdaughter/creating_quality_code | /peer-graded_assignment1/a1.py | 1,962 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 9 15:03:48 2018
@author: anna.whitehouse
"""
import math
def num_buses(n):
""" (int) -> int
Precondition: n >= 0
Return the minimum number of buses required to transport n people.
Each bus can hold 50 people.
>>> num_buses(75)
2
>>> num_b... |
a177115cde3a19cf9e2397aa844610b5a62ffb0c | CIS123Sp2020A/extendedpopupproceed-tricheli | /main.py | 614 | 4.21875 | 4 | #Tenisce Richelieu
from tkinter import
import tkinter.messagebox as box
#The first step after imports is crate a window
window = Tk()
#This shows up at the top of the frame
window.title('Message Box Example')
#create the dialog for the window
def dialog():
var = box. askyesno('Message Box', 'Proceed?')
if ... |
da51d17fe485cb16671cdb00458a70522f0ae0bf | nuzzle000/Alvl_Project | /Sort_Search_Sandbox.py | 3,888 | 4 | 4 |
data = []
def resetdata():
global data
data = []
import random
num = int(input("How many data items?"))
data = []
for i in range (0,num): #create array with user length
x = random.randint(0,1000) #range of values
data.append(x) #adding value(s) to array
... |
9b43fd64192698a1402e0d19d1e1661859c45366 | lovekobe13001400/pystudy | /py-cookbook/1.数据结构和算法/1.18映射名称到序列元素.py | 2,260 | 3.609375 | 4 | from collections import namedtuple
Subscriber = namedtuple('Subscriber',['addr','joined'])
Subscriber = namedtuple('Subscriber2',['addr','joined'])
#Subscriber2 可以理解类实例,但是又可以跟元组类型一样可交换,支持所有的普通元组操作,比如索引和解压。 比如:
sub = Subscriber('jonesy@qq.com','2019-01-01')
a,b = sub
print(a,b)
'''
命名元组的一个主要用途是将你的代码从下标操作中解脱出来。... |
e8421d43ad9e9dfce0819604bd87a5ca542e5f5f | lovekobe13001400/pystudy | /date_study.py | 522 | 3.578125 | 4 | from datetime import datetime
from datetime import timedelta
#1.datetime.now()返回当前日期和时间,其类型是datetime。
now = datetime.now()
#2.转时间戳
now_stamp = now.timestamp()
#3timestamp转换为datetime
now_date = datetime.fromtimestamp(now_stamp)
#4.str转换为datetime
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H... |
5efa370c0a115f4189aec0eb59ef5d8e45b9ccb7 | lovekobe13001400/pystudy | /哈希.py | 2,367 | 3.859375 | 4 | '''
哈希表的定义:
哈希存储的基本思想是以关键字Key为自变量,通过一定的函数关系(散列函数或哈希函数),计算出对应的函数值(哈希地址),以这个值作为数据元素的地址,并将数据元素存入到相应地址的存储单元中。
查找时再根据要查找的关键字采用同样的函数计算出哈希地址,然后直接到相应的存储单元中去取要找的数据元素即可。
'''
#实现哈希表(线性地址再散列)
def ChangeKey(key,m,di):
key01 = (key+di)%m
return key01
def chainHash(InputList):
res = {}
for line in I... |
c71778d278dc8123fca59857375d05880e304b98 | lovekobe13001400/pystudy | /py-cookbook/7.函数/5-6-7.定义有默认参数的函数.py | 1,338 | 3.640625 | 4 | def spam(a,b=42):
print(a,b)
spam(1)
spam(1,2)
#如果你并不想提供一个默认值,而是想仅仅测试下某个默认参数是不是有传递进来,可以像下面这样写:
#因为不传值
_no_value = object()
def spam(a,b=_no_value):
if b is _no_value:
print('no value come in ')
spam(1,None)
spam(1)
#匿名函数
add = lambda x,y:x+y
add(2,3)
#运用
names = ['a','dav... |
303915e17b0044f68f042ef834e4e4094d3b69f2 | lovekobe13001400/pystudy | /py-cookbook/5.文件与iO/13.获取文件夹中的文件列表.py | 489 | 3.546875 | 4 | import os
names = os.listdir('../')
print(names)
#过滤
names = [name for name in os.listdir('../') if os.path.isfile(os.path.join('../',name))]
dirnames = [name for name in os.listdir('../') if os.path.isdir(os.path.join('../',name))]
print(dirnames)
#对于文件名的匹配
import glob
pyfiles = glob.glob(... |
3751d4f3b1af6ba5a2dc69cc5d38e2e5128e87be | lovekobe13001400/pystudy | /py-cookbook/1.数据结构和算法/20.py | 500 | 3.578125 | 4 | a = {'x':1,'z':3}
b = {'y':2,'z':4}
from collections import ChainMap
c = ChainMap(a,b)
#现在假设你必须在两个字典中执行查找操作(比如先从 a 中找,如果找不到再在 b 中找)。
# 一个非常简单的解决方案就是使用 collections 模块中的 ChainMap 类。比如:
print(c['x'])
print(c['y'])
print(c['z'])
#方法2
a = {'x': 1, 'z': 3 }
b = {'y': 2, 'z': 4 }
merged = dict(b)
merged.upd... |
6b0687e02deb21f5c94bbd7521ecadbc94eb6f07 | parulbaweja/wikiracer | /graph.py | 3,497 | 3.609375 | 4 | from queue import Queue
from wiki import wiki_request
import fetcher
import asyncio
import sys
class WikiGraph(object):
"""
A Wikipedia page and its outlinks stored as a graph.
"""
def __init__(self, is_source=True):
self.graph = {} # stores links for all topics
... |
8bf1ca8087a06503da73cb9241b340a96d2bd681 | gpioblink/dbmanage-git | /dice.py | 308 | 3.875 | 4 | import random
print("What is your name?")
name = input("> ")
print("Hello,", name + "!")
print("Rolling the dice...")
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
print("Die 1:", die1)
print("Die 2:", die2)
print("Die 3:", die3)
print("Total value:", die1 + die2 + die3) |
c51eadfd535bfb7f4ddbe531c73762c948d30050 | YulongWu/AlgoExercise_CPP | /leetcode/2016/14_LongestCommonPrefix.py | 2,453 | 3.5625 | 4 | import sys
class Solution(object):
'''
runtime: 56ms only beats 24.12%
'''
def commonPrefix(self, str1, str2):
i = 0
for i, c in enumerate(str1):
if i == len(str2) or c != str2[i]:
break
else:
return str1
return str1[0:i]
def lo... |
add393354db633c7da68ce701f6f327c92754b9a | YulongWu/AlgoExercise_CPP | /leetcode/2016/25_reverseKGroup.py | 2,062 | 3.765625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not h... |
377627ef67813cb37ed25b17cf56f7a8943a50a0 | YulongWu/AlgoExercise_CPP | /SwordForOffer/11_Pow.py | 640 | 3.984375 | 4 | import sys
def pow_(x, a):
if x == 0:
if a < 0:
raise Exception("Illegal Exception")
else:
return 0
if a == 0:
return 1
if a < 0:
return 1.0 / pow_(x, -a)
if x < 0 and a & 1 != 0:
return -pow_(-x, a)
x = abs(x)
if a == 1:
... |
f6aed0e0b5e38e97a0071dfdde9ca6124d137319 | nguyenuy/adventofcode2018 | /day02/checksum.py | 1,801 | 3.96875 | 4 | #!/usr/bin/env python
from collections import Counter
import difflib
day = 2
file_name = "input.txt"
def process_input():
with open (file_name, "r") as input_file:
input = input_file.readlines()
total_two = 0
total_three = 0
for i in input:
count = dict(Counter(i))
exactly_t... |
f1ae2f5e1f8fe3372a55deb18ea2a0507600fec7 | etlundquist/cousins | /FindCousins.py | 5,874 | 4.1875 | 4 | class Family(object):
def __init__(self, founder):
"""
Initialize with string of name of oldest ancestor
"""
self.names_to_nodes = {}
self.root = Member(founder)
self.names_to_nodes[founder] = self.root
def set_children(self, mother, list_of_children):
... |
3e2f0e953f0da8b739bde088930a93c20c5dcd35 | Jamespatterson789/spikes | /python/main.py | 1,346 | 3.703125 | 4 | import random
# this is a comment
def run_test_1():
# integer
foo = 1
bar = 2
baz = (foo + bar)
# float
mcztest = 3.5
# string
string = "hello world"
# list
container = [foo, bar, baz, string]
# string
total = ""
for jimmy in container:
# jimmy is the re... |
3e3e2b58a7de2e5476c5263bda43e797d836bc51 | chenj209/acm | /big_num_practice.py | 4,005 | 3.546875 | 4 | MAX_LEN = 10
DEBUG = 1
def debug_log(*msg, flag=True):
if DEBUG and flag:
print(*msg)
def clear_num(digits_lst):
assert(len(digits_lst) == MAX_LEN)
for i in range(MAX_LEN):
digits_lst[i] = 0
def read_num(num_str):
"""
reads a string representing a number and store it in
a array... |
d625e1281292b5111a2387c83179662dcee3690a | Rishabh450/PythonConcepts | /mutability.py | 807 | 4.125 | 4 | friends_last_seen ={
'name': 'Rishabh',
'id': 15
}
print(id(friends_last_seen))
friends_last_seen ={
'name': 'Rishabh',
'id': 15
}
print(id(friends_last_seen))
# mutable object, when dictionary is passed in argument the change occus
# in same memory location same object, be careful this can be dangerou... |
feed24d4e7abcfdb7c8e5ab225c1c28b7fea25c4 | Tessmore/code-jams | /2016/revenge-of-the-pancakes/main.py | 2,567 | 3.546875 | 4 | """
Revenge of the Pancakes: https://code.google.com/codejam/contest/6254486/dashboard#s=p1
The Infinite House of Pancakes has just introduced a new kind of pancake! It has a happy face made of chocolate chips on one side (the "happy side"), and nothing on the other side (the "blank side").
You are the head waiter o... |
5400dd3f942d281a61eb7758cdda198d9af3739b | surajnikam21/simplePatterns.py | /demo/work.py | 748 | 4 | 4 | def student():
student = {}
student["Name"] = input("Name: ")
student["Age"] = input("Age: ")
student["Course"] = input("Course: ")
student["City"] = input("City: ")
print(type(student))
return student
#students = student()
# with open('students.txt', 'a') as f:
# f.write(students.__st... |
c0679eaacf8b8e31f329cf4ff8c829510e237719 | surajnikam21/simplePatterns.py | /basic/4loops.py | 1,199 | 4 | 4 |
message = 'This is learning: session of Python'
words = message.split(':')
print(words) # []
print(len(words)) #2
message = 'This is learning session of Python'
words = message.split(' ')
print(words) # []
print(len(words)) #6
message = 'apple, orange, papaya, banana, kiwi'
fruits = message.split(',') #list
pri... |
99dbdf5273d32350e7a7186cfeb2dca59819bbae | surajnikam21/simplePatterns.py | /basic/3conditions.py | 618 | 4.25 | 4 | #if else
num1 = 2
num2 = 3
if (num1 == num2):
print('Equals')
else:
print('Not Equals')
# multi if elif els
if(num1 != num2):
print('Not Equal')
elif(num1 == num2):
print("Equals")
elif(num1 > num2 ):
print("num1 > num2")
else:
print("some data")
str1 = 'Suraj'
str2 = 'suraj'
if(str1== st... |
91e0309aa6ba666f9feaf2b63efd1d81f56078c0 | mahimaupadhya/Hackerrank | /Python/SetIntersection().py | 161 | 3.515625 | 4 | enf=int(input())
eng_set=set(map(int,input().split()))
french=int(input())
french_set=set(map(int,input().split()))
print(len(eng_set.intersection(french_set)))
|
fb5befb185dc9b4d98b2ca20e6599eefac88d214 | ziepio/ATM_project_ | /atm.py | 576 | 3.84375 | 4 | '''Cash machine allows to:
-> withdraw cash
-> setup new pin number
'''
from atm_card import Card
class Atm(Card):
def withdraw_cash(self, sum):
if self.__balance >= 0 and self.__balance >= sum > 0:
self.__balance = self.__balance - sum
return True
else:
... |
db3b9930b4bdd50b52346f517393858543df7e45 | YolandaLin/3rd-ML100Days | /homework/D100_D1HW.ipynb | 2,514 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
作業1:
# In[1]:
# 載入基礎套件與代稱
import numpy as np
import matplotlib.pyplot as plt
# In[10]:
import numpy
def mean_absolute_error(y, yp):
"""
計算 MAE
Args:
- y: 實際值
- yp: 預測值
Return:
- mae: MAE
"""
mae = MAE = sum(abs(y -... |
95cd03ef51707c7e716ff13084a665b3c37edc03 | Bryalle90/cs456-project2-huffman | /pr2.py | 4,659 | 3.578125 | 4 | # Student: Bryan Allen
# Class: CS456 Spring 2015
# Assignment: Project 2
# Required Files: alphabet.txt
# To Run: navigate to folder containing pr2.py in console/terminal and enter: python pr2.py
import os, sys, math, collections
class HuffNode(object):
def __init__(self, c, f, l=None, r=None):
self.character = c... |
05fb019e4ee405d01c884c8436c8309caf55c1b3 | laisy/run.codes-questoes | /Interseção de Conjuntos.py | 211 | 3.546875 | 4 | x = input()
y = input()
contador = 0
for k in range(len(x)):
for n in range(len(y)):
if x[k] == y[n]:
contador += 1
print 'As listas tem', contador, 'elementos em comum.'
|
f96811ed38ed0bfa5ce8e7023b69cf4ee02c758b | brentholmes317/Dungeon_Fatality | /Dungeon_Fatality.py | 8,670 | 3.828125 | 4 | from sys import exit
#This array keeps track of various things that get turned on throughout the game
#the zeroeth slot is if the person found the wings
#the first slot is if the person found the gun
#the second slot is if the person found the gold answer
#the third slot is if the person found honey
#the fourth slot s... |
812d4e19e22d63637f905d9269cf2ea2e610b088 | aalto-speech/wdecoder | /scripts/triphonize.py | 394 | 3.640625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
def triphonize(letters):
triphones = []
for i in range(1, len(letters)-1):
triphones.append("%s-%s+%s" % (letters[i-1], letters[i],
letters[i+1]))
return triphones
for wrd in sys.argv[1:]:
letters = list("_" + wrd + "_")
triphones = ... |
3a044398c5fb368d2edb737c4a2e23ef1d8b592e | jamesmontalvo3/IntroToAlgorithms | /Quicksort/Quicksort.py | 3,979 | 3.890625 | 4 | #!/usr/bin/env python
from random import randint
from math import floor
from sys import setrecursionlimit
setrecursionlimit(10000)
def myQuicksort( sortarray=None, start = 0, end = -1, pivotType=None ):
# deliberately long name for global var
global myQuicksortArray
global myQuicksortComparisons
# sortarray w... |
6931f5cae098f81057215ba2b13b59047d1f3658 | haskellstudio/college-coursework | /B351/hw1/p1.py | 3,107 | 3.71875 | 4 | #Extra Credit
class MyGraph:
OUTSIDE = 'U'
BATTERY = 45
def __init__(self):
self.adj = {}
#build() : Edges -> Void
#Builds the adjacency dictionary with values
# being a list of adjacent vertices in the same
# order they were encountered in edges set.
def build(sel... |
3db02a9f4f5d2a88eb8068f7304ef7e8e2028c61 | thangpro1242002/thangpro1242002 | /bai8.py | 407 | 3.59375 | 4 | x = input("địa chỉ email muốn gửi thư: ")
y = input("thông điệp gửi thư: ")
z = input("số lần gửi thư: ")
answer=1
n=int(input("nhập vào số lần lặp: "))
while answer <= n:
answer=answer+1
print("địa chỉ email muốn gửi thư: ",x)
print("thông điệp muốn gửi thư: ",y)
print("số lần ... |
68e08f95632d47c27d72359612bec67fb3b36367 | JayMass718/python-challenge | /python-challenge/pypoll/main.py | 2,410 | 3.859375 | 4 | # Incorporated the csv module
import csv
import os
# Files to load and output (Remember to change these)
election_csv = os.path.join(".." "Resources", "election_data.csv")
text = os.path.join(".." "Resources", "election_analysis.txt")
# Candidate
candidate = row[2]
# Total votes
total_votes = 0
# The winner
winning... |
6842cc695fbe233ef1bbc2ac525af0ad68346c68 | dgruen6/shipping_route_mileage_retrieval | /Data_Models/Address.py | 419 | 3.515625 | 4 | from typing import Optional
class Address:
def __init__(self, city: str, state: str, zip_code: str, country: str = None):
self.city: str = city
self.state: str = state
self.zip_code: str = zip_code
self.zip_code_modified: Optional[str] = None
self.country: str = country
... |
21c3f3fa3162d74522428e25a5343e16d2b4161b | weblate/bombard | /bombard/pretty_ns.py | 1,579 | 3.671875 | 4 | """
- time_ns for Python before 3.7
- Elapsed context manager
- pretty_ns to represent time elapsed in human lovable form
Usage:
>>> start = time_ns()
>>> import time
>>> time.sleep(0.0000001)
>>> pretty_ns((start + 100) - start)
'0.1 mks'
>>> with Timer() as timer:
... import time
... time.sleep(0.0000001)
.... |
22478901521148db39cdd6b8c336b7e583e083d3 | turksoyomer/TicTacToe-AI | /codes/game.py | 1,318 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@author: turksoyomer
"""
from tictactoe import TicTacToe
from minimax import MiniMax
from alphabeta import AlphaBeta
from qlearning import QLearning
import time
game = TicTacToe()
user = int(input("Player1(X) or Player2(O):"))
ai = 2 if user == 1 else 1
ai_algorithm = input("""Choose your ... |
b25b852d98c0db3598ab016050ef30b6b57711a2 | afcarl/simple-aco | /ant.py | 3,610 | 3.890625 | 4 | from agent import Agent
from random import uniform
import settings
class Ant(Agent):
FORWARDS = 0
BACKWARDS = 1
def __init__(self, world, location, direction = None):
super(Ant, self).__init__()
self.world = world;
self.direction = direction or self.FORWARDS
self.history = [] ... |
4b6e701e58025fb765ec485142eee221ee4c419c | jeronimofjr/Object-Oriented-Programming-OOP-in-Python | /Projetos/carro/carro.py | 1,910 | 3.6875 | 4 | class Car:
def __init__(self, gas, gasMax, passg, passMax, km):
self.gas = gas
self.gasMax = gasMax
self.passg = passg
self.passMax = passMax
self.km = km
def in_(self):
if self.getPass() == self.getPassMax():
return 'fail: limites de pessoas atingido... |
c365f42bf2d0fa7af3c0165c1afcaf9a0a69e22e | kangah-codes/fade | /fading.py | 1,990 | 3.875 | 4 | __author__ = "Joshua Akangah"
import pygame
#screen = pygame.display.set_mode((600, 500))
pygame.init()
class FadingText():
def __init__(self, text, color, size, fadespeed):
"""
params:
text: Text to render
color: Color to render text in RGB format
size: Size o... |
b2d5f118ef9e0e5a2965eabf671d16fd3248d52f | ehteshamkaushik/Python_Practice | /sum of series.py | 110 | 3.671875 | 4 | n=int(input())
sum=0
for i in range(1,n+1,1):
for j in range(1,i+1,1):
sum=sum+j*j
print(sum)
|
7ec354d8ac91bc2583ceccddf9da2cc60c089b18 | ehteshamkaushik/Python_Practice | /prime 2.py | 234 | 3.625 | 4 | def prime_number(n):
sq=int(n**.5)
flag=1
for j in range (2,sq+1,1):
if n%j==0:
flag=0
break
if flag==1:
print(n)
n=int(input())
for i in range(2,n+1,1):
prime_number(i)
|
92acbf864eb8536232cd3deb7ca5922dd403eb24 | ehteshamkaushik/Python_Practice | /input list.py | 130 | 3.546875 | 4 | def input_list(n):
lst=[]
while n>0:
lst.append(int(input()))
n-=1
print(lst)
n=int(input())
print(input_list(n))
|
16ec55c09644e53e0bfe1e693e08db18040b0fb6 | ehteshamkaushik/Python_Practice | /pattern.py | 164 | 3.640625 | 4 | n=int(input())
for i in range(1,n+1):
for k in range(1,n-i+1,1):
print(end=' ')
for j in range(1,2*i,1):
print(j,end=' ')
print()
|
4b5f784d5378020d66a197195c70df2e72e629d0 | ehteshamkaushik/Python_Practice | /list sum.py | 133 | 3.640625 | 4 | def sum_list_1(a):
_sum=0
for num in range(len(a)):
_sum=_sum+int(a[num])
return _sum
a=list(input())
print(sum_list_1(a))
|
c5024b025ca57f8e3d36c4cb690c4e722c2190eb | zkurtz/emstats | /emstats/hiddencoins.py | 5,494 | 3.78125 | 4 | import numpy as np
import pandas as pd
class Simulation:
''' Simulate a process of randomly selecting one of N coins, flipping the
selected coin a certain number of times, and then repeating this a few times
'''
def __init__(self,
n_sequences=10,
n_reps_per_sequence=7... |
d251c01650c960e33c1414cbba09e7ec68b12d39 | KenOtis/Rock-Paper-Scissors-Game | /RockPaperScissors.py | 1,343 | 4.15625 | 4 | import random
import time
def main():
a=["rock","paper","scissors"]
go="yes"
print("\nLets play Rock, Paper, Scissors! \nBest of 3 wins.")
computer=0
user=0
while (computer<2 or user<2 ):
b=(random.choice(a))
choice=input("Your choice: ")
time.sleep(2)
... |
620320c030d29620cc08e29f468bf74e586fa164 | danielsamuels/advent-of-code | /year_2022/day_9.py | 2,165 | 3.71875 | 4 | Position = tuple[int, int]
Positions = list[Position]
PositionHistory = list[Positions]
def move_head(head: Position, direction: str) -> Position:
# Get the current position and apply the movement to the head.
head_x, head_y = head
return (
head_x + (1 if direction == 'R' else -1 if direction == '... |
f3376b0e86f74a0697b815180718ebf662355218 | cloudmesh/cloudmesh-common | /cloudmesh/common/security.py | 403 | 3.59375 | 4 | import random
import string
def generate_strong_pass():
"""
Generates a password from letters, digits and punctuation
:return: password
:rtype: str
"""
length = random.randint(10, 15)
password_characters = \
string.ascii_letters + \
string.digits + \
string.punctua... |
216be4268b9645ea13b8ac7a80b731c96036860b | bhokansonfasig/Project_Euler | /problem012.py | 1,418 | 3.6875 | 4 | from problem003 import partial_factorize
from math import factorial
import sys
def all_divisors(number):
divisors = [1]
for i in range(2,number+1):
if number%i==0:
divisors.append(i)
return divisors
def num_divisors(number):
if number==1:
return 1
factors = partial_fact... |
36524c740f77855aa04906a0bb248cf4ea08ade5 | bhokansonfasig/Project_Euler | /problem003.py | 1,275 | 3.984375 | 4 | from math import sqrt
def generate_primes(maximum):
primes = [2]
for number in range(3,maximum+1):
add_to_primes = True
for prime in primes:
if number%prime==0:
add_to_primes = False
break
if add_to_primes:
primes.append(number)
... |
c8b0ccf1c5626cf5fd1eff4e05457b42f8c3c3c1 | bhokansonfasig/Project_Euler | /problem005_2.py | 490 | 3.859375 | 4 | from problem003 import full_factorize
if __name__ == '__main__':
number = 1
for i in range(2,21):
if number%i!=0:
number = number*i
print(number)
for i in range(2,21):
print(number,"divisible by",i,number%i==0)
factors = full_factorize(number)
print(factors)
for ... |
356d34ec3290b758dd3812e71d10bd1f220096a0 | bhokansonfasig/Project_Euler | /generate_prime_table.py | 433 | 3.65625 | 4 | import sys
maximum = int(sys.argv[1])
primes = [2]
for number in range(3,maximum+1):
add_to_primes = True
for prime in primes:
if number%prime==0:
add_to_primes = False
break
if add_to_primes:
primes.append(number)
print("Done generating table, now writing...")
tab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.