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
3e62b6eb0e46756095000a0f5c7b2ec89c449b50
elanorigby/EndlessCapitalsQuiz
/ccquiz/logic.py
1,155
4
4
from random import choice from .data import Data class Quiz: """ Pass in 'capitals', 'countries', or 'random' when you create an new instance. This will give you the properties - instance.kind - instance.ans - instance.hint - instance.question and the method - instance...
74a65de3a2e43797cb215f39171a371ad34b2faa
cfish-fi/kivy-ensikello
/audioplayer.py
1,562
3.546875
4
#!/usr/bin/env python """This script defines AudioPlayer class for Ensikello application""" from kivy.core.audio import SoundLoader class AudioPlayer(SoundLoader): """Implements a simple queued wav audio player""" queue = [] playing = None def play_queue(self, *_): """Plays the first filena...
6063da0e5abdec6c256197489913440f58974a82
SeriARM/Data-Structures
/text_buffer.py
4,771
3.796875
4
class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next def insert_after(self, value): current_next = self.next self.next = ListNode(value, self, current_next) if current_next: current_next.prev = self.next def insert_befo...
2408451313af66158ab95302ee2ebab3e7784ba2
LenonAbreu/pythonUerj
/exercicios/aula6_condicionais.py
892
3.984375
4
import turtle import matplotlib.pyplot as plt def draw_bar(t, height): """ função para desenhar um histograma com o modulo turtle . """ t.begin_fill() t.left(90) t.forward(height) t.write(" "+ str(height))#cria um rotulo indica a frequencia o dado t.right(90) t.forward(...
704a0891a943fff13693ea8d11d45586892e0019
MoChin/Python
/stock_analysis1/csv_test.py
347
3.71875
4
import csv with open('data.csv', 'wb') as f: writer = csv.writer(f) writer.writerow(['C1','C2','C3']) lines = [range(3) for i in range(5)] for line in lines: writer.writerow(line) with open('data.csv', 'rb') as f: reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE) for row in...
c66afad1d1ede6376c4c356db69f38c5014f1950
traumgedanken/python_orm
/columns/column.py
3,265
3.59375
4
import abc from columns.expression import Expression class Column(metaclass=abc.ABCMeta): """Class to represent table column in ORM class object""" def __init__(self, primary_key=False, nullable=True): self.type = None self.col_name = None self.table_name = None self.prim...
65f97da9905624c5f171355c7e5856c594a16723
sivaramsajeev/Python-SQLite
/create_table.py
571
3.65625
4
import sqlite3 try: sqliteConnection = sqlite3.connect('SQLite_Python.db') cursor = sqliteConnection.cursor() print("Successfully Connected to SQLite") with open('create_table.sql', 'r') as sqlite_file: sql_script = sqlite_file.read() cursor.executescript(sql_script) print("SQLite sc...
0f1200534740d923716f050293f50b0ed9866f43
dhruvkam/Python
/AAKASH2.py
209
3.734375
4
import RPi.GPIO as GPIO GPIO.setmode (GPIO.BCM ) GPIO.setup (26,GPIO.OUT) print("please type 1 or 2") x= int (input ()) if x==1: GPIO.output (26,GPIO.HIGH) if x==2: GPIO.output (26,GPIO LOW)
47db5a67b7279c4482d61bb4238b52a914dfbecd
orionarcher/Game
/Game/starter/item.py
2,641
3.59375
4
import os # changed 8:13 def clear(): os.system('cls' if os.name == 'nt' else 'clear') class Player: def __init__(self): self.location = None self.items = [] self.cases = [] # the cases self.health = 50 self.cunning = 2 # modifies spell effects self.cunningtemp ...
f3a20fff06bb91aebf8b6267aae4c0346fb28225
NChesser/cluey
/Cluedo/main.py
1,507
3.59375
4
from setup import SetUp #Cluedo Game def game(times=100): #adding a comment here to test rounds = 0 for i in range(0, times): new_game = SetUp(6) rounds += handle_turns(new_game.players, new_game.crime) print ("Average rounds taken " + str(rounds/times)) def ...
76d52e91e16e9cf676d1d4ca8ce970d9d9829c24
mattearly/scan-url-for-emails
/urlscan.py
4,391
3.734375
4
########################################################################################### # Programmer: Matthew Jay Early # File Created: 2017-02-13 # Program Description: This program runs in Python3 console and will scan a website for # Emails and associated Names, exportin...
e740851e24b30da701fb1b929cb4a3cde4b2cd61
QiangjunZhang/Data-Structure-and-Algorithm-in-Python
/Algorithms/MonotonicStack/jumpGame.py
545
3.609375
4
class JumpGame: def jump(self, nums): """ keep a monotonic jump range """ stack = [0] * len(nums) for i in range(len(nums) - 2, -1, -1): if i + nums[i] >= len(nums) - 1: stack[i] = 1 elif nums[i] < 1: stack[i] = float('i...
7e1940c8e5bbf7214c83427f158215bd90987ce9
QiangjunZhang/Data-Structure-and-Algorithm-in-Python
/LeetCode/AddTwoNums.py
1,389
3.78125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = Lis...
b7f111978d7fe4c60a1c000c1dfd1cfeb2051a77
priyansh71/qstp-cybersec
/Cryptography/1.5.py
1,124
3.921875
4
# Repeating-key XOR # Here, instead of using chars from 0-255, we have been given a key, each of whose letters have to be xorred against corresponding # characters of the given string, and the key has to be repeated until it's length equals len(string). key = b'ICE' string = b"Burning 'em, if you ain't quick and nimb...
3d3267f8075dbd0d697c47c894c14b220bb1259d
NarsimhaChilkuri/Supervised-Learning
/KNN.py
2,174
3.859375
4
import numpy as np class KNN: """ Regression or Classification using the K-Nearest Neighbours approach. Args: X : numpy array of dimension Nxp, where N is the number of trainig examples and p is the number of predictors. Y : numpy array of dimension Nx1, where N is the num...
0750b9201f2c2c5bc5e2bd8fdd478dfdffbffe4f
cschmidli/SBTi
/SBTi/data/__init__.py
2,673
3.515625
4
""" This module contains classes that create connections to data providers. """ from typing import Type import pandas as pd from SBTi.configs import ColumnsConfig def get_company_data(data_providers: list, companies: list, config: Type[ColumnsConfig] = ColumnsConfig) -> pd.DataFrame: """ Get the company dat...
ea159a0a72f73016debc3b0b88d78a7463c3325f
skarycarry/nn_hw
/Assignment2/ecbm4040/layer_funcs.py
14,239
3.765625
4
#!/usr/bin/env/ python # ECBM E4040 Fall 2018 Assignment 2 # This Python script contains various functions for layer construction. import numpy as np def affine_forward(x, w, b): """ Computes the forward pass for an affine (fully-connected) layer. The input x has shape (N, d_1, ..., d_k) and contains a ...
ca272b96782975a587bc04bd2c8f1ce24c03d248
reventhtv/kerasTensorFlowSample
/kerasSample.py
4,610
3.546875
4
# This is a simple keras with TensorFlow Python script. #Data Preparation and Processing import numpy as np from random import randint from sklearn.utils import shuffle from sklearn.preprocessing import MinMaxScaler train_labels = [] train_samples = [] #Example data: #An experimental drug was tested on individuals f...
92c06355bb078fb1b0c39b87e605ecf608f960c1
huge-sesh/work
/movement.py
1,038
3.546875
4
class Movement(object): def acceleration(self, time): if self.accel_time != 0: return self.max_speed / self.accel_time * time else: return self.max_speed def deceleration(self, time): if self.decel_time != 0: return self.max_speed / self.decel_time * time else: return self.max_s...
f0cf8343b7cb9293b5ecea2532953d0ca0b55d49
devaljansari/consultadd
/1.py
1,496
4.59375
5
"""Write a Python program to print the following string in a specific format (see the output). Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what y...
ccc00e92c9f20c39747cdc92261ae761594f50c0
xyiDuan/simple-inventory-management
/run_me.py
1,472
3.921875
4
from inventorymm import management if __name__ == '__main__': print('***Welcome to the inventory management system***') items_list = management.retrieve_inventory_items() items_dict = management.items_list_to_dict(items_list) management.show_current_inventory(items_list) is_continue = 'Y' whil...
782486a4f6ebc82a9f4ecb3dcd76b0f4c5809018
aobo711/Investments
/shells/mysql/dealing_raw.py
1,409
3.5
4
# -*- coding: utf-8 -*- #!/usr/bin/python # 把投资原始数据按 yearmonth 分拆,并插入到 ii_monthlydata 表中 # 用于分析每个行业的月总投资笔数 import MySQLdb db = MySQLdb.connect(host='localhost', # your host, usually localhost user='root', # your username passwd='', # your password ...
4a4498909f1608b95703e80461250b03de4fb47e
RL-WFU/GeneticWeightUploading
/Prediction.py
8,674
3.71875
4
""" Benjamin Raiford — June 2020 Convolutional Neural Network for MNIST Predict the class given an image This project owes a substantial debt to Jason Brownlee's tutorial at: https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-from-scratch-for-mnist-handwritten-digit-classification/ ""...
ff2b2a555ee7cfe9bc86fbcfd9cc041594a3de75
vinayamrk/Basic_programming_using_python
/function_declaration.py
1,779
4
4
def f(x): return(x*x) def greet(): print("hello world") def avg(a,b): return((a+b)/2) def circle(r): """return the area and perimeter of circle given radiusr""" pi=3.14 area=pi*r*r perimeter=2*pi*r return(area,perimeter) def something(): ...
38b69f31f73c3295bfcbc08be9e1b21bb5810e78
nyarlatoteph/AoC2017
/day11.py
1,118
3.515625
4
import math def distance(x, y, z): return max(abs(x), abs(y), abs(z)) def count(input): steps = input.split(',') x = 0 y = 0 z = 0 max_distance = 0 for step in steps: if step == "sw": x -= 1 z += 1 elif step == "se": x += 1 ...
a0e8824ce57a0f8541982ea7b558c15badac23c1
peter359/Programming101-3
/week3/bank.py
2,074
3.6875
4
class BankAccount: def __init__(self, name, start_balance, currency): if start_balance < 0: raise ValueError("Start balance must not be negative") self.__balance = start_balance self.__name = str(name) self.__currency = str(currency) self.__history = [] ...
4a595b917cbdad52aef1ae71a886e9f1d000a602
peter359/Programming101-3
/week7/create_company.py
635
3.96875
4
import sqlite3 connection = sqlite3.connect("company.db") cursor = connection.cursor() create_company_table = """ CREATE TABLE IF NOT EXISTS company (id INTEGER PRIMARY KEY, name TEXT, monthly_salary int, yearly_bonus int, position TEXT) """ add_employees = """ INSERT INTO company (name, monthly_salary, yearly_bonus...
464b1fa36c663826b9a631731cca2661b0103695
scynthero/numerical_methods_solutions_lab
/lab4/ex1.py
281
3.59375
4
from matplotlib.pyplot import * from numpy import * def Euler(a=1,T=3,h=0.1): initial_x = 1 t = arange(0, T, h) x = zeros(t.shape) x[0] = initial_x for i in range(t.size - 1): x[i + 1] = x[i] + h * (1 * x[i]) plot(t, x, '-') show() Euler()
63b5c92221d4d38ecc2d69b325a65dc0ee620089
simax8859/python
/chapter_16/fkmodule.py
890
3.984375
4
MY_NAME = '疯狂软件教育中心' def say_hi(name): """ 定义一个打招呼的函数 :param name: 对象姓名 :return: 返回对指定用户打招呼的字符串 """ print("执行say_hi函数") return name + "你好" def print_rect(height, width): """ 定义一个打印矩形的函数 :param height: 代表矩形的高 :param width: 代表矩形的宽 :return: """ print(('*' * width...
b2214356c23983ffa32277f2e138706a069a37dd
westb2/opsys_hw2
/PPalg.py
7,018
3.546875
4
import PROCESS import CPUS import IOwait from Queue import PriorityQueue import PROCESS import CPUS import IOwait from Queue import PriorityQueue def simulatePP(Processes, num_cpus, dead_condition): #get the cpus up and running cpus = CPUS.CPUS(num_cpus) waiting_on_IO=IOwait.IOwait() dead_processes=[] time=0 ...
2b18385f2dc36a87477c3e7df27ff8bd2a988c33
heet-gorakhiya/Scaler-solutions
/Trees/Trees-1-AS_inorder_traversal.py
1,783
4.125
4
# Inorder Traversal # Problem Description # Given a binary tree, return the inorder traversal of its nodes values. # NOTE: Using recursion is not allowed. # Problem Constraints # 1 <= number of nodes <= 10^5 # Input Format # First and only argument is root node of the binary tree, A. # Output Format # Return an in...
70171798a6cd2d2550062193fb366f63f3d163ae
heet-gorakhiya/Scaler-solutions
/Arrays/Array-and-Math-AS_closest_minmax.py
1,430
3.640625
4
# Closest MinMax # Problem Description # Given an array A. Find the size of the smallest subarray such that it contains atleast one occurrence of the maximum value of the array # and atleast one occurrence of the minimum value of the array. # Problem Constraints # 1 <= |A| <= 2000 # Input Format # First and only arg...
7bef35d2469918adffb66551f01f2d6f7e243326
heet-gorakhiya/Scaler-solutions
/Bit-Manipulation/Bit-Manipulation-AS_min_xor_value.py
930
3.96875
4
# Min XOR value # Problem Description # Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value. # Problem Constraints # 2 <= length of the array <= 100000 # 0 <= A[i] <= 109 # Input Format # First and only argument of input contains a...
c7cc2513ded62eee010d3a1c72f0fa41d1633ae9
heet-gorakhiya/Scaler-solutions
/Arrays/Arrays-AS_N_by_3_repeat_number.py
1,754
3.5
4
# N/3 Repeat Number # You're given a read only array of n integers. Find out if any integer occurs more than n/3 times in the array in linear time and constant additional space. # If so, return the integer. If not, return -1. # If there are multiple solutions, return any one. # Example : # Input : [1 2 3 1 1] # O...
40e8f9195bb42c0a8c3373b2cc5c24c485c7b097
heet-gorakhiya/Scaler-solutions
/Trees/Trees-2-AS_right_view_of_tree.py
2,121
4.09375
4
# Right view of Binary tree # Problem Description # Given a binary tree of integers denoted by root A. Return an array of integers representing the right view of the Binary tree. # Right view of a Binary Tree is a set of nodes visible when the tree is visited from Right side. # Problem Constraints # 1 <= Number of no...
459ee1c60423011457183df6e5a897df77b7b62d
ani07/Coding_Problems
/project_euler1.py
491
4.28125
4
""" This solution is based on Project Euler Problem Number 1. If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ class MultiplesThreeFive(): def multiples(self): sum =...
5d401b278b9e481bc02bfd5c57cedcbf945b9104
DeepakMe/Excellence-Technologies-
/QONE.py
309
4.15625
4
# Question1 # Q1.Write a function which returns sum of the list of numbers? # Ans: list1 = [1,2,3,4] def Sumlist(list,size): if (size==0): return 0 else: return list[size-1]+Sumlist(list,size-1) total = Sumlist(list1,len(list1)) print("Sum of given elements in List: ",total)
1da8ae890418a584f680327861b108ab4a2943d4
juliusiv/plangrid-spellchecker
/spellchecker.py
2,208
3.53125
4
import re class Spellchecker: def __init__(self, langs={}): self.languages = langs def get_languages(self): return self.languages # Spellchecks a sequence of text |text| using all languages in the current # spellchecking dictionaries. def check(self, text): words = normalize(text).split() m...
e31e1faec48a064176ad9dba34ed13ba8d263272
SaratM34/CSEE5590-490-Python-and-DL-SP2018
/Python Lab Assignment 1/Source/Q2.py
771
4.4375
4
# Taking input from the user list1 = input("Enter Sentence: ").split(" ") # Function for evaluating the sentence def give_sentence(list1): # Declaring empty list list2 = [] #Print middle words in a sentence print("Middle Words of the Sentence are: "+list1[len(list1)//2], list1[(len(list1)//2)+1]) ...
5219e9eb04ae6ab5c6dcc115f279ff0d627bc9a4
saad1803/python-rest
/Employee.py
270
3.703125
4
class Employee : emp = 0 __name = '' __salary = 0 def __init__(self,name,salary) : self.name = name self.salary = salary Employee.emp += 1 def printEmployee (self) : print self.name + ' ' + str(self.salary)
17d716fe5010d3519d438aed8a870cec17521640
pmacosta/pmisc
/pmisc/misc.py
607
3.53125
4
# misc.py # Copyright (c) 2013-2020 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0111 ### # Functions ### def flatten_list(lobj): """ Recursively flattens a list. :param lobj: List to flatten :type lobj: list :rtype: list For example: >>> import pmisc ...
0b6d1670a243eddf00129f5ec29489c2c44187a1
Tomer-Shahar/Conformant-CBS
/pathfinding/planners/utils/time_uncertainty_plan.py
1,412
3.6875
4
""" Class representing a conformant plan. """ import math class TimeUncertaintyPlan: def __init__(self, agent_id, path, cost): """ :param agent_id: The agent number (i.e 1,2,3..) :param path: A list containing tuples of the form <time range, coordinate> where both time range and coordina...
ebccbbf25fff7ed4b4ed2636f7ef70b9169b89b8
jcallahan4/linear_systems
/linear_systems.py
7,790
4.34375
4
# linear_systems.py """ Linear Systems Jake Callahan The fundamental problem of linear algebra is solving the linear system Ax = b, given that a solution exists. There are many approaches to solving this problem, each with different pros and cons. In this program we implement the LU decomposition and use it to solve s...
f46f891c7b8fb47b39665ec257484ae63a950722
P-cathony/mio
/tkinter/recoger-datos.py
1,454
3.75
4
from tkinter import * # crear la ventana raiz ventana = Tk() # cambiar tamaño en la ventana ventana.geometry("700x500") ventana.title(" recoger datos de formularios en tkinter | toni") # configuracion de la ventana ventana.config( bd=50 ) # metodo para recoger valor de dato def getdato(): resultado...
1642433fceaec6123f82a26505f67023be86f53f
P-cathony/mio
/tkinter/ejecicio_plus.py
4,731
3.53125
4
from tkinter import * from tkinter import messagebox as messagebox from PIL import Image,ImageTk class Calculadora: #consutructor def __init__(self, alertas): self.numero1 = StringVar() self.numero2 = StringVar() self.resultado = StringVar() self.alertas = alertas ...
54c6ea99804e10a3d4003911d127ab1b382dc3e2
JoseAVallejo12/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/9-print_last_digit.py
128
4.09375
4
#!/usr/bin/python3 def print_last_digit(number): n = int(repr(number)[-1]) print("{}".format(n), end="") return (n)
b46aa66680057cba5c3257bbe670002fb7c8fe91
JoseAVallejo12/holbertonschool-higher_level_programming
/0x03-python-data_structures/9-max_integer.py
206
3.515625
4
#!/usr/bin/python3 def max_integer(my_list=[]): if my_list: n_max = my_list[0] for i in my_list: if i > n_max: n_max = i return n_max return None
1e3cb2b44e6b1450f94e56fc2558a488e9d7cc60
JoseAVallejo12/holbertonschool-higher_level_programming
/0x06-python-classes/2-square.py
385
3.875
4
#!/usr/bin/python3 # 2-square.py # jose vallejo <1545@holbertonschool.com """ validate atributte """ class Square(object): """ class Square """ def __init__(self, size=0): """ inicialize size var """ if type(size) is not int: raise TypeError("size must be an integer") elif...
dba305ce221d265d1965ba622203420fce3ec389
JoseAVallejo12/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
412
3.921875
4
#!/usr/bin/python3 """ create a new class """ class MyInt(int): """ class MyInt rebel """ def __init__(self, valor): """ inicialice var valor """ self.valor = valor def __eq__(self, other): """ __eq__ represent a == b """ return self.valor != other def __ne__(self, o...
9ff25351a22a941292fd0ee1067c84ebddebbd75
JoseAVallejo12/holbertonschool-higher_level_programming
/0x0B-python-input_output/8-load_from_json_file.py
331
3.71875
4
#!/usr/bin/python3 """ create a new funtions """ import json def load_from_json_file(filename): """load Json form file Args: filename ([str]): name of file Json Returns: [python-obj]: """ with open(filename, mode='r', encoding="utf-8") as my_file: return json.loads(my_fi...
05318c1a256fb911d8f17846edbace6f9b1a857c
JoseAVallejo12/holbertonschool-higher_level_programming
/0x03-python-data_structures/7-add_tuple.py
247
3.578125
4
#!/usr/bin/python3 def add_tuple(tuple_a=(), tuple_b=()): list_t_a = tuple_a + ('0', '0') list_t_b = tuple_b + ('0', '0') sum1 = int(list_t_a[0]) + int(list_t_b[0]) sum2 = int(list_t_a[1]) + int(list_t_b[1]) return sum1, sum2
36064eef44757b2770ee0bf6a7d5cb556aeeefd9
Steven24K/Cryptopals-Solutions
/challenge2.py
2,341
3.546875
4
from challenge1 import hex2bin from challenge1 import BinairtoDecimal def Xor(byte1, byte2): """ byte1: byte_array\n byte2: byte_array\n Xor([0,0,0,0], [0,0,0,1]) => [0,0,0,1]\n Returns the XOR combination from two byte arrays, with length x.\n 0000 ^ 0001 => 0001 0 XOR 0 => 0 ...
b66e53fcea2e0232c032ed701e780a9846377322
ashiifi/basic-encryption
/encryption.py
2,527
4.40625
4
""" Basic Encryption Project: encryption(S,n) takes in a string and a number. It then moves each letter in the string n amount of times through the alphabet. In this way, 'encrypting' the string then decryption(W) takes in the encrypted string with the n at the end of it. like "helloworld1" """ def encryption(S, n): ...
4ad92ff857fe54ee93d569d04d36b6a7156c70f5
coderismail1/Python_repository
/application.2 .py
2,359
4.0625
4
""" #İKİNCİ VE SON LİSTE ELEMANININ ÇIKTISINI BÜYÜK HARFLE ALIN cities = ['Uşak', 'Manisa','İzmir','Ankara','İSTANBUL'] print(cities[1].upper()) print(cities[-1].upper()) """ """ # İzmir ve Ankara elemanlarının çıktısını al, # İlk iki elemanın çıktısını al, # Son iki elemanın çıktısını al, cities = ['U...
416b3d0890693cb9025e21df25028bcea52f8e03
Alejandrolaramasc/generalidades_de_python
/f_compresiones_listas.py
1,799
3.859375
4
# %% def divisible_por_5_o_3(n): return n % 3 == 0 or n % 5 == 0 lista = [1, 2, 15, 4, 256, 100, 60] for result in map(divisible_por_5_o_3, lista): print(result) #La función map le aplica una función a todos los elementos de una secuencia, # y retorna una secuencia con los retornos de la función aplicada. # %% ...
84dfdafa03243f8a3a1d5ed1827a78d95c57cd10
Alejandrolaramasc/generalidades_de_python
/d_tuplas.py
253
3.71875
4
# %% lenguajes = ["python", "C++", "Java", "R", "Julia"] enumerate(lenguajes) # %% list(enumerate(lenguajes)) # %% numbers=[1, 2, 3] letters=['a','b','c'] a=zip(numbers, letters) a #se genera un error # %% list(a) #entrega una lista de tuplas # %%
b5eb0154acefbf51050104418e861553462b2f40
jccf12/python-general
/exercise11.8.5.py
283
3.53125
4
import turtle t = turtle.Turtle() w = turtle.Screen() t.speed(10) f = open('mystery.txt', 'r') for l in f: i = l.split() if i[0] == 'UP': t.up() elif i[0] == 'DOWN': t.down() else: t.goto(int(i[0]), int(i[1])) t.hideturtle() w.exitonclick()
70bba3f91ecd6f64014689735d0753a6a21863d7
ParulProgrammingHub/assignment-1-Dhara01
/Program-8.py
162
4.125
4
base=float(input(“Enter the value: “)) height=float(input(“Enter the value: “)) area = 0.5 * base * height print (“The area of triangle is %f”,%area)
b10b31fa33816939bef36211a9ab488a9221c9b5
ParulProgrammingHub/assignment-1-Dhara01
/Program-6.py
128
4.09375
4
x=int(input(“Enter the value of x: “)) y=int(input(“Enter the value of y: “)) ans = x**y print (“ x^y is %d”,%ans)
74da0f8158d49547eca7bc7bd829b67cf4a9ddf7
JoRoPi/Udacity
/CS253/Unit4/src/37_Bcrypt.py
626
3.625
4
import bcrypt # Hash a password for the first time, with a randomly-generated salt password="1234" hashed = bcrypt.hashpw(password, bcrypt.gensalt()) print hashed # gensalt's log_rounds parameter determines the complexity. # The work factor is 2**log_rounds, and the default is 12 hashed = bcrypt.hashpw(password, bcry...
2827295319c31dc475acbeaf53b87039df03aae6
zhangyunrui/python_practice
/lxx/lazy_sum.py
643
3.828125
4
# -*- coding: utf-8 -*- def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum ff = lazy_sum(*[3, 3, 5, 7, 9]) f = lazy_sum f1 = lazy_sum(*[3, 3, 5, 7, 9]) f2 = lazy_sum(*[3, 3, 5, 7, 9]) print "lazy_sum(*[1, 3, 5, 7, 9])" print lazy_sum(*[1, ...
a2975450ba5f812cc4f2d84685c7b7002f2f19b6
zhangyunrui/python_practice
/python_cook/vect_addition_pro.py
437
3.78125
4
# -*- coding: utf-8 -*- class Vector: def __init__(self, x, y): self.vec_repr = x, y def __add__(self, other): new_x = self.x + other.x new_y = self.y + other.y return Vector(new_x, new_y) @property def x(self): return self.vec_repr[0] @property def y(s...
75dc543320bf2d1ddc1844ecd50a2551213a20f4
mrroot5/wall-builder
/wall/builder.py
1,389
3.953125
4
""" Python version 3.6.7 OS Linux Ubuntu 18.04.1 LTS Created: 30/11/2018 17:12 Finished: 30/11/2018 19: Author: Adrian Garrido Garcia """ from wall.brick import Brick def build_a_wall(rows=None, bricks=None): wall = "" full_brick = 2 half_brick = 1 mortar = "|" brick_builder = Brick() try: ...
65800fba09d9c89253b8a11211474606cba55eb9
jpinsonault/dfa-runner
/DFA.py
6,352
3.75
4
""" CS311 Author: Joe Pinsonault Contains objects and functions for parsing, creating, running, and validating DFAs. DFAs are stored in `DFA` tuples, which contain the set of states, transition function, and so on. DFAs can be run through the `validate_dfa` function to ensure they've ...
873095dc3cc3264ab8be8dc55181c0ce453a51c2
durwasa-chakraborty/leetcode_challenge
/employee-importance.py
1,854
3.890625
4
#Employee Information # def get_importance(self,employees,id): # q = queue.Queue() # total_importance = 0 # for employee in employees: # total_importance+=employee.importance # q.put([emp for emp in employee.subordinates]) # while not q.empty(): # ...
4f1743654fa5b7641b7848226620ba701a4cc829
demonzyj56/chino
/chino/image.py
1,710
3.609375
4
"""Utilities for loading an image from path, with given options.""" import logging import os import numpy as np import cv2 logger = logging.getLogger(__name__) def imread(filename, dtype=np.float32, scaled=True, gray=False, dsize=None): """Load image from filename. Parameters ---------- filename: st...
6ac5b14f0c4198911be83349f9e7b9f09af23417
hitrzajc/mid_programming
/acm/vaja1.2.py
699
3.78125
4
a = input("") #a = "asdflkjasdlfj" def beauty(n): x = 0 shorter_words = 0 longer_words = 0 for i in n: if i == ' ' or i == ',' or i == '!' or i == '?' or i == '.': if x > 8: longer_words += 1 elif x < 3 and x > 0: shorter_words += 1 ...
2648a1106a52a127c3023f1e5a39f7d8e2efcf9c
mb208/netherlands_border
/utils/db_connect.py
1,116
3.53125
4
""" Function to run sql query from python using psycopg2 requires environment_variables with database parameters set. """ import os import sys import pandas as pd import psycopg2 def query(sql_query): """ connect to PostgreSQL database server with psycopg2 and run query """ conn = None try: conn ...
5601e8891e3871a3b23637ee8f403b1f9a70ebf4
ligregni/coursera
/mathcs/week2/queens.py
917
3.890625
4
# Mathematical Thinking in Computer Science # Week 2 # # Number of solutions for the 8 Queens puzzle. import sys from typing import List, Tuple QUEENS = 8 def is_valid(board: List[int]): for i in range(len(board) - 1): if len(board) - 1 - i == abs(board[-1] - board[i]): return False return True d...
5f3849f4381782e68c155e8af53108b1493c7989
alanrogers/toymetro
/toymetro.py
2,396
3.78125
4
# toymetro: a toy model illustrating the metropolis algorithm. # # Data is (are?) one toss of a coin, which comes up heads. # Likelihood of data is p, the probability of a head. Prior density # of p is uniform, so posterior density is # # p # Pr[p|heads] = -------- = 2p # 1 # ...
091b89ee0138e5ba5f05b7d59f5fade1eb786744
SMS-NED16/pcc-data-vis
/tests/mpl_1000_squares.py
608
3.6875
4
import matplotlib.pyplot as plt x_values = list(range(1, 1001)) y_values = [y ** 2 for y in x_values] #Actual plotting of the scatter plot custom_color = (0.9, 0.5, 0.6) #R G B between 0.0 and 1.0 plt.scatter(x_values, y_values, s=4, c=y_values, edgecolor='none', cmap=plt.cm.Blues) #Figure labelling and axes ad...
3490faed9461e14e03b99893b623d440a7cbb4cd
SMS-NED16/pcc-data-vis
/downloading_data/highs_lows_2.py
1,217
3.71875
4
import csv from matplotlib import pyplot as plt from datetime import datetime filename = 'sitka_weather_2014.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) #creating empty lists to store temps and dates lows, highs, dates = [], [], [] for row in reader: #convert string date to...
bd0d749db6d2b4e045c8cef8e55d7fa1e48bd1eb
SMS-NED16/pcc-data-vis
/pygal/15_10_matplot_die.py
933
3.75
4
import matplotlib.pyplot as plt from die import Die #Creating D6 and storing results of rolling 10000 times die_1 = Die() total_rolls = 500000 results = [] for roll in range(total_rolls): results.append(die_1.roll()) frequencies = [] for value in range(min(results), max(results) + 1): frequency_count = results.cou...
ef03e93acb8702b176e01bef1d1da208d509622e
YuPo13/py_roman
/roman.py
583
3.671875
4
"""module docstring""" def convert(roman_numeral): """function docstring""" basic_symbols = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} decimal_num = 0 for seq, _value in enumerate(roman_numeral): if seq > 0 and basic_symbols[roman_numeral[seq]] > \ basic_sy...
810029cd6876edf8d0c8424fd09ef4ab8ee472e8
nidhinayak86/micromouse
/robot.py
3,042
4.1875
4
import numpy as np import random from algo import AlgoPackage class Robot(object): def __init__(self, maze_dim): ''' Use the initialization function to set up attributes that your robot will use to learn and navigate the maze. Some initial attributes are provided based on common inf...
e4f35b35ae6349085b455c4c37d9c33b6752c789
Forgotten-Forever/Sword-finger-offer
/Binary_tree_to_bidirectional_list.py
1,542
3.640625
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ @author: forgotten_liu @projectName: python_study @file: Binary_tree_to_bidirectional_list @time: 2021/1/5 9:00 @IDE: PyCharm @desc: 二叉搜索树与双向链表 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。 """ class TreeNode: def __init__(self, x): self.val = x ...
07a842ec8a3e7a5b3dfb23ce9f9ec8f30f3d5421
Forgotten-Forever/Sword-finger-offer
/jumpFloorII.py
918
4.03125
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- """ @author: forgotten_liu @projectName: python_study @file: jumpFloorII @time: 2020/12/24 11:03 @IDE: PyCharm @desc: 变态跳台阶 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法 """ # 贪心算法 class Solution2: def jumpFloorII(self, number): arr1, arr2 = 1, 2 ...
7a1eff343eace36e8f04f7dc9dac0176e4b91b3e
chenyingxue0124/pythonFiles
/twoSumのコピー.py
234
3.546875
4
def twoSum(nums,target): adict = {} for i,num in enumerate(nums): if target-num in adict: return adict[target-num],i else: adict.update({num:i}) print(twoSum([3,3,4,5],6))
2b2590dea900a124a6ac024075c099b32de0f49f
chenyingxue0124/pythonFiles
/longestsubstringwrc.py
568
3.609375
4
def lengthOfLongestSubstring(s): start = longestsub = 0 # return the number of substring usedchar = {} # memory the used char for i in range(len(s)): #use the index 不用range的话输出的就是字符了 if s[i] in usedchar and start <= usedchar[s[i]]: start = usedchar[s[i]] + 1 else: lon...
6a2575f9b1f8dc004c0e1af0db2f9c0ffc7a8a2c
chenyingxue0124/pythonFiles
/combinationsum2.py
654
3.515625
4
def combinationSum2(candidates,target): def dfs(nums,target,index,path,res): if target < 0: return if target == 0: res.append(path) return for i in range(index,len(nums)): if i > index and nums[i] == nums[i-1]: continue #continu...
06ae96ea510921ba2d1ed979d6dd2743a1d0fa1c
chenyingxue0124/pythonFiles
/stringtointeger.py
1,464
3.578125
4
def myAtoi(str): if len(str) == 0: return(0) ans = 0 #进行各种标记 number_started = False #进行开头的标记 sign = 1 signflag = False for i in str: #一开始是空格就跳过,中间是空格就终止 if i == " ": if number_started == False: ...
b2a7a14ccf32ece134f0d20b577fc3fcb6b4a132
brittCommit/lab_word_count
/wordcount.py
831
4.21875
4
# put your code here. import sys def get_word_count(file_name): """Will return word count of a given text file. user will enter python3 wordcount.py 'anytextfilehere' on the command line to run the code """ text_file = open(sys.argv[1]) word_count = {} special_charac...
292c63c14fcacd9900f0889072383015958a9574
rajshak123/Algorithms-in-python
/Linkedlist/app.py
526
3.890625
4
from linkedlist import LinkedList LinkedList=LinkedList() LinkedList.insertStart(12) LinkedList.insertStart(34) LinkedList.insertStart(50) print('\n') LinkedList.traverse() LinkedList.insertEnd(90) LinkedList.insertEnd(100) LinkedList.insertEnd(29) print('\n') LinkedList.traverse() # LinkedList.removeStart() # prin...
ce41e171f05fa35d8198ba09139fcd149434a896
vglmarcos/Lenguajes-de-programacion
/Practica python/Palindromo.py
1,546
3.84375
4
#Definicion de variables longitud=None i=None a=None j=None array=[] def main(): print("\nPrograma que determina si una palabra es palindroma o no.\n") while True: while True: #Validamos que solo se introduzcan palabras array=input("\nIntroduzca una palabra: ") if array.isalpha...
e14282c2fe451bc2a6f2121e3f553c5306552763
aljoharrakh/100DaysOfCode
/Day4.py
540
3.5
4
import random IntNum=10 FloNum=5.5 CompNum=1+2j print(IntNum,' number is ',type(IntNum)) print(FloNum,' number is ',type(FloNum)) print(CompNum,' number is ',type(CompNum)) print('***********************************') print('convert',IntNum,' to float is ',float(IntNum)) print('convert',FloNum,' to integer is ',int(Flo...
08afb1bde81d4f4466e825a8b39d77e23ae0f27c
aljoharrakh/100DaysOfCode
/Day18-19.py
1,767
3.9375
4
print("*********welcome to Supermarket**********") menu = ["milk", "bread", "juice", "Vegetables", "cheese", "Fruits"] price = [7, 2, 6, 4, 3, 9] bill = 0 cust = [] finalyOrder=[] while True: ch=int(input("1-Go to shopping\n2-Go for the bag\n3-Delete all contents of the bag\n4-delete specific purpose \n5-Going to p...
ee7e466ffbc9e80aafe766ca8d95918f7db7af33
hosyaeuw/ubit_react
/src/static/test.py
916
3.828125
4
from PIL import Image, ImageDraw image = Image.open('123.jpg') # Открываем изображение draw = ImageDraw.Draw(image) # Создаем инструмент для рисования width = image.size[0] # Определяем ширину height = image.size[1] # Определяем высоту pix = image.load() # Выгружаем значения пикселей for x in range(width): ...
effdce35d2d6086701d72f6244b82ecc46dd65eb
Nightlord851108/HowToSolveIt
/Python/hw9/Circle.py
725
3.765625
4
import Vector import VectorInput import Shape import math class Circle(Shape.Shape): def __init__(self, o, r): if r <= 0: raise Exception("Radius less than zero") self.o = o self.r = r def description(self): s = "{circle, " s += "(" + str(self....
b8397d36b580077337a794991bf083c2003222a6
EgorKurito/little_projects
/NumberGame.py
1,228
4.1875
4
import random # главная функция игры def game(): # генерация случайного числа от 1 до 10 secret_num = random.randint(1, 10) # Список чисел пользователя guesses = [] while len(guesses) < 3: # проверка того, что пользователь ввел число try: # считывание числа пользовател...
9d32a06041706a7aa1305e5dcd053b92a2712c99
anktplwl91/Topic_Modelling
/wikidump_parsing.py
2,834
3.5625
4
''' The Wikidump class is used to create 'vocabulary' of words from the wikipedia corpus provided by 'input_dir_path', count number of documents in the corpus and create a term-document matrix from the corpus. I have removed non-alphabetic tokens, stopwords mentioned in nltk English corpus andd words that have frequenc...
65723298f529a9d0d87ace981ce25ea5aabf6a5c
ademenet/expert_system
/expert_system.py
1,886
3.921875
4
""" TODO: implement backward chaining inference engine. """ from collections import OrderedDict class RulesList(object): """List of rules.""" def __init__(self): self.rules_list = OrderedDict() def add(self): pass class Fact(object): def __init__(self, letter: str, value: bool=False)...
7f975add2af0c547eb50bb7f48d2859c407255a1
photonPrograms/ML-Classification-Problem
/plotcost.py
640
3.703125
4
# plotting the variation of cost function with the number of iterations # to see whether logistic regression is working as expected import matplotlib.pyplot as plt import json filename = "costs.json" with open(filename) as f: cost_list = json.load(f) iterations = range(1, len(cost_list) + 1) plt.style.use("sea...
ec7ed49d6e0ab03ac54e26673be563679e29a106
jamiejamiebobamie/tweet-generator
/test_uppercase.py
2,413
4.09375
4
import sys import string def arrayFileWords(file): """opens a file, puts the words into an array, closes the file and returns the array of strings""" f = open(file, "r") array = f.read().split() f.close() return array def arrayToString(array): """takes in an array and returns the a string ...
fdcf500e0977252b8a4b0eb0545ea30bc561d679
weskerhluffy/closest_ass
/src/closest/parejitas.py
2,245
3.65625
4
''' Created on 06/11/2016 @author: ernesto https://www.hackerrank.com/challenges/closest-numbers/submissions/code/31624162 ''' import sys def insert_sort(numeros): alist=list(numeros) for index in range(1,len(alist)): currentvalue = alist[index] position = index ...
61079b42ce83b6ba48b96cf7d56a5304b8716118
jenjohnson7/CSCI321Chp3-4-5
/CSCI321Chp3/ECycleOfficial.py
2,662
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ rosalind.info Problem 3F @author: michaellinderman """ import sys import copy # 170 minutes def read3F(filename): """Read 3F input""" with open(filename, "r") as file: graph = {} for line in file: a_node, b_nodes = map(str.strip,...
672f5e5307e09e8f05e3a2e1967d334023ecc06f
yalinchou/python
/day03/fib.py
778
3.84375
4
# def mk_fib(): # fib = [0, 1] # n = int(input('请输入数列的长度: ')) # for i in range(n -2): # fib.append(fib[-1] + fib[-2]) # print(fib) # # mk_fib() # mk_fib() # def mk_fib(): # fib = [0, 1] # n = int(input('请输入数列的长度: ')) # for i in range(n -2): # fib.append(fib[-1] + fib[-2]) # ...
686b9aa7d198d63527ab14d4ba6cd4e604af9615
yalinchou/python
/day02/guess.py
321
3.75
4
import random num = random.randint(1,100) counter = 0 while counter < 5: counter += 1 answer = int(input('guess: ')) if answer == num: print('猜对了') break if answer > num : print('猜大了') else: print('猜小了') else: print('正确答案是%s ' % num)
c50af15e0559cf6f96a622d92f56f64828b1003f
sarazwairi/data-structures-and-algorithms
/python/code_challenges/tree_fizz_buzz/tree_fizz_buzz.py
2,952
3.828125
4
# from stack_queue.stack_and_queue import Node,Queue # # from trees.trees import BinaryTree # class Node: # def __init__(self,value): # self.value=value # self.children=[] # def breadth_first(tree): # if tree.root is None: # return [] # queue=Queue() # queue.enqueue(tree.root) #...
22f8f3f61f63a9c1a0c174761c56bfd621a4c915
AnabellJimenez/SQL_python_script
/data_display.py
1,395
4.34375
4
import sqlite3 '''Python file to enter sql code into command line and generate a csv file with the information from the: fertility SQL DB ''' from Database_model import Database import requests import csv #open sqlite3 connection def db_open(filename): return sqlite3.connect(filename) #close sqlite3 connection def ...
4a369eb65883b3df61723eb15d41d52d0e18732c
ravisjoshi/python_snippets
/DataStructure/ReverseLinkedList.py
1,741
4.0625
4
""" Reverse a singly linked list. Input: 1->2->3->4->5->NULL / Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solut...