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 |
|---|---|---|---|---|---|---|
aed6b57c7b9c1c9ec63cb0d2bb96723adc72934f | chyidl/chyidlTutorial | /root/os/DSAA/DataStructuresAndAlgorithms/python/greedy_algorithms_huffman_code_implement.py | 5,741 | 3.75 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# greedy_algorithms_huffman_code_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for th... |
a06208c839a3331629c2116f667e73a693dc62a9 | chyidl/chyidlTutorial | /root/os/DSAA/DataStructuresAndAlgorithms/python/sort_selection_array_implement.py | 1,878 | 4.34375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sort_selection_array_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the status q... |
0ddee11f59b5d1624fa880016512ec8d57733980 | chyidl/chyidlTutorial | /root/mldl/RequirementTutorial/OpenCV/PracticalPythonOpenCV/canny.py | 1,370 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Canny Edge Detection is a popular edge detection algorithm. It was developed by John F.Canny in 1986. It is a multi-stage algorithm algorithm and we will go through each stages.
1. Noise Reduction
Since edge detection is susceptible to noise in the image, fi... |
ff6d2042f3b7b1f12d73adcad947680d0eb03af6 | chyidl/chyidlTutorial | /root/os/DSAA/DataStructuresAndAlgorithms/python/queue_array_implement.py | 3,208 | 4.28125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# queue_array_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the status quo.
# You... |
1733f01506436cde4ecae459fcd153806bb056eb | chyidl/chyidlTutorial | /root/python/PythonTutorial/Py3CookBook/ch01/1.18.Mapping_Names_to_Sequence_Elements.py | 2,411 | 4.0625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 1.18.Mapping_Names_to_Sequence_Elements.py
# ch01
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the s... |
86f11ce0f384e309f90c2da3056f4ea4e60c1acd | chyidl/chyidlTutorial | /root/python/PythonTutorial/Py3CookBook/ch01/1.3.Keeping_the_Last_N_Items.py | 1,933 | 3.53125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 1.3.Keeping_the_Last_N_Items.py
# ch01
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the status quo.
... |
050f0109629ee4062f1c35e9412d49310b7847fa | chyidl/chyidlTutorial | /root/python/PythonTutorial/Py3CookBook/ch01/1.13.Sorting_a_List_of_Dictionaries_by_a_Common_Key.py | 1,688 | 3.59375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 1.13.Sorting_a_List_of_Dictionaries_by_a_Common_Key.py
# ch01
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respe... |
1b41ab2485c1417978c41cfa004729c05506e5e5 | chyidl/chyidlTutorial | /root/python/PythonTutorial/Template/socket_client_thread_sample/socketclientthread.py | 5,295 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Simple socket client thread smaple
"""
1. Doing the I/O in a separate thread
2. Using asynchronous I/O with callbacks integrated into the GUI event loop
"""
import socket
# struct -- Interpret bytes as packed binary data
import struct
import threading
# queue -- A synchro... |
7d15c9730c3eaa0547bcc05433c46ca8aa8d85d3 | chyidl/chyidlTutorial | /root/python/PythonSourceCode/concurrent.futures/examples/futures_thread_pool_submit.py | 811 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Scheduling Individual Tasks
Schedule an individual task with an executor using submit(), and use the Future
instance returned to wait for that task's results.
"""
from concurrent import futures
import threading
import time
def task(n):
print("{}: sleeping {}".for... |
3b2d4f6855512f17e98d393348cdf39f855ab739 | lstobie/CP1404_practicals | /prac_03/ASCII.py | 612 | 4.125 | 4 | def main():
LOWER_LIMIT = 33
UPPER_LIMIT = 127
char = input("Enter a character: ")
print("The ASCII code for {} is {}".format(char, ord(char)))
cord = int(input("Enter a number between {} and {}: ".format(LOWER_LIMIT, UPPER_LIMIT)))
if LOWER_LIMIT <= cord <= UPPER_LIMIT:
print("The chara... |
3fc55ab4e04a4793eff5827ae4033c0f2a25fbe2 | lstobie/CP1404_practicals | /prac_01/Electricity Bill.py | 388 | 4 | 4 | """Electricity bill estimator
Enter cents per kWh: 35
Enter daily use in kWh: 4.5
Enter number of billing days: 90
Estimated bill: $141.75 """
def e_bill_est():
ckwh = float(input("cost per kWh: (cents)"))
daily_kw = float(input("daily use of kWh: "))
billing_days = int(input("Enter number of billing days... |
fa831333ccba3c9f683f4388160af0e640655d1b | bluisalima/Solyd-Python | /aula5.py | 548 | 4.28125 | 4 | ''' Exercício - Aula 5: Faça um programa que leia a quantidade de pessoas que serão convidadas para uma festa.
Após isso o programa irá perguntar o nome de todas as pessoas e colocar numa lista de convidados.
Imprima todos os nomes da lista.
'''
numero_convidados = input("Número de pessoas convidadas: ")
convidados = ... |
73f23cf9b45eb8d79ac80004d83855dd0f4f3d82 | lzl813/Python_dataming | /爬虫/01/db.py | 2,930 | 3.796875 | 4 | import sqlite3 as sq
import sys
class Manger:
def main(self):
print("*****欢迎使用名片管理系统*****")
print("输出你想要做的事")
print("1 添 加 用 户")
print("2 删 除 用 户")
print("3 查看所有用户")
print("4 修改用户信息")
print("5 查 看 用 户")
print("6 退 出")
num = input("输入您的选择... |
f607d1a6bb37486172a511d848657e146b3b104d | lzl813/Python_dataming | /python01/02/02.py | 412 | 4.25 | 4 | #创建列表
a = list("abc")
print(a)
#替换指定序列
a[1] = "5"
print(a)
#删除一个序列
del a[1]
print(a)
#追加
a.append("def")
print(a)
#链表的添加
a.extend(a)
print(a)
#链表的插入
a.insert(2,"kf")
print(a)
#删除指定序列的对象
a.pop(2)
print(a)
#链表的复制
s = a.copy()
print(s)
#链表的反转
s2 = a.reverse()
print(s2)
#链表排序
s3 = [2, 3, 4, 0]
s3.sort()
print(s3) |
b9e4b98ae8d205b6c2636b7f94aa872db11a8c63 | zoharbou/IML | /ex2/ex2.py | 3,926 | 3.546875 | 4 | # imports:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
to_drop = ['date']
data_file_name = r'kc_house_data.csv'
# the data set
df = pd.read_csv(data_file_name)
def clean_data():
"""
cleans the data from unused columns.
:return: the prices of the houses by their id
"""
d... |
03110cf67b75ea1b43daa7df1bea22e1a9b424b4 | lucasdantas2014/Python | /Exercicios2Bim-master/exercicioProva2Bim/Questao24-Estrutura-de-Repeticao.py | 184 | 3.875 | 4 | notas=eval(input("Digite as notas:"))
soma = 0
contador = 0
for n in notas:
soma = soma + n
contador = contador + 1
media = soma / contador
print("A media das notas é:",media) |
1e9cc7ad660619ca0af3805aee16e7de8d7406b4 | lucasdantas2014/Python | /Exercicios-Dicionario-master/Questão1.py | 610 | 3.75 | 4 | semana = {}
def adicionarDia(posicao, dia):
semana[posicao] = dia
def exibirDias(dias):
dias = semana.items()
for dia in dias :
print(dia[0],dia[1])
while (True):
print("Opções:\n 1-Adicionar Dia \n 2- Exibir Dias")
escolha = int(input("Digite o número correspondente ao que desejas executar: "))
i... |
ff9b508c66ec2aa321a68235409b5d01c4517646 | lucasdantas2014/Python | /Exercicios2Bim-master/exercicioProva2Bim/Questao19-Estrutura-de-Repeticao.py | 830 | 3.890625 | 4 | #VAriaveis
valores=eval(input("Digite uma lista de numeros:"))
soma = 0
loop1 = 0
teste = True
#Repetiçao para teste de confirmaçao da condiçao
for n in valores:
if(n < 0 or n > 1000):
teste = False
#Teste da Condiçao
if(teste == True):
#Comandos se a condição der verdadeira
for x in valores:
i... |
52a5050e6c9a85775dea0b08fbd2281c24e24f99 | lucasdantas2014/Python | /Exercicios2Bim-master/exercicioProva2Bim/Questao11-Estrutura-de-Repeticao.py | 466 | 3.96875 | 4 | valorI=eval(input("Digite o valor inicial do intervalo:"))
valorF=eval(input("Digite o valor final do intervalo:"))
if (valorI <= valorF):
intervalo = valorI + 1
soma = 0
while(intervalo < valorF):
print(intervalo)
soma = intervalo + soma
intervalo = intervalo + 1
print("O result... |
3170ec830a0f5ed015494cd3ff0226b073b4fd06 | jordanlaforest/simple-blackjack | /blackjack.py | 5,142 | 3.578125 | 4 | import random
import time
#Constants
CPU_SLEEP_TIME = 1.5 #How much time the cpu takes to do actions
NUM_DECKS = 2
def main():
if(NUM_DECKS == 1):
plural = ""
else:
plural = "s"
print "Play blackjack until you run out of cards from " + str(NUM_DECKS) + " deck" + plural + "."
print "Try to turn your $500 into ... |
1c758f299bb0715525837378154b393a9808dd1d | DanielaRod/DanielaRod.github.io | /PedraPapelTesoura.py | 933 | 3.796875 | 4 | from random import randint
t = ["Pedra", "Papel", "Tesoura"]
computer = t[randint(0,2)]
player = False
while player == False:
player = input("Pedra, Papel, Tesoura?")
if player == computer:
print("Empatado!")
elif player == "Pedra":
if computer == "Papel":
print("Perdeste!",... |
391caebfcc3dfb23bd7841af355aec2d8635bca7 | DAVIDJJX/Python_self_practice | /quiz2.py | 465 | 3.84375 | 4 | name=input('pick up name for file:')
f=open(f'{name}file.txt','w+')
nums = list()
cnt = 1
# Take in numbers
while True:
entered = input(f"Enter the {cnt} number, or enter f when you are finished: ")
cnt += 1
if entered == 'f' or entered == '':
break
else:
try:
n = float... |
69b1a8d6f2f59a4cc3a1b91aaf58a54468344ce7 | DAVIDJJX/Python_self_practice | /20210806/99recursion.py | 241 | 3.921875 | 4 | ## 99乘法表
def func(a:int,b:int):
c=int(a)*int(b)
print(a,'*',b,'=',c)
if a==1 and b==1:
return c
elif a!=1 and b==1:
print(end='\n')
func(a-1,9)
else:
func(a,b-1)
func(9,9)
|
1d0762eef9a0acf8da8b875ff92e67d6bd5fee57 | kimukook/variable_length_oscillating_pendulum | /asymptotic_control_vector_field.py | 3,488 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pendulum
from pendulum import Pendulum
from functools import partial
from scipy import io
'''
This is a script that generates the vector field of the dynamic of closed-loop control of variable-length pendulu.
After the discretization of the phase space, compute... |
15f6490a99acc0d3ef914242eea74cd93ac1d5eb | Sergii-Lak/OOP_practic | /anagramme.py | 356 | 3.75 | 4 |
a = "weg"
b = "gew"
if len(a) != len(b):
print("Not anagrams")
else:
rep = 'Anagram'
a_list = list(a)
b_list = list(b)
for i in a_list:
if i in b_list:
a_list.remove(i)
b_list.remove(i)
continue
elif i not in b_list:
rep = "Not anagra... |
f51ca6b263f3e41729a4c68fe791c0f75ac6744d | Sergii-Lak/OOP_practic | /practic10.py | 999 | 3.640625 | 4 | def mysplit(strng):
b = []
if strng.isspace() or strng == '':
return b
else:
a = []
m = ''
for i in strng:
if i != ' ':
m += i
else:
if m != '':
a.append(m)
m = ''
return a
... |
4cdfeb03bd1cc05aaa896eb8690e1fde3272e18a | Sergii-Lak/OOP_practic | /OOP_egorof_chanel/practic04_property.py | 837 | 4 | 4 |
class Square:
def __init__(self, s):
self.__s = s
self.__n = None # значение для кеша который хранит уже вычисленный квадрат числа
@property
def get_val(self):
return self.__s
@get_val.setter
def get_val(self, value): # сеттер когда мы вводим или меняем значение сбрасы... |
f22ed8e2658285373f5123825d9a28b319a53d59 | Sergii-Lak/OOP_practic | /oop2.py | 2,390 | 3.578125 | 4 | # Nasledovanie
class Point:
def __init__(self, x = 0, y =0):
self.__x = x
self.__y = y
def __str__(self):
return f"{self.__x}, {self.__y}" # pereopredelenie vuvoda str
class Prop:
def __init__(self, sp:Point, ep:Point, color:str="red", width:int = 1): # dvoetochie tolko rekomendu... |
6c08a79ceca420e9b4966a91a4b83458b03b2dec | WangXiaoCao/TF-Tutorial | /mnist/test/test1.py | 1,291 | 3.734375 | 4 | from tensorflow.examples.tutorials.mnist.input_data import *
import tensorflow as tf
# read data
mnist = read_data_sets("MNIST_data/", one_hot=True)
# create n* 784 placeholder(as the number of factor is 784)
x = tf.placeholder(tf.float32, [None, 784])
# create variables:weight and bias(the initial value is 0)
w = t... |
967bb21482280ffe1eff1b09ee403dcaac27858d | alexpsimone/other-practice | /repls/anagram_finder.py | 2,072 | 4.1875 | 4 | # anagram finder
# write a function that takes two strings and returns whether or not they are anagrams
# abc cab -> true
# abc abc -> true
# abc abd -> False
# '' '' -> True
# abc1 1abc -> True
# abcd abc -> False
# numbers and letters, no spaces, any length strings
def anagram(x, y):
# if the stri... |
63ab7889501a98a5ba49bc7300e0fe11060327d3 | yuki67/OddImageConverter | /main.py | 912 | 3.671875 | 4 | import argparse
from PIL import Image
import OddImageConverter
def prompt():
""" メイン処理 """
# 引数を処理
parser = argparse.ArgumentParser(description="convert image into odd formats.")
parser.add_argument("-l", action="store_true", help="show the formats into which this program can convert.")
parser.add... |
875e3d2299611f15653215d3f3703d73fd7fe8cb | CatLiv/Arabesque | /Rosette2.py | 850 | 3.8125 | 4 | # file: rosetta.py
# https://github.com/jxxcarlson/PyExamples/blob/1bcaea7aec8a3bf31ab3ef2fc05ad844a72a9eb8/rosetta.py
"""Draw rosetta figure using pentagons."""
# Author: J. Carlson, 2/14/2013 @ square-the-circle.com
from turtle import *
fred = Turtle()
fred.speed("fast")
def pentagon(turtle):
for k in... |
bb40fb86a454d0617480ae24c842a1cd91ca9c7c | erijones/phs | /python/intro/prime_finder.py | 1,815 | 4.40625 | 4 | #!/usr/bin/python3
# This program runs as ./prime_finder (with correct permissions), but
# incorrectly! The program's goal is to list the prime numbers below a certain
# number using the Sieve of Eratosthenes, discovered around 200 BC.
# Run the file, and mess around with the testing area below. Debug and
# troublesho... |
376d468e7bce033358224ab78e463787a704d0c5 | NurRozikin/python-labs | /pengenalan-python/continue.py | 127 | 3.59375 | 4 | # Belajar Continue
# Untuk skip ke proses selanjutnya
for i in range(1,100):
if i % 2 == 1:
continue
print(i) |
28b7000c8262e18f1bfc1aea76987c59f775fa30 | salewski/sedbf | /tools/ascii_to_bytes.py | 177 | 4.0625 | 4 | #!/usr/bin/python3
while True:
try:
string = input()
except:
break
for char in string:
print("%03d" % ord(char), end="")
print("")
|
4885d8d60b7b2245f2bc4c8d398a66e26a5620e9 | noehoro/Python-Data-Structures-and-Algorithms | /Recursion/recursiveMultiply.py | 349 | 4.15625 | 4 | def iterative_multiply(x, y):
results = 0
for i in range(y):
results += x
return results
def recursive_multiply(x, y):
# This cuts down on the total number of
# recursive calls:
if y == 0:
return 0
return x + recursive_multiply(x, y - 1)
x = 500
y = 2000
print(x * y)
pri... |
9ea9de95112cbcf5d0c6dc1e87833c67b9602bf1 | prince6635/expert-python-programming | /syntax_best_practices/coroutines.py | 2,417 | 4.1875 | 4 | """
Coroutines:
A coroutine is a function that can be suspended and resumed, and can have multiple entry points.
For example, each coroutine consumes or produces data, then pauses until other data are passed along.
PEP 342 that initiated the new behavior of generators also
provides a full example on ho... |
297be99001229c022c8cdeb10122df55491d401c | zackbrienza/fantasy-football | /sorting.py | 1,399 | 4.1875 | 4 | #Scott Dickson
#Practice writing sorting algorithms
import random
#Also as expected
def quicksort(arr):
n = len(arr)
if n == 1 or n == 0:
return arr
elif n == 2:
return arr if arr[1] > arr[0] else [arr[1],arr[0]]
else:
splitter = arr[random.randrange(n)]
right = []
... |
42f683fe766f18b63b26b435e3e74ebc950e2c4b | anitaokoh/Streamlit_Python_Viz_App | /other_app_py_files/year_wrapup_viz.py | 2,708 | 3.890625 | 4 | import pandas as pd
import plotly
import plotly.express as px
def create_fig(df,emotions_list,emotion_scale, min_content, max_content):
"""
Creates a Plotly cutomized line chart with annotations
Args: The user input, emotion scale measures, and the test received for annotation
Return: A Plotly figur... |
7ca88eb31db15a3c0c55acc2e3ecbafbe7a01ed1 | alancyao/fun-times | /Algorithms/hr.py | 1,195 | 3.828125 | 4 | #!/usr/bin/env python3
import sys
def run_max_subarray():
"""Input:
First line of the input has an integer T. T cases follow Each test case begins with an integer N. In the next line, N integers follow.
Output:
2 space separated integers denoting the maximum contiguous and non-contiguous subarray. At least one... |
98aefb8c8ae08939ef877e268bfc10a54a0be896 | alancyao/fun-times | /Algorithms/reverse_contiguous_subset_to_sort.py | 794 | 4.21875 | 4 | #!/usr/bin/env python3
""" Problem description:
You have an array of n distinct integers. Determine whether it is possible to sort the array by reversing exactly one contiguous segment of the array. For example, 1 [4 3 2] 5 => 1 [2 3 4] 5.
"""
""" Some variables for testing """
possible = [1, 2, 6, 5, 4, 3, 7, 8]
imp... |
33779c38a4abf5e2d11d0062998f2e7feda7adcd | rziemski/389Rfall18 | /week/2/stub.py | 1,844 | 3.625 | 4 | """
If you know the IP address of the Briong server and you
know the port number of the service you are trying to connect
to, you can use nc or telnet in your Linux terminal to interface
with the server. To do so, run:
$ nc <ip address here> <port here>
In the above the example, the $-sign... |
8d9285835d0353ca6628e3d62b857fc066f70357 | xuezhizeng/data-science-projects | /salmon_identification/spotID/my_functions.py | 639 | 3.640625 | 4 | def extract_circles_from_labelme_json(json_path):
'''
Extract center and radious of circles from a json mark file generated with labelme
'''
with open(json_path) as f:
data = json.load(f)
# P1: circle center; P2: point on circle
P1 = [p['points'][0] for p in data['shapes']]
P2 ... |
07abeb9f17b1665d9284596d25ef336343ad7c99 | bgeorg/doublespikePy | /loaddata.py | 1,478 | 3.859375 | 4 |
"""Load data from csv file,
and perform some operations to bring dataframe into shape.
Dataframe is used to feed elemental info to elemental objects later on.
@author: bastian
"""
import pandas as pd
import numpy as np
def read_data():
header_cols = ['element', 'isotope', 'mass', 'standard',
... |
c661ea7839afb9aefdfc5b87fd1c96b546bd3dc1 | Splintr255/computer-programming-1 | /cash_register/cash_register.py | 648 | 3.9375 | 4 | # variables
from decimal import Decimal
taxRate = 0.08
numItems = int(input('Number of items '))
costPerItem = float(input('Cost Per item '))
# calculator
subTotal = numItems * costPerItem
taxAmmount = taxRate * subTotal
totalPrice = subTotal + taxAmmount
# reciept information
print('SALES RECIEPT')
print('\n')
prin... |
c6ec6a2b8a4f67015589478bfbe7729107d5d095 | vikramkumarsj/AdvancedAnalyticsWork | /RNN_Forecasting_Retail.py | 2,321 | 3.765625 | 4 | # Recurrent Neural Network
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the training set
training_set = pd.read_csv('D:/Data/Retail_Soft_Drink_Sale.csv')
training_set = training_set.iloc[:,1:2].values
# Featur... |
cfe9977f7bf5081576ee4a9eccd34f54edf14a60 | nicklambson/pcap | /class/subclass.py | 407 | 3.875 | 4 | class A:
pass
class B(A):
pass
class C(B):
pass
print(issubclass(C,A)) # True
print(issubclass(C,B)) # True
print(issubclass(C,C)) # True
print(issubclass(B,A)) # True
print(issubclass(B,B)) # True
print(issubclass(B,C)) # False
print(issubclass(A,A)) # True
print(issubclass(A,B)) # False
print(issubcl... |
0e0bbc7c9d542fe1967d7b1fdd36cda4548bf5f7 | nicklambson/pcap | /class/subclass2.py | 460 | 4.28125 | 4 | class A:
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
# super().__init__()
A.__init__(self)
# self.a = 2
self.b = 3
# use super() to access the methods of the parent class
# or A.__init__(self)
# use super().__init__() to initialize from the parent cla... |
3123e526b96d7aa2d5eaaa3e22bc676e127f9307 | nicklambson/pcap | /exceptions/which_exception.py | 419 | 4.125 | 4 | '''
try:
raise Exception
except:
print("c")
except BaseException:
print("a")
except Exception:
print("b")
'''
# error: default except: must be last
try:
raise Exception
except BaseException:
print("a")
except Exception:
print("b")
except:
print("c")
# a
try:
raise Exception
excep... |
04c5b113fbbfb7deba4fa06f7da4f584728a33fb | nicklambson/pcap | /class/instance_method_2.py | 325 | 4 | 4 | class A:
A = 1
def __init__(self, v=2):
self.v = v + A.A
A.A += 1
def set(self, v):
self.v += v
A.A += 1
return
a = A()
a.set(2)
print(a.v)
# 5
# a is instantiated
# through __init__, self.v becomes 3 and A.A. becomes 2
# through set, self.v becomes 5 and A.A. beco... |
62ed08e08c38f025d858b8febf200dee32442f73 | nicklambson/pcap | /labs/sudoku.py | 1,182 | 3.734375 | 4 | def get_blocks(board):
blocks = list()
for row in range(0, 9, 3):
for col in range(0, 9, 3):
block = list()
for r in range(row, row + 3):
for c in range(col, col + 3):
block.append(board[r][c])
blocks.append(block)
return blocks... |
d49c0f3ccca031ea2ad6721ad0f1ae0024b9cd12 | nicklambson/pcap | /comprehensions/list_comp_1.py | 131 | 3.75 | 4 | ls = [[c for c in range(r)] for r in range(3)]
for x in ls:
if len(x) < 2:
print("x")
print(ls)
# two x's are printed |
8a09343995257ffa64a3177ac38f07df1c68987c | Al3xDu/PythonProjects | /CacheSystem/helpers.py | 1,977 | 3.5 | 4 | import regex as re
import yaml
# func to verify an url with regex
def url_verifier(url):
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
... |
111c3a2fb61146006008ccb9fde5413dbb724bb8 | Robinron/IS-105 | /Lab-4/Lab4.py | 11,413 | 3.6875 | 4 | # -*- coding: latin-1 -*-
#
# IS-105 LAB4
#
#
#
#
import sys
import random
import math
import itertools
from collections import defaultdict
gruppe = { 'student1': 'Robin Amir Rondestvedt Moudnib', \
'student2': 'Ricky Løtoft Omland', \
'student3': 'Cuong Bui', \
'studen... |
6242873534ea3736e3c7c2383245ef2aaf0110b4 | g2graman/Miscellaneous | /Data_Structures/Trees/Data-partitioning Trees/Kd Trees/Explicit/pq.py | 2,948 | 4 | 4 | class PriorityQueue(object):
'''A binary heap-based Priority Queue.'''
def __init__(self):
'''(PriorityQueue) -> NoneType.'''
self._queue = []
self._size = 0
def enqueue(self, obj, priority):
'''(PriorityQueue, object, int) -> NoneType.
Enqueue object into PriorityQueue.'''
self._que... |
fa62ec80fba8d640d3c3a51dc1b610d650754967 | g2graman/Miscellaneous | /Data_Structures/Trees/Data-partitioning Trees/Kd Trees/Explicit/stack.py | 538 | 3.828125 | 4 | class Stack(list):
'''A last-in, first-out (LIFO) stack of items'''
def __init__(self):
'''(Stack) -> NoneType
A new empty Stack.
'''
self.contents = []
def push(self, v):
'''(Stack, object) -> NoneType
Make v the new top object on this stack.
'''
self.contents.append(v)
def pop(self):
'''... |
f076129ad723a67c6a1776ae8b2fe98c9e4f36fa | stollcode/CSP | /guess_3_ex1-3-8.py | 4,574 | 4.6875 | 5 | '''
*** Guess Three Program ***
*** Guess Three Program ***
*** Guess Three Program ***
This program:
- Generates a three digit number at random (called the secret number).
- Each digit in the secret number must be unique (880 is invalid since the 8 is repeated).
- Asks the player to gues... |
bcc9fb70576c74b870faadacca231a129ee3b466 | davidnorminton/NASA-desktop-wallpaper | /wallpaper/wallpaper.py | 3,217 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author David Norminton
# <davidnorminton@gmail.com>
# last updated : 24 - 02 -16
# This has a, "do whatever you want with it license", so run wild.
import nasa
import set_wallpaper
import sys
#url to find list of images
list_url = 'http://apod.nasa.gov/apod/archivepix.h... |
0fbf985e83490e2f119e81b66aab6307b3dd97ac | hakonbyh/NTNU-TDT4117 | /genism.py | 7,071 | 3.734375 | 4 | import random
import gensim
import string
from itertools import groupby
import re
from nltk.stem.porter import PorterStemmer
# NOTE: PARAGRAPH == DOCUMENT
# ## Task 1 ## #
# random numbers generator
random.seed(123)
# A word stemmer based on the Porter stemming algorithm
stemmer = PorterStemmer()
... |
9ecde3742a8c669a30848684f7638d17b1ae29ea | pywjh/BrainBurningRecord | /排序/version_python/归并排序.py | 1,784 | 4.03125 | 4 | def merge_sort(array, start, end):
"""
归并排序
[8, 4, 5, 7, 1, 3, 6, 2]
----------------------------------
[4, 8]
----------------------------------
[5, 7]
----------------------------------
[4, 5, 7, 8]
----------------------------------
[1, ... |
84ce8e7f8f47154770bc0eccf12122cbb7a3a691 | yaronlevi1/CDcode | /Python/python_fundamentals/hello_numpy.py | 191 | 3.59375 | 4 | import numpy as np
my_list = [1,2,3]
print(my_list)
arr = np.array(my_list)
print(arr[1:])
print(type(arr))
x=np.array([ [1,2,3], [4,5,6], [6,7,8] ])
print(x)
print(np.arange(0,10,2)) |
8836013b5152ebea99ee57296d5c81d26e364e38 | yaronlevi1/CDcode | /Python/algo/makeChange.py | 478 | 3.6875 | 4 | import math
def change(cents):
coins = {}
coins['dollars'] = math.floor(cents/100)
cents-=100*coins['dollars']
coins['quarter'] = math.floor(cents/25)
cents-=25*coins['quarter']
coins['dime'] = math.floor(cents/10)
cents-=10*coins['dime']
coins['nickel'] = math.floor(cents/5)
cents-... |
5664e914071c8cb5b0336f8830c2109d13ff45d4 | yaronlevi1/CDcode | /Python/python_fundamentals/FunwithFunctions.py | 487 | 4.09375 | 4 | def odd_even():
for i in range(1,21):
if i%2==0:
p2="even"
else:
p2="odd"
print("NUmber is ",i, "-- This is an", p2, "number")
odd_even()
def multiply(a,b):
mList=[]
for i in a:
mList.append(i*b)
#print(mList)
return mList
multiply([1,2,3],3)
... |
4e277295852fb06ca1d9d5e2a7453c26ae596881 | yaronlevi1/CDcode | /Python/python_fundamentals/MultiplicationTable.py | 361 | 3.78125 | 4 | for i in range(0,13):
for j in range(0,13):
if i==0 and j==0:
my_str += "x".ljust(5," ")
elif i==0:
my_str += str(j).ljust(5," ")
elif i>0 and j==0:
my_str += str(i).ljust(5," ")
else:
my_str += str(i*j).ljust(5," ")
if j==12:
... |
aa63891f50707742521ae95086e4a36a72ab5f3b | ravituduru/itversity_pyspark | /6.Develop_data_processing_applications_using_loops_and_collections/1.py | 2,178 | 3.5625 | 4 | def readData(datapath):
datafile=open(datapath)
datastr=datafile.read()
datalist=datastr.splitlines()
return datalist
#columns in order_items
#id,order_id,product_id,quantity,sub-total,price
orderItems=readData("D:\\Ravi\\data-master\\retail_db\\order_items\\part-00000")
#1.Create a Function to get rev... |
1101b9abde86086a883133be5b91534c5c4b2769 | ArroyoBernilla/T08_Arroyo.Aguilar.. | /Aguilar/concatenacion_cadena.py | 4,537 | 3.59375 | 4 | print("="*70)
#ejercicio 1 - concatenacion
#concatenar los mensajes 1, 2 y 3
#Y formar el mensaje: todo cambio dentro de mi
msg1="todo cambio"
msg2="dentro de"
msg3="mi"
msgf=msg1+" "+ msg2+ " "+msg3
print(msgf)
#FIN_CONCATENACION
print("="*70)
#ejercicio 2 - concatenacion
#concatenar los mensajes 4, 5, 6, 7, 8, 9, 10... |
d950eeff5361dd1474da59f111a8d6f81ec6b2f8 | ArroyoBernilla/T08_Arroyo.Aguilar.. | /Aguilar/Busqueda_cadena.py | 4,284 | 3.984375 | 4 | print("="*50)
#ejercicio 1 = buscador
#buscar la palabra: MENUDO
frase1="EL QUE TIENE GRANDES PENSAMIENTOS, A MENUDO COMETE GRANDES ERRORES"
buscador1=frase1.index("MENUDO")
print("La palabra MENUDO esta en la posicion: ", buscador1)
print("="*50)
#FIN_BUSCADOR
#ejercicio 2 = buscador
#buscar la palabra: ENSEÑA
frase2... |
d114efc41de6d90e81eb858cbc652fe2541bef14 | rumeysakarakavak/Algorithm-Design-with-Python | /HW05/141044063_HW5.py | 5,123 | 3.625 | 4 | ################################################## Part1 ###############################################################
print("######### Part1 ###########")
def minimumCost(n, m, nCostArray, sCostArray):
minimumS = 0
minimumN = 0
for i in range(0, n - 1):
lastS = minimumS
lastN = m... |
e616966a28dbd8bbd905ecba525b13c87ce2980d | deelm7478/CTI110 | /P4T2_BugCollector_MathewDeel.py | 602 | 4.3125 | 4 | # Collects and displays the number of bugs collected.
# 10/15/18
# CTI-110 P4T2 - Bug Collector
# Mathew Deel
#
def main():
#Initialize the accumulator
total = 0
#Get the bugs collected for each day.
for day in range(1, 6):
#Prompt user for amount of bugs that day
print('E... |
f91daa21904b1c8272e2eaa69f2b416cd7942870 | deelm7478/CTI110 | /P4T1a_Deel.py | 852 | 4.21875 | 4 | # A program that draws both a square and a triangle
# 10/23/18
# CTI-110 P4T1a: Shapes
# Mathew Deel
#
def main():
#Import function
import turtle
#Specify shapes and playground
win = turtle.Screen()
s = turtle.Turtle()
t = turtle.Turtle()
#Specify pen characteristics for tr... |
e34d1d88baccae19431131256b8d91c27b4249b8 | bryanlim97/clothing_restock | /crawler.py | 1,845 | 3.546875 | 4 | """Main file that interacts with the specified URLs."""
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import config, mail, time
def crawl(product_name, my_size, product_url):
"""Interact with the internet. The main logic flow is as fol... |
ca73b40e32c72da665e3ca602ee47ad4ce7e2ede | thomas-pln/TwitterBot_AgendaAN | /timeDate.py | 827 | 3.71875 | 4 | from datetime import date, datetime
import time
def today():
"""
Date actuelle format standard :
YYYY-MM-DD
"""
today = date.today()
#print(today)
return str(today)
#return "2021-05-20"
def todayFR():
"""
Date actuelle format français :
DD / MM / YYYY
"""
todaty =... |
4cd32957676afff3615d7fc10c0d59f9896ead23 | karanpreetjaggi/Election_Analysis | /loop.py | 95 | 3.890625 | 4 | x = 0
while x <=5:
print(x)
x = x+1
count = 7
while count <1:
print("Hello World")
|
657bc76d681ddc356531a6666e503fda463ac59d | fentonreid/Sudoku-Solver | /board.py | 3,067 | 4.125 | 4 | from square import square
class board():
def __init__(self, window):
"""
intialise the board class
:param window: takes the main pygame screen
"""
self.window = window
self.grid = []
self.hover = None
def createBoard(self, width, height, ... |
f5587a5a1eb6d02337511ec5bc16d23f2bd0af9d | jesusalatorre/Python | /factorial.py | 191 | 4.03125 | 4 | #factorial
def factorial():
prompt=int(raw_input ('Please input the number for the factorial: '))
answer=prompt
for number in range[1,prompt]:
answer=answer*(prompt-number)
print answer |
07900967bffe31a357ef425d97989e5344eed383 | Nonoreve/2048Solver | /solver/AIsolver/GeneticNeuralNetwork.py | 3,922 | 3.75 | 4 | import math
BIAS = -1
"""
To view the structure of the Neural Network, type
print network_name
"""
class Neuron:
def __init__(self, nbInputs, weights):
""" last case of weights is the bias (so weights's length is nb_inputs + 1) """
self.n_inputs = nbInputs
# a tab of weights
sel... |
47f46b0486a855cd2a7f562177ce5ba5cae7a01a | andrewcao95/Chinese_modern_poem_generator | /informationRetrievalBased/rerank/find_path.py | 1,577 | 4 | 4 | def find_path(j):
path_vertexs.append(j) #把该节点标记为已走过
row=c[j]
#创建copy_row,删除row中已走过的顶点,防止直接在row上操作.
copy_row=[value for value in row]
walked_vertex=[]
for i in path_vertexs:#已走过的顶点
walked_vertex.append(copy_row[i])
for vertex in walked_vertex:
copy_row.remove(vertex)
... |
97241aa2280caca03938b38a26b4cd88689eec6f | amit70/Python-Interview-Examples | /patternString.py | 1,152 | 3.65625 | 4 | #Find all the occurence of pattern string in an input string
def zArray(inputString,patterlength):
outputArr = [0] * len(inputString)
inputStringPointer = 1
while inputStringPointer <= len(inputString) - 1:
leftpointer = 0
rightpointer = inputStringPointer
currentcount = 0
... |
89485553984586b755ceb910ff336e33bb3bb283 | amit70/Python-Interview-Examples | /addOnetoNumber.py | 545 | 3.796875 | 4 | #Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
#The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
#You may assume the integer does not contain any leading zero, except the number ... |
9583849c3077e5aeefc86c503f69043286d0edf9 | amit70/Python-Interview-Examples | /isPower2.py | 481 | 4.28125 | 4 | #Given an integer, write a function to determine if it is a power of two.
def isPower(n):
# Base case
if (n <= 1):
return True
# Try all numbers from 2 to sqrt(n)
# as base
for x in range(2, (int)(math.sqrt(n)) + 1):
p = x
# Keep multiplying p with x while
# is sm... |
4d9c9af48ae08f6e2010945028d9efd204b2147c | christopherambrus/Froggit | /samples/pyro.py | 7,280 | 3.703125 | 4 | """
A Game-like Controller module for lecture demos.
You should refer to this file to see how to had and remove
objects as they die or go offscreen.
Authors: Walker White (wmw2), Lillian Lee (ljl2), and Steve Marschner (srm2)
Date: November 20, 2019
"""
import introcs
import random
import math
from game2d import *... |
7f6332b55bbbe18522967423ca8bdbca643e0522 | christopherambrus/Froggit | /models.py | 3,058 | 4 | 4 | """
Models module for Froggit
This module contains the model classes for the Frogger game. Anything that you
interact with on the screen is model: the frog, the cars, the logs, and so on.
Just because something is a model does not mean there has to be a special class for
it. Unless you need something special for your... |
2ff9dba312bba113507e2c4e2c368acead1c46bd | seoyoungs/coding_test | /중복수제거.py | 470 | 3.9375 | 4 | \
# 중복수 제거
def solution(arr):
answer = []
for i in arr:
if i not in answer:
answer.append(i)
print('Hello Python')
return answer
# 짝수단위 중복 수 제거
def solution(arr):
answer = []
answer.append(arr[0])
for i in range(1, len(arr)):
if arr[i] != arr[i-1]: # 앞뒤 두개씩 비교
... |
1408d18dd690f8f97b000a74645064bd4d5839e3 | AvneeshAFC/Movie_trailer | /media.py | 732 | 3.625 | 4 | import webbrowser # Imports the module Webbrowser
class Movie():
""" This class provides movie realted information.
Info like movie title, storyline, poster image,
trailer is displayed of each movie. """
# List of ratings that can be given to a movie
VALID_RATINGS = ["G", "PG", "PG-13", "R"]
... |
1d472f6668a882338dcc4131be59e31368c20056 | zaiba19/computer-science-127 | /octagon.py | 178 | 4.03125 | 4 | #Name: ...Zaiba Iqbal...
#Date: August 29, 2017
#This program draws a octagon.
import turtle
tia = turtle.Turtle()
for i in range(8):
tia.forward(45)
tia.right(45)
|
3e72ccdbfe293dd5ed3e323341022b98657a7c93 | reprah/fp | /eulerian_paths.py | 3,427 | 4.125 | 4 | """
An Euler path (EP) is a path that uses every edge of a graph exactly once and
starts and ends at different vertices.
To have an EP, the graph must have exactly two nodes of odd degree:
an EP will visit every edge as well as exit any node the same
number of times it enters the node, except for the starting and endi... |
d49fcefa3a96fdc9c72cdd9315ed4c29a5e9aa10 | jperezllorente/api-sentiment-project | /tools/getdata.py | 1,947 | 3.765625 | 4 | from configuration.config import collection
import tools.extraction as ext
def film_review(title):
'''
This function allows to select a title from the mongodb collection, and returns a list with the title we are
interested in and the reviews of that title. Remember, it can be a movie or a tv show.
It ... |
d0cd0a1e056e774afa74b86f840ac086f1a69be7 | bobeff/playground | /fmi/python/2014/tasks/02-five_functions/my_solution.py | 974 | 3.53125 | 4 | from collections import defaultdict
from functools import cmp_to_key
BG_LETTERS = "абвгдежзийклмнопрстуфхцчшщъьюя"
def is_pangram(sentence):
return len({letter for letter in sentence.lower()
if letter in BG_LETTERS}) == 30
def char_histogram(text):
histogram = defaultdict(int)
for charac... |
85e1d79bf92663eaa8926ce8127e0790777ed50e | bobeff/playground | /fmi/python/2014/challenges/01-perfect-number/author_solution.py | 190 | 3.5625 | 4 | from functools import reduce
from operator import add
def is_perfect(number):
divisors = [d for d in range(1, number) if number % d == 0]
return reduce(add, divisors, 0) == number
|
1d3ec1cdebaddc4482ca55cf19ba03653d637f7c | dvagala/VUT-FIT-IPP-Code-interpreter | /interpret_src/Instruction.py | 808 | 3.65625 | 4 |
class Instruction:
"""
Represents instruction in IPPcode19
"""
def __init__(self, name, arguments, order=None ):
self.name = name.upper()
self.arguments = arguments
if order:
self.order = int(order)
else:
self.order = None
def __str__(self):
"""
Just for friendly debug print
"""
... |
c4ecf5787a7e1c03ee3f017354f120f2e7bd1e08 | Butterparade/School-stuff | /Programming 122 - Python/Jamie_Thayer_Proj9.py | 1,486 | 3.515625 | 4 | """
Jamie Thayer -- Optional Project 9
"""
""" Problem 1 """
def check_file(fname):
"""
('filepath')->file contents
Opens given file path (or file name if file is in same folder as proj9)
reads contents if able, and prints those contents if able.
returns none
>>> check_file("\\Users\\Huffl... |
0aadbf5bf9ba3b33c387cfc50e843b3dfd766be2 | Butterparade/School-stuff | /Programming 122 - Python/Jamie_Thayer_Proj3_1-1.py | 407 | 3.75 | 4 | import turtle
"""declaring Q as the ratio of the size of the earth compared
to the size of the sun"""
Q = (1392000/12756)
turtle.up()
turtle.goto(0,-320)
turtle.down()
turtle.fillcolor('green')
turtle.begin_fill()
turtle.circle(2.75)
turtle.end_fill()
turtle.up()
turtle.goto(0,-300)
turtle.down()
turtle.fillcolor('or... |
9155292ee252ccbf0682cca7df6a321f227d0d34 | kylebejel/Vigenere-Cipher | /vigenere.py | 663 | 4.125 | 4 | def encrypt(message, key):
alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
key_index = 0
new_message = ""
for ch in message:
new_ch = alph[(alph.index(ch) + (26 - alph.index(key[key_index])))%26]
... |
c0f944eb86a98e18b3625d18aa70fd3389ccf381 | jango/calculon | /calculon/Calculon.py | 3,888 | 3.6875 | 4 | from multiprocessing import Queue, Pipe
from Consumer import ConsumerProcess, ConsumerThread
from Producer import ProducerProcess, ProducerThread
class Calculon:
"""Producer-consumer class. Responsible for initializing producers and consumers and controlling execution."""
def __init__(self, prod_func, prod_k... |
794b01b3462f94f38243053c076cd46b506763b0 | yokabicarpmaz/ME462_ControlSystemsTools | /Webots Simulations/Vehicle/controllers/OpenLoop_controller/OpenLoop_controller.py | 2,497 | 3.65625 | 4 | """OpenLoop_controller."""
# This controller is compatible with 'vehicle.wbt' world
# OPEN-LOOP VEHICLE
"""
In this simulation, The vehicle has an open-loop system.
The purpose of this simulation is to understand
the difference between open and closed-loop systems.
"""
# You may need to import some classes of the c... |
7364789665dbfbe4b7ca803bae11736b0a3c2e6e | 7h3730B/advent-of-code | /2020/05/main.py | 221 | 3.53125 | 4 | with open('input.txt', 'r') as f:
entries = [line.strip() for line in f]
def get_seatid(entry):
return int(''.join('0' if x in 'FL' else '1' for x in entry), 2)
print(max(get_seatid(entry) for entry in entries)) |
fb7ebca50685c19f736d1c0fb97a0e22299f0eff | glamod/glamod_landQC | /geometry.py | 6,304 | 4.09375 | 4 | """Methods for geometric calculations on a sphere"""
# hadcrut/analysis/geometry.py @ 20200116
import numpy as np
def cross_indices(array_a, array_b=None):
"""Construct an array of indices mapping between all combinations of elements of input arrays.
Arg:
array_a:
A 2D array of shape (M,... |
134d690ef5727cce192900151ddb83c8d67b73b8 | jananee009/DataStructures_And_Algorithms | /Arrays_And_Strings/ReverseString.py | 1,183 | 4.6875 | 5 | # Implement a program to reverse a string.
# Follow up: Write a function to reverse an array of characters in place. "In place" means "without creating a new string in memory."
def reverseString(inputStr):
reversed = ""
for i in range(len(inputStr)-1,-1,-1):
reversed = reversed + inputStr[i]
return reversed
de... |
d8c39538141f5d4065f9a6c89a0b438d66648a9e | jananee009/DataStructures_And_Algorithms | /Arrays_And_Strings/ReplaceAllSpaces.py | 749 | 4.4375 | 4 | # Write a method to replace all spaces in a string with '%20'. Assume that the string has sufficient space at the end of the string to hold the additional characters
# and that you are given the true length of the string.
# E.g. Input: "Mr John Smith ", 13
# Output: "Mr%20John%20Smith"
def replaceAllSpaces(inpu... |
f90911ff384b918a697fd987bf4e12b814bbc92c | jananee009/DataStructures_And_Algorithms | /Miscellaneous/Parentheticals.py | 1,984 | 4.125 | 4 | # Write a function that, given a sentence, , finds the position of an opening parenthesis and the corresponding closing parenthesis.
# Source: https://www.interviewcake.com/question/python/matching-parens?utm_source=weekly_email&__s=ibuidbvzaa2i67rfb2mc
# Approach: 1. Process the string character by character.
# We c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.