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 |
|---|---|---|---|---|---|---|
1ebe3c7270be19c680ec51024b10c560289095e4 | ZSerhii/Beetroot.Academy | /Homeworks/calc.py | 5,500 | 4.3125 | 4 | print('Welcome!')
print('Select the operation from the list and enter its marking')
print('''Available operations:
> + - Sum of X and Y
> - - Difference of X and Y
> * - Product of X and Y
> / - Quotient of X and Y
> // - Floored quotient of X and Y
> % - Remainder of X / Y
> neg - X negated
>... |
8a7758d475b264d779dfdbaa14ddee47412f4a8a | ZSerhii/Beetroot.Academy | /Homeworks/classes_homework.py | 9,523 | 3.96875 | 4 | #Beetroot python
# task 1
# Create new class SortedList, by extending standard list functionality to keep it sorted
# on creation, appending new elements, adding another list
# e.g. sorted_list = SortedList([2, 3, 1])
# sorted_list -> [1, 2, 3]
# use following function to test your new class
# test_sorted_list(SortedL... |
af30645406d953795958b806cf529f1ce97150c2 | ZSerhii/Beetroot.Academy | /Homeworks/HW6.py | 2,918 | 4.1875 | 4 | print('Task 1.\n')
print('''Make a program that generates a list that has all squared values of integers
from 1 to 100, i.e., like this: [1, 4, 9, 16, 25, 36, ..., 10000]
''')
print('Result 1:\n')
vResultList = []
for i in range(1, 101):
vResultList.append(i * i)
print('Squared values list of integers from 1 to... |
e302b302c3abee09db6d63ef7aa8e0f1be2ee009 | skylarlegend/project_files | /Python Projects/palindromes_test.py | 842 | 4 | 4 | print '\n\n\n\t\t*****This program tests for Palindromes*****\n'
print 'You can enter as many times as you want.'
decision = 0
while decision != 1:
print '\n\n'
wordEntered = raw_input ('Enter the word: ')
wordListed = list (wordEntered)
wordReversed = wordListed [::-1]
wordStringed = ''.join (w... |
485b0d28dc6bc51c5c993b56968112ad403637b4 | malviyanaman/startercode | /classcode/mapreduce/lowercount.py | 389 | 3.6875 | 4 | from mrjob.job import MRJob
class LowerCount(MRJob):
""" get the counts of words that start with lowercase i """
def mapper(self, key, line):
words = line.split()
for w in words:
if w.startswith('i'):
yield (w, 1)
def reducer(self, key, values):
yield... |
bb998f574c6e17dcde9a60e966f0a25a0de02c1c | xanthorpe/pythonstuff | /hangman.py | 1,953 | 4.0625 | 4 | import random
"""This game plays hangman with the user."""
class Hangman:
def __init__(self):
self.hidden_word = self.find_word()
self.blank_string = "-" * len(self.hidden_word)
self.lives = 6
#For debugging only ;)
print(self.hidden_word)
print(self.blank_string)
... |
5b09c53fccfb250096c51cc9f2fd45b32879ebff | nitesh60/Tictactoe-Game | /Tictactoe.py | 4,772 | 3.5 | 4 | from tkinter import *
from tkinter.messagebox import showinfo
y=""
x=2
player_1 = []
player_2 = []
def define_sign(number):
global x,y
global player_1,player_2
from itertools import permutations
set1=permutations([1,2,3])
set2=permutations([3,5,7])
set3=permutations([1,5,9])
set4=permutati... |
621249e40091e4574019a78cf0682d13c15c585a | JulenZZZ/python-course-1 | /miniprojects/renfe/renfe_flask/controller/renfe.py | 965 | 3.84375 | 4 | """ RENFE """
import renfefunctions as rf
my_station = "Irun"
def main():
print(my_station.upper())
print("----------------")
# option (go | return | monthly)
while True:
opt = rf.print_opt_menu()
if opt != "error":
break
print("Option: " + opt)
# select ... |
4702b4ed37d9a5a2b6e48003777c58bd38541fb0 | jclarkrichards/minimax | /tictactoe.py | 6,067 | 3.6875 | 4 | from random import randint
from gamestate import GameState
from minimax import minimax, Minimax
#==============================================================================
class TicTacToe(GameState):
def __init__(self, state, level=0):
GameState.__init__(self, state, level)
#state is a list wit... |
86a43aee8d0b8c854111cdd9b32d2dd0bafe1725 | gurpreetsingh26/datastructure | /array/intersectarray.py | 893 | 3.78125 | 4 |
"""
Follow same for 6:
Divide and Conquer
solve for 3 and 3
then 2,1 and 2, 1
then 1,1,1 and 1,1,1
"""
def intersect(m,n):
"""
Arrarys are sorted
:param m:
:param n:
:return:
"""
result = []
i = j = 0
while i < len(m) and j < len(n):
if m[i] == n[j]:
result.a... |
dd826d7964ec35b5857860adc174c3d86c74f545 | g-parki/Cowlitz-COVID-Tracking | /main.py | 10,360 | 3.53125 | 4 | from bs4 import BeautifulSoup as bs
from datetime import date, datetime
import requests
import csv
import pandas as pd
import COVIDModule
#load daily data page
try:
source = requests.get('https://www.co.cowlitz.wa.us/2749/COVID-19-Daily-Data-Summary').text
soup = bs(source, 'lxml')
except:
COVIDModule.Send... |
bf86a653c416211c48e80ebaeaf0f6fe32b32fef | baranusluel/hacker-rank | /Artificial Intelligence/Bot Building/BotSavesPrincess2.py | 541 | 3.515625 | 4 | #!/usr/bin/python
def nextMove(r,c,y,x):
if abs(x - c) > abs(y - r):
if x > c:
return "RIGHT"
elif c > x:
return "LEFT"
else:
if y > r:
return "DOWN"
elif r > y:
return "UP"
return ""
n = int(input())
r,c = [int(i) for i in in... |
ba69572b481046b73f0fb53c333870d3f4b9e611 | baranusluel/hacker-rank | /Artificial Intelligence/Bot Building/BotClean.py | 3,013 | 3.828125 | 4 | #!/usr/bin/python
from copy import copy, deepcopy
def next_move(posr, posc, board):
if game_simulator(posr, posc, deepcopy(board), True) < game_simulator(posr, posc, deepcopy(board), False):
return next_move_rows(posr, posc, board)
else:
return next_move_columns(posr, posc, board)
def gam... |
727c1f3b880b6282f4e79c6ef74cf9551b42ad08 | jpmcknz8/cmpt120mckenzie | /calculator1.py | 1,156 | 3.671875 | 4 | # Calculator.py
def getPieces(user_in):
number1 = 0
number2 = 0
for c in user_in:
if c in ['*','/','+','-']:
number1 = float(''.join(user_in[:user_in.index(c)]))
number2 = float(''.join(user_in[user_in.index(c)+1:]))
operator = user_in[user_in.index(c)]
retur... |
6a35ef60803d375ac5a0ec9243cfcf10333e30f5 | Albert840529/SC-Projects | /python_Projects/boggle_game_solver/anagram.py | 3,121 | 4.1875 | 4 | """
File: anagram.py
Name: Albert
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each wor... |
7a92f0852cd054f6ffb1060f709fcc436fabe169 | dbw16/Computer_Simulations_3_HW | /hw4_2.py | 1,780 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def mean_subtractor(x):
for i in range(len(x[0])):
summed = 0
for j in range(len(x)):
summed = summed + x[j][i]
mean = summed / len(x)
for j in range(len(x)):
x[j][i] = x[j][i] - mean
return x
x = np.array([[4.,2.,.6],[4.2,2.1,.59],[3.9,... |
e6d9fb65e87873292769ac5a51f4b810b672034c | nicoj-l/minesweeper-GUI | /minesweeper_nicolasjimenez-lozano.recursive.3.py | 11,173 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 11:25:27 2019
@author: nj2418
"""
import time
import random
import copy
import string
from pprint import pprint
start_time = time.time()
print("to start the game type in game_mode(dif)")
#from pprint import pprint
#width = int(input("what is the width... |
81f93d82895ffb9b63771e9b2b3c021ddbd5712c | pawanpp13/Python-Assignments | /Assignment4/Assignment4_2.py | 203 | 3.71875 | 4 |
fp = lambda no1,no2 : no1*no2
def main():
value1=int(input("enter 1 no"))
value2 = int(input("enter 2nd no"))
ret = fp(value1,value2)
print(ret)
if __name__=='__main__':
main();
|
e3c5c8e5bf548412a18355bbd80f438af6d90893 | Samuel-Hayes/cp1404practicals | /prac_02/files.py | 397 | 3.90625 | 4 | name = str(input("Please enter your name: "))
out_file = open('name.txt', 'w')
print(name, file=out_file)
out_file.close()
in_file = open('name.txt', 'r')
read_name = in_file.readline()
print("Your name is {}".format(read_name))
in_file.close()
number_file = open('numbers.txt', 'r')
total = 0
for line in number_file:... |
0756cf276a827609f6c12bd0a5d9e61d8082a7a6 | Samuel-Hayes/cp1404practicals | /prac_04/lists_warmup.py | 371 | 3.953125 | 4 | #numbers[0] gives 3
#numbers[-1] gives 2
#numbers[3] gives 1
#numbers[:-1] gives [3, 1, 4, 1, 5, 9]
#numbers[3:4} gives 1
#5 in numbers gives True
#7 in numbers gives False
#"3" in numbers False
#numbers + [6, 5, 3] gives [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers[0] = 10
numbers[-1] = 1
pri... |
509edb5600983c26a9bd41c51f72a5fe5ae0e341 | anikethdevarasetty/Movie-Watchlist | /movieWatchlist.py | 13,261 | 3.765625 | 4 | import tkinter
import tkinter.messagebox
import pickle
import movieClass
root = tkinter.Tk()
root.title("Movie Watchlist")
#functions
#add
def addToOne():
movie = entryMov.get()
if movie != "":
newMov = movieClass.movieObj(movie) #new movie
entryMov.delete(0,tkinter.END)
... |
64894571b57ec1784ec680c0196dcc02d6944b5e | priyarajkumar4/HAB | /coordfinder.py | 1,015 | 3.5625 | 4 | # import simplekml
'''
Takes in a string e.g '3752.45N/12215.48W' and parses it to
latitude and longitude
'''
og_str = input('Enter a Lat and Long in degrees decimal minutes as one string: ')
#Split string into N and W
for i in range(len(og_str)):
if og_str[i] == '/':
middle = i
og_north = og_str[:middle... |
7da20b1ae605d176ddfcca508669dd781a101d13 | luzgool/ReachMaster | /software/ReachSplitter/Classification_Visualization.py | 6,823 | 3.765625 | 4 | """
Written by Brett Nelson, UC Berkeley/ Lawrence Berkeley National Labs, NSDS Lab 12/8/2020
Functions to visualize classifier and segmentation model results using the yellowbrick library.
Functions are designed to work with a classifier of your choice.
Edited: 12/14/2020
"""
from sklearn.metrics im... |
805095d9ee3558abe9059c73bd08b432e872be01 | erictseng89/CS50_2021 | /week6/meow.py | 62 | 3.625 | 4 | # To print "meow" three times
for i in range(3):
print(meow) |
4cc9d559c7a44cd2f500a60548fc6b98294828f0 | erictseng89/CS50_2021 | /week6/scores.py | 769 | 4.125 | 4 | scores = [72, 73, 33]
""" print("Average: " + (sum(scores) / len(scores))) """
# The "len" will return the number of values in a given list.
# The above will return the error:
# TypeError: can only concatenate str (not "float") to str
# This is because python does not like to concatenate a float value to a string.
... |
b8c1194ac09ffc895485cffeb85ad10904d0939b | erictseng89/CS50_2021 | /pset6/test.py | 69 | 3.59375 | 4 | number = input("Number: ")
x = (int(number[0] + number[1]))
print(x)
|
daf361313ec36b17c5bcda8915c61723a813ecbd | bloobglob/AWG | /AWG_App_py2.py | 19,665 | 3.734375 | 4 | # Title: AWG - Akemi's Word Game
# Author: Daniel Commins
# Date: June 13, 2015
# Files: AWG_App_py2.py; SINGLE.TXT (dictionary words file)
# Tested: python 2.61
# Info: Akemi's Word Game: The game where you try and guess the computer's randomly
# selected word! Each letter appears only once.
import sys... |
068719713cfd2dabcba7856ad9978d4f9271afe4 | kuzhi1900/PythonLesson | /lesson01/ColorSpiral.py | 405 | 3.546875 | 4 | # ColorSpiral.py
import turtle
sum = 0
for x in range(1, 101):
sum = sum + x
print(sum)
pen = turtle.Pen()
pen.pencolor("yellow")
pen.width(2)
turtle.bgcolor("black")
# sides = 4
for x in range(0, 100):
pen.forward(x*4)
pen.left(46)
pen.forward(x)
pen.right(180)
# pen.forward(100)
# pen.left(90)
#... |
666261d24cbadd1743d97e6124f32c15c5ea118b | mmsesay/SaloneHackathon2019-Tasks | /departure.py | 2,995 | 3.78125 | 4 | #!/usr/bin/python3
import csv
import json
import time
import requests
import plotly.graph_objects as go
# all departure flights
def departures(airport):
# these variables will hold the departure and arrivals
estDept = ''
estArrival = ''
# hese variables will hold the latitude and longitude cordinates... |
d91f68afa62c70ee07c80f4c830a2e3dccf68ef4 | mzdesa/me100 | /lab3/blink.py | 413 | 3.640625 | 4 | from board import LED
from machine import Pin
import time
#initialize the GPIO pin number 14, store it in the variable pin_14
pin_14 = Pin(14, mode = Pin.OUT)
#cycle the square wave 300 times
i = 0 #counter variable
t = 0.002 #time to hold an output for
while i<3000:
pin_14(1) #hold at a high value for t seconds
... |
72548593092cdbc2ddb64d76951d71d4a89b93e3 | mzdesa/me100 | /hw1/guessNum.py | 599 | 4.21875 | 4 | #write a python program that asks a user to guess an integer between 1 and 15!
import random
random_num = random.randint(1,15) #generates a random int between 0 and 15
guess = None #generate an empty variable
count = 0
while guess != random_num:
count+=1
guess = int(input('Take a guess: '))
if guess == rand... |
3f9dc9d9ed2bfe40227b131a3f4e84fcd0b118cb | shreetiranjit/TNT | /log_in.py | 6,637 | 3.78125 | 4 | from tkinter import *
from tkinter import messagebox
import os
from registration import registrationform
def login_success():
messagebox.showinfo(screen, "Login Successful")
screen2.destroy()
registrationform()
def password_not_recognised():
messagebox.showwarning('ALERT', 'INCORRECT PASSWORD.')
def use... |
ee9607fd9c4bac99372ddd0ffa69099e28e7fcfd | robban112/ML1-Lab2 | /testdata_generator.py | 2,436 | 3.65625 | 4 | import numpy
from random import shuffle
from collections import namedtuple
"""Module usage:
1. First call one of the `test_classes_x` functions, to get data points divided
into two classes, a class A and a class B.
2. Then to get the actual input data to the svm, pass the two classes received from
the previous step ... |
5b42e00b65ee0274dc8b812547f04e7e5b1d9cbb | SCU-AIBOX/AIBox-Server | /app/modules/time_transfer/chin2time.py | 5,771 | 3.625 | 4 | from datetime import datetime, date, timedelta
def chinweekday2int(chin_weekday):
'''中文數字轉阿拉伯數字
Args:
(string)chin_weekday: 中文數字
Returns:
(int)阿拉伯數字
'''
if chin_weekday == '一':
return 1
elif chin_weekday == '二':
return 2
elif chin_weekday == '三':
retu... |
fc713b8149bd3ed93e3653dd4f10ecf828c33597 | nestorcolt/smartninja-april-2020 | /Lesson_001/lesson_001.py | 1,316 | 3.9375 | 4 | # Variables
##############################################################################################
link_to_video = r"https://www.loom.com/share/21b1000ad71b40bea7f086a9aab4a510"
github = "https://github.com/nestorcolt/smartninja-april-2020"
x = 10
y = 7
result = x + y
# print(result)
# Variables more than nu... |
5d63c7dec436ebe38c41925d0b42c1791660fbdf | MeiSee/1050321 | /test.py | 1,401 | 3.578125 | 4 | from random import randint
chance = input("1 先手 2 後手:")
chance = int(chance) % 2 # 0後手 1先手
rows = [ str(i) for i in range(1, 10) ]
turn = chance
def check_win(data):
for i in range(3):
if data[i*3] == data[i*3 + 1] and data[i*3+1] == data[i*3 + 2]:
return data[i]
if data[i] == data[i... |
0fd73143540a8dc5af23f239f08dcb351825b3c9 | Universe-Liu/Python | /Algorithm/0425_basechange.py | 126 | 3.578125 | 4 | def sumBase(n,k):
ans=[]
while(n):
ans.append(n%k)
n=int(n/k)
return sum(ans)
print(sumBase(34,6)) |
c21ae2d023b1bc2d89c19ad82d4fdd544f8a076c | adugyan/IRIS | /Earthquake Cross Section/xsect.py | 955 | 3.515625 | 4 | import os
import pandas as pd
import matplotlib.pyplot as plt
#Use the IRIS FetchEvent tool to download the hypocenters for a thin slice of earthquakes in the Oaxaca area of Mexico. I used longitude range restricted to between -94.5 and -94, while the latitude range would be from 14 to 19. Magnitudes greater than 4 sh... |
cf6da19b016553c9767895e31f7466f2494ce42f | NataliaKozlikova/python_basic_22_10_2020 | /homeworks/les1/task4.py | 630 | 3.84375 | 4 | """
4.Пользователь вводит целое положительное число.
Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.
"""
while True:
user_num = input("Введите целое число\n>>>")
if user_num.isdigit():
user_num = int(user_num)
break
print('Ошибка! Введено н... |
18c78ba941d203da8047f079edeed32604e73a70 | NicholasPaquin/Machine_Learning-Computational_Mathematics | /operations.py | 483 | 3.5 | 4 | class Basic:
def assign(val):
return val
def add(vals):
sum = 0
for i in vals:
sum += i
return sum
class ActivationFunctions:
def relu(self, weight):
return weight if weight > 0 else 0
def sigmoid(self, weight):
pass
def l_relu(self, ... |
53353bb02e66a3aac3f43e061d27e84c5a13c28b | dh4gan/luce | /plot/show_orbit.py | 5,852 | 3.59375 | 4 | '''
Created on Apr 16, 2013
@author: David Harvey
Plot the orbits of the bodies in the system
'''
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from sys import argv
from matplotlib import pyplot as plt
import io_nbody_EBM as io_nbody
from time import sleep
def show_orbit():
# Data file rea... |
11167786282d10c1f2995c3a931b50f8b9e26215 | ATT-Bub/pdsnd_github | /bikeshare_2.py | 10,505 | 4.28125 | 4 | # Andrew Bub
import time
import pandas as pd
import numpy as np
import datetime as dt
import calendar
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
# --------------------------------------------------------------------------... |
05a37b567510c72f19ff5b22725c9e909b2f65f8 | abrolon87/Python-Crash-Course | /p143.py | 1,167 | 3.671875 | 4 | def greet_users(names):
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
#modifying lists in function
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
... |
e7011a00db9e29abb6e8ad19259dfcacc1423525 | abrolon87/Python-Crash-Course | /useInput.py | 1,219 | 4.28125 | 4 | message = input("Tell me something, and I will repeat it back to you: ")
print (message)
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
#prompt += "\nWhat is your age? " this do... |
d7b3a32e23fb19af3f206e0ec888fe34ecfd0b4d | Allen-Whitt/python | /CPCKata/VoteCounter.py | 1,324 | 3.640625 | 4 | import sys
import math
electionDate = 12*30-4 # 356
voteArr = []
retArr = []
def getArray():
global voteArr
# If given a string of inputs as command line args, go ahead
# Input must be comma separated and have no spaces
if len(sys.argv) > 1:
# Make sure it's a valid array
if any(elem.upper() not in ['M... |
f6354f1ed5ed36dbc30bf9b646854e45322ab092 | dillonp23/CSPT19_Sprint_3 | /sprint_challenge.py | 3,123 | 3.75 | 4 |
""" Sprint Challenge 3 - Data Structures & Algorithms II """
"""
Exercise 1: You are given the root node of a binary search tree (BST).
You need to write a function that returns the sum of values of all the nodes with a value between lower and upper (inclusive).
The BST is guaranteed to have unique values.
* Exa... |
1957711865e1570ed423c327f288ce8a12d2fe50 | jacquelinefedyk/team3 | /examples_unittest/area_square.py | 284 | 4.21875 | 4 | def area_squa(l):
"""Calculates the area of a square with given side length l.
:Input: Side length of the square l (float, >=0)
:Returns: Area of the square A (float)."""
if l < 0:
raise ValueError("The side length must be >= 0.")
A = l**2
return A
|
5076cd32913ff0675e96cb80b9eda912edc5c7e2 | jacquelinefedyk/team3 | /examples_unittest/test_area_triangle.py | 525 | 3.671875 | 4 | import unittest
import area_triangle as trA
class test_area_triangle(unittest.TestCase):
def test_area_tr(self):
""""Test the area values against a reference for b >= 0 and h >= 0."""
self.assertEqual(trA.area_tr(10,12),60)
self.assertEqual(trA.area_tr(8,6),24)
self.assertEqual(trA... |
0830b10177f4ca8715e6c9f1b55a46695de9205f | trev155/ruminations | /red_wine/redwine_visualization.py | 2,921 | 3.765625 | 4 | """
Using the Red Wine Dataset, from https://www.kaggle.com/piyushgoyal443/red-wine-dataset.
The dependent variable is "quality", the last column of the csv.
All other columns are predictors.
See the associated .txt file for more information on the data.
"""
# -- Import Libraries
import numpy as np
import matplotlib... |
a957e7f81f52bc56d9af1cd63a284f2e597c6f9d | JohnAsare/functionHomework | /upLow.py | 766 | 4.15625 | 4 | # John Asare
# Jun 19 2020
""" Write a Python function that accepts a string and calculates the number of upper case letters and
lower case letters.
Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'
Expected Output :
No. of Upper case characters : 4
No. of Lower case Characters : 33 """
def up_low(... |
c522d3b8879862fea2def5775f6321b35c1bdfa6 | Loopmootin/Python | /FunctionalPython/FunctionalPython.py | 2,982 | 3.90625 | 4 | import functools
numbers = [1, 2, 3, 4]
dogs = ["Fido", "Pluto", "Lady"]
# Non functional (how to do)
total = 0
for number in numbers:
total += number
print(total)
# Functional (what you want)
print(sum(numbers))
# Functional without the readymade sum
print(functools.reduce(lambda mysum, x: mysum + x, numbers)... |
e4fe0fbdf318b38ff03816f71979858e7dec6775 | Loopmootin/Python | /LoopsListsFunctionsMath/functions.py | 480 | 3.640625 | 4 | import math
# Hello
def hello(name):
n = len(name)
print("-" * (n + 8))
print("Hello", name, "!")
print("-" * (n + 8))
hello("Hugo")
print()
# Function and main
def bottlevolume(height, diameter):
volume = height * math.pi * diameter**2 / 4
return volume
def main():
first = bottle... |
1271f66ffb283518d6ba80292d579d12506456c2 | Loopmootin/Python | /Tkinter/tKinterGraphics.py | 1,675 | 3.796875 | 4 | from tkinter import *
# draw flag
def flag(flagcanvas):
flagcanvas.create_rectangle(40, 40, 100, 100, fill="red", outline="red")
flagcanvas.create_rectangle(100, 40, 120, 100, fill="white", outline="white")
flagcanvas.create_rectangle(120, 40, 210, 100, fill="red", outline="red")
flagcanvas.create_re... |
9aade646c8a5e8b1f17ebcfca11f7444fc349117 | JRMfer/Bachelorthesis | /fixed_strategies/agent_test.py | 9,942 | 3.796875 | 4 | # AGENT
# Julien Fer
# University of Amsterdam
#
# This script contains the functionality to computationally visualize either a
# ZI-U, ZI-C or Kaplan agent.
from random import randint
from math import inf
class Agent(object):
"""
This is a representation of
a financial agent (buyer/seller).
"""
... |
bdca36532da7a5bef5cedb4675837b1e36fb3a0c | SuvroBaner/Big-Data-with-Apache-Spark-and-Python | /ml_ratings-counter.py | 1,741 | 3.671875 | 4 | # SparkContext : Fundamental to create RDDs
# SparkConf : It helps create SparkContext, like to run on a standalone computer or a cluster.
# collections : Python package for sorting
from pyspark import SparkConf, SparkContext
import collections
# Create the Spark Context
conf = SparkConf().setMaster("local").setAppNa... |
f4746fe42d069dc24f047c25925579d64544bb22 | davnav/crackingthecodinginterview | /chapter1/coinexchange.py | 2,998 | 3.890625 | 4 | #minimum coin exchange problem
#coins of different denominations & Amount
#Find a minimum number of coins to make change of given amount
#*********Solution1************
# print("********greedy approch****soluion won't be accurate always***")
#we will see how to use greedy approch which may be not accuate alwaysdatet... |
f6c4075e9ac554eca90226cc7f37459523c9c8a2 | davnav/crackingthecodinginterview | /chapter1/stringuniqe.py | 1,445 | 4.03125 | 4 | #Implement an algorithm to determine if a string has all unique characters. What if you
#can not use additional data structures?
#
#***********Solution1**********
print("***********Solution1**********")
s = raw_input("enter an input value:")
l = len(s)
print(type(l))
# s = s.sort()
# unique = True
def isUniq... |
3c1c3d25df123d6a6cef1ae6e54294968874f324 | playpauseandstop/tddspry | /tddspry/utils.py | 2,144 | 3.5 | 4 | import re
__all__ = ('camelcase_to_underscore', 'process_re_flags',
'underscore_to_camelcase')
RE_FLAGS = {'i': re.I, 'l': re.L, 'm': re.M, 's': re.S, 'u': re.U, 'x': re.X}
def camelcase_to_underscore(name):
"""
Convert old-style camel-case method names to new-style names with
underscores.
... |
f58e46485ba265f592646ef5715d6df1d7fbbd2c | DavideCanton/pyIA | /labyrinth/labyrinth.py | 20,016 | 3.953125 | 4 | from math import sqrt
from typing import Tuple, Callable, List
import numpy as np
from PIL import Image
U = np.array([0, -1])
L = np.array([-1, 0])
D = -U
R = -L
UL, UR = U + L, U + R
DL, DR = D + L, D + R
SQRT_2 = sqrt(2)
Node = Tuple[int, int]
def manhattan(goal: Node, _: Node) -> Callable[[Node], float]:
"... |
8041495dbf1109f17637f0e7ac1b24633425f020 | fpaupier/RapLyrics-Scraper | /pre_processing/analysis.py | 877 | 3.609375 | 4 | """Consume functions from utilities to analyse the dataset"""
from utils import occurences_counter
def main():
"""Add other relevant function calls for dataset analysis"""
occurences = occurences_counter('lyrics_US/dataset3-processed.txt')
# TODO hardcode your last results if you want
print("Number o... |
ea4de243979aedfeb87bdad4101ff5dd445b44b7 | ericjiang97/common-algorithms | /Sorting Algorithms/Quicksort/quicksort.py | 1,172 | 4.03125 | 4 | import time
def quickSort(alist, first, last):
'''
Recusive QuickSort Alogrithm
:param alist: the list to be sorted
:param first: the first position
:param last: the final position of the list
:return: the sorted list
'''
if (last - first) > 1:
# find pivot positioon
pivo... |
915217af9904d2a58b3c9b4069859c8538150350 | yoongi0428/algorithm_ps | /5_longest_ palindromic.py | 771 | 3.625 | 4 | """
https://leetcode.com/problems/longest-palindromic-substring/
"""
class Solution:
def longestPalindrome(self, s: str) -> str:
# exception: length 1
if len(s) == 1 or s == s[::-1]:
return s
def expand(s, left, right):
while left >= 0 and right <= len(s) and... |
c4ef0db8fe24decc9a24a0272d95aab0b5923b6d | yoongi0428/algorithm_ps | /49_group_anagram.py | 784 | 3.71875 | 4 | """
https://leetcode.com/problems/group-anagrams/
"""
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if len(strs) == 1:
return [strs]
idx_dict = {}
answer = []
# for each word
for string in strs:
... |
6b0ce62f85bc9ba881f4a391bdde5742537a6d7d | yoongi0428/algorithm_ps | /20_valid_paranthesis.py | 813 | 3.6875 | 4 | """
https://leetcode.com/problems/valid-parentheses/
"""
from collections import defaultdict
class Solution:
def isValid(self, s: str) -> bool:
stack = []
close_to_open = {']': '[', '}': '{', ')':'('}
def is_open(c):
return c in ['(', '{', '[']
ans = True
for c... |
f5306409b6be76bdc3ce5789daafcca973fdb971 | kelvinng213/PythonDailyChallenge | /Day09Challenge.py | 311 | 4.1875 | 4 | #Given a string, add or subtract numbers and return the answer.
#Example:
#Input: 1plus2plus3minus4
#Output: 2
#Input: 2minus6plus4plus7
#Output: 7
def evaltoexpression(s):
s = s.replace('plus','+')
s = s.replace('minus','-')
return eval(s)
print(evaltoexpression('1plus2plus3minus4')) |
e082eb4ff18f0f3a19576a5e3e346227ba98ebf8 | kelvinng213/PythonDailyChallenge | /Day02Challenge.py | 894 | 4.53125 | 5 | # Create a function that estimates the weight loss of a person using a certain weight loss program
# with their gender, current weight and how many weeks they plan to do the program as input.
# If the person follows the weight loss program, men can lose 1.5% of their body weight per week while
# women can lose 1.2% o... |
ec5885d44806f07df5347af756425775d490d36f | kelvinng213/PythonDailyChallenge | /Day15Challenge.py | 940 | 3.984375 | 4 | # Given two lists of any data type,
# return a list that combines the two lists by alternating the elements
# passed. The input lists can be of different lengths.
lst1 = [1,2,3,4,5,6,7]
length1 = len(lst1)
lst2 = ['a','b','c','d','e','f','g','h','i']
length2 = len(lst2)
difference = length1 - length2
lst = []
lst... |
3f43708adf18b649efab06f3f0aaf21de64c5171 | jkraenzle/datasource | /portal/objects.py | 32,745 | 3.65625 | 4 | """
Portal's REST API has a defined set of "Models" that are used in GET and POST operations,
typically in JSON format.
This file creates Python classes, and their associated attributes, that map to each Model.
The attributes are defined as dictionaries, or lists of dictionaries, as each Model is
de... |
bb8a8fc6bb51637c9f27f2b7f0dfe81fd06dfefb | alsanhory/python1 | /star1.py | 104 | 3.515625 | 4 | for i in range (1,7):
strrr=""
for k in range(1,i):
strrr+="*"
print(strrr)
|
1a22cb221890079fd7521e45ab85a39afee6ab27 | alsanhory/python1 | /fun4.py | 187 | 3.5625 | 4 | def sayhi():
print("Hello nafisa")
sayhi()
sayhi()
sayhi()
def average(n1,n2,n3):
total=n1+n2+n3
avg=total/3
return avg
print(average(3,4,5))
a= average(15,20,25)
print(a) |
b1a5cd9be063ed13e7384386c9a73d303d636e14 | alsanhory/python1 | /dictionary1.py | 198 | 4 | 4 | employee={'name':"Nafo","age":29,"address":"Bahry"}
employee['address']="Mamoura"
employee["haja"]= "bs kida"
print(employee)
for i in employee:
print (employee[i])
print("hajaaa" in employee) |
0d191483d4e31b6c610e3d0d84aaea306feff97e | lucyyu24/operation-fun-times | /CoraNotebook/RecursionDP/ctcMagicIndex.py | 494 | 3.984375 | 4 | '''
Magic Index: Given a sorted array of distinct integers, write a method to find a magic index a[i] = i.
'''
def findIndex(n, start, end):
if start == end:
midIndex = start
else:
midIndex = (start+end)//2
if midIndex == n[midIndex]:
return midIndex
elif start == end:
return None
elif midIndex > n[midIn... |
20071ee409c50fa6559526cc314b04fa45e23a68 | lucyyu24/operation-fun-times | /CoraNotebook/RecursionDP/ctcSubset.py | 495 | 3.8125 | 4 | '''
Return all subsets of a set.
(Used an array instead of a set - TODO just use sets)
'''
def binToSet(b, s):
subset = []
bStr = str(b)
for i in range(len(s)):
if bStr[i] == '1':
subset.append(s[i])
return subset
def findSubsets(inp):
inSize = '{0:0' + str(len(inp)) + 'b}' # trust; it works
allSubsets = [... |
14eb0117f986d979f4e9d20b5d4f78bcd01b83f1 | eduardoramirez/Microsoft-Coding-Challenge | /NDrome/NDrome.py | 1,228 | 3.53125 | 4 | import sys
def isEqual(m,n):
length = len(n)
for i in range(0, length):
if m[i] != n[i]:
return False
return True
def isPali(n):
return n == n[::-1]
##str = raw_input("String: ")##sys.stdin.read(1)
inputs = ["ab|1",
"123456123455|6",
"123456789987654321|9",
"1234abcd|4",
"1234567891234... |
b220ee448818f39e4edd9680972fd9206eda0c28 | savvy379/egamma | /egamma/models/nn.py | 1,747 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Utilities for creating simple neural network models.
"""
# Keras import(s)
from keras.models import Model
from keras.layers import Input, BatchNormalization, Dense, Dropout
def nn_ (num_features, num_layers=3, num_nodes=16, num_outputs=1, activation_inner='relu', activation='sigmoid', b... |
94afaa7896775081f9bffe2b4a76692a0ce9f835 | rogerevansNLTG/traces-through-time | /ttt/date.py | 2,377 | 3.8125 | 4 | """
Stupid way of getting dates with coarse grained resolution
"""
# author: Eric Kow
# license: Public domain
from dateutil.parser import parse as dparse
import datetime
import itertools
_FAR_AWAY = 9999
_DEFAULT_DATE_1 = datetime.datetime(_FAR_AWAY, 1, 1)
_DEFAULT_DATE_2 = datetime.datetime(_FAR_AWAY, 2, 15)
d... |
f298ca010f286f7f737152b4beb7926695b75796 | mohdaliriaz/New_Project | /guessing.py | 458 | 3.890625 | 4 | forbidden_num = 667
guess = input("guess a digit 1-1000 ")
print("your digit is " + str(guess) + " try again")
#+ str(forbidden_num))
while True:
if int(guess) > 500:
print("guess lower")
#break
if int(guess) < 668:
print("guess higher")
#break
if type(guess) != in... |
889e622e0a513a4b64a3324de650079557a367a8 | gjorando/AdventOfCode2018 | /day8/1.py | 1,301 | 3.71875 | 4 | #!/usr/bin/env python3
with open("input") as input_file:
input_list = input_file.readline().replace("\n", "").split(" ")
input_list = [int(elem) for elem in input_list]
def new_node():
return {"children": [], "metadata": []}
def process_children(input_list, output_tree):
"""
Computes the chil... |
d7b545cd2d5fae12a20fc16e267883043b790dcc | gjorando/AdventOfCode2018 | /day1/2.py | 510 | 3.828125 | 4 | #!/usr/bin/env python3
reached_frequencies = set()
input_frequencies = []
result = 0
reached_twice = False
with open("input") as input_file:
for _, freq in enumerate(input_file):
input_frequencies.append(int(freq))
while not reached_twice:
for frequency in input_frequencies:
result+= frequenc... |
2704379bb901d51976ab93a67cb53adec5454725 | gjorando/AdventOfCode2018 | /day9/1.py | 965 | 3.640625 | 4 | #!/usr/bin/env python3
import re
matching_regex = re.compile("(?P<num_players>\d+) players; last marble is worth (?P<num_marbles>\d+) points")
with open("input") as input_file:
matched_values = matching_regex.match(input_file.readline().replace("\n", ""))
num_players = int(matched_values.group("num_players")... |
357acc4d7f0c75bfce20693eef50f2c4b350cc79 | rsoemardja/Udacity | /Intro to Programming Nanodegree Program/04. Intro to Python, Part 1/01 Turtles and Code/07 shapes/two.py | 125 | 3.515625 | 4 | import turtle
amy = turtle.Turtle()
amy.color("green")
for side in [1, 2, 3, 4, 5]:
amy.forward(100)
amy.right(72)
|
22eaecec798e9007e960decf49d772009926f6af | rsoemardja/Udacity | /Intro to Programming Nanodegree Program/04. Intro to Python, Part 1/03 Functions Part 2/18 if and elif/workspace.py | 307 | 3.875 | 4 | mood = "happy"
import turtle
riley = turtle.Turtle()
riley.width(5)
# Add your code here.
#solution with if statement
if mood == "happy":
riley.color("yellow")
elif mood == "sad":
riley.color("blue")
else:
riley.color("gray")
for side in range(5):
riley.forward(100)
riley.right(144) |
7148aaa638286c6f5815dfe1738d81a54a3ac750 | rsoemardja/Udacity | /Intro to Programming Nanodegree Program/07. Intro to Python, Part 3/03 Objects & Classes/05 Defining a new class 2/animals (2).py | 191 | 3.59375 | 4 | class Dog:
def speak(self):
print("Woof!")
def eat(self, food):
if food == "biscuit":
print("Yummy!")
else:
print("That's not food!")
|
c92e395a10bbdcf2fab3e14e6b75fe0adace389b | rsoemardja/Udacity | /Intro to Programming Nanodegree Program/04. Intro to Python, Part 1/03 Functions Part 2/05 modulo 2/11b_stairs.py | 290 | 4.03125 | 4 | # Write code to draw the staircase
# pattern above. The modulo operation
# might be useful!
import turtle
t = turtle.Turtle()
t.width(5)
t.color("limegreen")
for step in range(21):
t.forward(10)
if step % 2 == 0:
t.left(90)
else:
t.right(90)
t.hideturtle() |
b8cb5c57f701a8933e5626f07a4d12a2699e23c4 | rsoemardja/Udacity | /Intro to Programming Nanodegree Program/04. Intro to Python, Part 1/03 Functions Part 2/02 Conditionals in loops/workspace.py | 382 | 3.859375 | 4 | #import turtle
#jack = turtle.Turtle()
#jack.width(5)
#jack.color("yellow")
#for side in range(4):
# jack.forward(100)
# jack.right(90)
# solution
import turtle
jack = turtle.Turtle()
jack.width(5)
jack.color("yellow")
for side in range(4):
if side == 1:
jack.color("blue")
if side == 2:
... |
c23f7e99c4407ca25c5b4710e566fa5684a65f77 | rsoemardja/Udacity | /Intro to Programming Nanodegree Program/04. Intro to Python, Part 1/02 Functions Part 1/10 draw_square define/draw_square.py | 339 | 3.984375 | 4 | # sample
#import turtle
#jack = turtle.Turtle()
#jack.color("yellow")
# answer
import turtle
jack = turtle.Turtle()
jack.color("yellow")
jack.speed(0)
def draw_square():
for side in range(4):
jack.forward(100)
jack.right(90)
for square in range(80):
draw_square()
jack.forward(5)
jack.le... |
298eb3a215df05c2d75b3e14a1c8a12a4a201897 | kamail05/MyProject | /writedataintoexcel.py | 782 | 3.78125 | 4 | import openpyxl
# Creating object for the workbook to use it.
wb = openpyxl.Workbook()
# Verifying the current active sheet name
sh = wb.active
print(sh.title)
# Changing the sheet name in excel
sh.title="HelloTestingworld"
print(sh.title)
# Entering the value into the excel
# By selecting the cell and se... |
4cd295a920a50b3d2a14f6ecc63d75992914566d | novel62/helloword | /flowch4.py | 390 | 3.703125 | 4 | # Masukkan sebuah bilangan
# Bagi bilangan tersebut dengan 2
# Jika sisa pembagian = 0 maka bilangan tersebut adalah bilangan genap
# Jika sisa pembagian = 1 maka bilangan tersebut adalah bilangan ganjil
bil = int(input('masukkan bilangan ='))
sisa = bil % 2
if sisa == 0:
print('bilangan tersebut adalah gena... |
998f1c98f4baaaa9a996017bbd5ea050c4c9ad09 | cruiser10/investment-project | /test.py | 1,764 | 3.515625 | 4 | import pandas as pd
investment = pd.read_csv("./investment.csv")
budget = pd.read_csv("./Budget.csv")
#print(budget)
budget.isnull() # to check if there are null values
budget.fillna(value='NO',inplace=True) # replacing null values with "NO"
#print(budget)
# now converting date to datetime format
investment... |
61a5e199053e7293c33ff13f9095ed0aa629b118 | umtkrl1993/AlgorithmsAndDataStructures | /work_algo/trie.py | 4,904 | 3.578125 | 4 |
CHAR_NUMBER = 26
class Node():
def __init__(self, value):
self.value = value
self.children = [ None for i in xrange(0,CHAR_NUMBER) ]
self.end_word = False
class Trie():
def __init__(self):
self.root = Node(None)
def contains(self, word):
current = self.root
for i in xrange... |
45f5407c770e494c7d9be2fbcbf1802e56c74e21 | rohan-krishna/dsapractice | /arrays/array_rotate.py | 533 | 4.125 | 4 | # for the sake of simplicity, we'll use python list
# this is also known as Left Shifting of Arrays
def rotateArray(arr, d):
# arr = the input array
# d = number of rotations
shift_elements = arr[0:d]
arr[:d] = []
arr.extend(shift_elements)
return arr
if __name__ == "__main__":
print("How m... |
99007176dc2a146e9544aa3dfef500371ac2c0ef | 123kfk/JetBrains-Academy | /Smart Calculator.py | 4,633 | 3.640625 | 4 | # diccionario que va a guardar la variables
Dic_variables = {}
from collections import deque
def isOperand(n: str):
operators = ['+', '-', '*', '/', '(', ')']
return True if n not in operators else False
def isLeftParenthesis(n: str):
return True if n == '(' else False
def isRightParen... |
db22f50b551b01bfff78364b11a40ec76cf0b193 | Anusha-Hegde/Trello | /Card.py | 889 | 3.609375 | 4 | from User import User
class Card:
def __init__(self,Id):
self.name = ""
self.Id = Id
self.description = ""
self.user=None
def setName(self,name):
self.name = name
def setDescription(self,desc):
self.description = desc
def isAssUser(self) -> bool:
... |
51449de737ef703fa0e6c94ab6d6c02213f4a538 | allamberto/cse-30872-fa18-contest-ii | /ChallengeE/program.py | 851 | 3.625 | 4 | #!/usr/bin/env python3
import sys
import math
# Functions
# Main Execution
if __name__ == "__main__":
for line in sys.stdin:
X, Y = map(int, line.split())
numbers = list(range(X, Y + 1))
hops = 0
step = 0
curr = numbers[0]
target = numbers[-1]
greatestStep ... |
fa61c4fa8db1b4941965419e2dc4cbfcfad5c581 | YaKobel/Testing | /test_unittest.py | 659 | 3.671875 | 4 | import unittest
from full_name import full_name
class NameTestCase(unittest.TestCase):
"""Тесты для full_name.py"""
def test_first_last_name(self):
""" Имена вида 'Коб Ярослав' работают нормально?"""
format_name = full_name('Коб', 'Ярослав')
self.assertEqual(format_name, 'Коб Ярослав'... |
f822de794c3e944005b20c03cc66bac2a46007ac | mas41672/Python | /ex20.py | 1,009 | 3.953125 | 4 | #function and files
from sys import argv # import argv
script, input_file = argv # unpack argv
def print_all(f): # function prrint_all()
print f.read() # read file Object f
def rewind(f):
f.seek(0) # Move to new file position - offset from start of file since no argument precizing position
def print_a_line(line_... |
715a4e15f4e2e0c30df9c560da381ee05f45a03c | mas41672/Python | /ex6.py | 935 | 4.0625 | 4 | x = "There are %d types of people." % 10 # def. of str 'x' with an intr format character -number inside str
binary = "binary" # def. of str 'binary'
do_not = "don't" # def. of str do_not
y = "Those who know %s and those who %s." % (binary, do_not) # def. of str y with two str format chr s - two strs insi... |
a8e2746561045c5a93d9af78ced3594ac12dc467 | dylannakahodo/advent-of-code-2019 | /day-4-secure-container/one.py | 628 | 3.75 | 4 | # - It is a six-digit number.
# - The value is within the range given in your puzzle input.
# - Two adjacent digits are the same (like 22 in 122345).
# - Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679).
# How many different passwords in your range?
#... |
15abc5a805b8e44290881a7151076b5c803b1f56 | fabricejeannet/pymon | /pymon.py | 707 | 3.65625 | 4 | import random
def start_sequence():
sequence = []
for value in range(4):
sequence.append(random.randint(0,3))
return sequence
def is_correct(sequence, index, input):
return sequence[index] == input
RED = 0
GREEN = 1
BLUE = 2
YELLOW = 3
#--------------------------------------------------------... |
b51055bc9ac98e8cb7d9cef036601b3e8ab05853 | rereregner/homework2 | /4.py | 188 | 3.5625 | 4 | my_str = input("Введите несколько слов: ")
a = my_str.split(' ')
for i, el in enumerate(a, 1):
if len(el) > 10:
el = el[0:10]
print(f"{i}. - {el}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.