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
e110641b843a1395d1481a7584914e555a8f90be
Dhrumil-Zion/Competitive-Programming-Basics
/Shopping_cart.py
543
3.703125
4
""" link = https://www.hackerrank.com/challenges/electronics-shop/problem """ def getMoneySpent(keyboards, drives, b): if len(keyboards) == 1 and keyboards[0] >= b: return -1 if len(drives) == 1 and drives[0] >= b: return -1 n = [] for x in keyboards: for y in drives: ...
ce5b4ffca7c3cc73a98e7dd577b25b3e66401737
Dhrumil-Zion/Competitive-Programming-Basics
/Codechef/Practice/Small Factorial.py
202
3.90625
4
T = int(input()) def factorial(n): if n in [1, 0]: return 1 else: return n * factorial(n-1) while T!=0: num = int(input()) fact = factorial(num) print(fact) T-=1
aa2c450d5a5d0e9345e369d8e5c0c7e270525597
Dhrumil-Zion/Competitive-Programming-Basics
/Codechef/Practice/Rectangle.py
215
3.546875
4
testcase =int(input()) while testcase!=0: a,b,c,d =map(int,input().split()) if(a == b and c == d or a == d and b == c or a == c and b == d): print("YES") else: print("NO") testcase-=1
d50b7d7bd5c2316508a9ebbfb3581ef8c98e311c
Dhrumil-Zion/Competitive-Programming-Basics
/LeetCode/String/Count_the_Number_of_Consistent_Strings.py
293
3.796875
4
allowed = "cad" words = ["cc","acd","b","ba","bac","bad","ac","d"] ## oneliner solution print(len([1 for word in words if set(word).issubset(allowed)])) ## somewhat slower than above one count = sum( set(allowed).intersection(set(word)) == set(word) for word in words ) print(count)
55b4cbde4639a7d0535b845bd6f39dc4bd879674
Dhrumil-Zion/Competitive-Programming-Basics
/LeetCode/Bit Manipulation/Hamming_Distance.py
191
3.71875
4
def hammingDistance(x, y): count = 0 while x or y: if x & 1 != y & 1: count += 1 x = x >> 1 y = y >> 1 return count print(hammingDistance(1,4))
12a6a257d396bb8b4c7bf403a36721deaa1dae4a
piyushgoyal1620/Python
/squre-root.py
288
3.609375
4
n=int(input("enter a number: ")) for i in range(n): if i*i==n: print(i) break if i*i>n: j=i-1 while j<=i: if j*j>n: print(j) break j=j+0.01 break ''' Output enter a number 100 10 another no--- enter a number 95 9.749999999999984 '''
c56f49e3ad1b142d6de7725fccd3d8a49bf00d2f
mbalbera/Showdown
/Gameplay.py
27,398
3.671875
4
# Gameplay.py """Controller module for Showdown card game. This module contains the subcontroller to play a single game of Showdown. Instances reflect a single game. To play a new game, make a new instance of Gameplay. This subcontroller manages the following and all associated die rolls: inning number and top/bott...
b690fd4157cdb699424b69f92e410fefcbf32e0b
Skar0/simu
/tools/piLoader.py
312
3.671875
4
# -*- coding: utf-8 -*- def piDigits(): """Loads all pi digits and returns them in a list""" file = open("assets/pi6.txt") next(file) digits = [] for line in file : for digit in line: if not digit.isspace() : digits.append(int(digit)) file.close() return digits
7228225d39948e95407e4365e4c2675d9ae61bbf
km-aero/eng-54-python-basics
/101_python_variable_print_type.py
303
3.921875
4
# Variables # like a box. Give it a name, put stuff inside book = 'Rich dad poor dad' # print function book print(book) # type function # allows us to check data types data_type_of_book = type(book) print(data_type_of_book) # input () ## Conventions #lower case for variable naming with under score
bf12f927c2d684699f41b48c1191ea956205a41c
km-aero/eng-54-python-basics
/exercise_103.py
433
4.3125
4
# Define the following variables # name, last_name, species, eye_color, hair_color # name = 'Lana' name = 'Kevin' last_name = 'Monteiro' species = 'Alien' eye_colour = 'blue' hair_colour = 'brown' # Prompt user for input and Re-assign these name = input('What new name would you like?') # Print them back to the user ...
a7c7cf8da6d5e74209261fd83493f60e46798fdf
khadtareb/class_assignments1
/pythonProject6/Assignment_18.py
162
3.90625
4
#8. Cloning or Copying a list Python #in built function l=[6,2,4,1,6,4] # l1=l.copy() # print(l1) #by using for loop l2=[] for i in l: l2.append(i) print(l2)
f693e45eab8cfcc4ab449149fcba829e8e4f0b02
khadtareb/class_assignments1
/pythonProject6/Assignment_62.py
351
4.1875
4
#62. Python | Ways to remove a key from dictionary Ways to sort list of dictionaries by values in d=[{ "name" : "Nandini", "age" : 22}, { "name" : "Manjeet", "age" : 20 }, { "name" : "Nikhil" , "age" : 19 }] print(sorted(d,key=lambda i:i['age'])) print(sorted(d,key=lambda i:i['age'],reverse=True)) print(sorted(d,key=...
d457484295a4aa989525dfd66213ee42c8f4fc43
khadtareb/class_assignments1
/pythonProject6/Assignment_25.py
107
4.1875
4
#. Python program to print even numbers in a list l=[3,2,6,4,3,5,6,5] l1=[i for i in l if i%2==0] print(l1)
48c123cc409891a4b5b8f9597e8b6a05498d734d
khadtareb/class_assignments1
/pythonProject6/Assignment_37.py
210
4.09375
4
# #Python | Program to print duplicates from a list of integers l=[3,2,7,9,4,3,5,8,3,2] if len(l)<2: print("add more elements") else: l1=[i for i in l if l.count(i)>1] a=set(l1) print(list(a))
5ffc98e2bf1d1f62ba6f09d163ea434fcc1bf6eb
khadtareb/class_assignments1
/pythonProject6/Assignment_26.py
108
4.0625
4
#26. Python program to print odd numbers in a Lis l=[3,2,6,4,3,5,6,5] l1=[i for i in l if i%2!=0] print(l1)
25d9ba3e06c2034b9b495e2d1c05642ce6fd2d6e
khadtareb/class_assignments1
/pythonProject6/Assignment_36.py
125
3.796875
4
# #. Python | Remove empty tuples from a list l=[3,2,6,(),4,7,()] for i in l: if i==(): l.remove(()) print(l)
ce31cb1d1ff67c29325ed64fff9ad99808408113
shuyiz666/stock_analysis
/shuyiz_3_3_8.py
740
3.5
4
''' assignment3: bakery dataset question8: what are the bottom 5 least popular items for each day of the week ''' import os import pandas as pd wd = os.getcwd() input_dir = wd ticker_file = os.path.join(input_dir, 'BreadBasket_DMS_output.csv') try: df = pd.read_csv(ticker_file) result = df.groupby(['Weekday'...
6f9835a2f739935bc0d1519eb55ee079a9b209c5
shuyiz666/stock_analysis
/shuyiz_2_3_3.py
995
3.53125
4
# -*- coding: utf-8 -*- ''' assigment 3: test normality returns question 1: compute the mean and standard deviation of daily returns ''' import os import pandas as pd ticker = 'ZSAN' wd = os.getcwd() input_dir = wd ticker_file = os.path.join(input_dir, ticker + '.csv') plot_dir = wd try: df = pd.read_csv(ticker_f...
85ef50b4a5b624ef5316fa82a5746628a391a89a
shuyiz666/stock_analysis
/shuyiz_4_2_2.py
1,646
3.5625
4
''' assignment2: trading with labels question2: plot the ”growth” of your account. Week numbers on x, account balance on y ''' import os import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mtick wd = os.getcwd() ticker = 'ZSAN' input_dir = wd ticker_file = os.path.join(input_dir, ticker + ...
ca6be4353afb568596d74a2d60de3e41ed2191aa
shuyiz666/stock_analysis
/shuyiz_8_2_2.py
787
3.53125
4
''' assignment2: naive bayesian question2: compute the confusion matrix for year 2 ''' import os import numpy as np import pandas as pd from sklearn.naive_bayes import GaussianNB from sklearn.metrics import confusion_matrix wd = os.getcwd() ticker = 'ZSAN' input_dir = wd ticker_file = os.path.join(input_dir, ticker + ...
9169678e188e0850c29da430efe2aa373423cc09
shuyiz666/stock_analysis
/shuyiz_9_2_2.py
845
3.53125
4
''' assignment2: decision trees question2: compute the confusion matrix for year 2 ''' import os import pandas as pd import numpy as np from sklearn import tree from sklearn.metrics import confusion_matrix import warnings warnings.filterwarnings("ignore") wd = os.getcwd() ticker = 'ZSAN' input_dir = wd ticker_file = ...
34e4e4a819522f5952581e47448fec521ad078b2
dan2014/Hash-Tables
/resizing_hashtable/r_hashtables.py
4,479
3.859375
4
# ''' # Linked List hash table key/value pair # ''' class LinkedPair: def __init__(self, key, value): self.key = key self.value = value self.next = None def __repr__(self): return f"\nkey: {self.key} value: {self.value}\n" # ''' # Fill this in # Resizing hash table # ''' c...
f92b899ec2d0946db44b5a078c221fea942d3a34
CheshireCat12/hackerrank
/eulerproject/problem027.py
851
3.59375
4
# import numpy as np from itertools import product def sieve_primes(): n = 10**7 primes = [True] * (n+1) idx = 2 while idx*idx <= n: if primes[idx]: for i in range(idx*idx, n+1, idx): primes[i] = False idx += 1 if idx == 2 else 2 return primes def m...
d9207ca829d69f8530aa4032b314dd6ca9fc91a0
CheshireCat12/hackerrank
/eulerproject/problem010.py
801
3.890625
4
#!/bin/python3 def sieve_of_eratosthenes(num): primes = [True] * (num+1) candidate = 2 while candidate**2 <= num: if primes[candidate]: primes[candidate**2::candidate] = [False] *\ len(primes[candidate**2::candidate]) candidate += 1 primes[:2] = [False...
d7b1e44e7ba498af64267230f8feb00b974aa55c
CheshireCat12/hackerrank
/ai/day6.py
836
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 16:51:05 2019 @author: cheshirecat12 hackerrank exercise: https://www.hackerrank.com/challenges/predicting-house-prices/problem """ # Enter your code here. Read input from STDIN. Print output to STDOUT import numpy as np from sklearn.linear_mod...
1736fa54bb0aa30ff931ced7e8fc61c104a3aa5d
CheshireCat12/hackerrank
/eulerproject/problem006.py
544
4.21875
4
#!/bin/python3 def square_of_sum(n): """Compute the square of the sum of the n first natural numbers.""" return (n*(n+1)//2)**2 def sum_of_squares(n): """Compute the sum of squares of the n first natural numbers.""" return n*(n+1)*(2*n+1)//6 def absolute_diff(n): """ Compute the absolute d...
dd5140fad8067d9c49215aa6a3600281770c22ff
marsdev26/python_exercises
/hello_turtle.py
1,085
4.28125
4
import turtle #Function to draw 1 petal of a flower def draw_petal(): turtle.down() turtle.forward(30) turtle.right(45) turtle.forward(30) turtle.right(135) turtle.forward(30) turtle.right(45) turtle.forward(30) turtle.right(135) #Function to draw a flower def draw_flower(): ...
5a80baff56e0be819776e4054fdf1ef3c6fadddd
koneil612/Python-Exercises
/pythonDictionaries.py
1,609
4.03125
4
# phonebook_dict = { # 'Alice': '703-493-1834', # 'Bob': '857-384-1234', # 'Elizabeth': '484-584-2923' # } # # print elizabeths phone number # # print phonebook_dict['Elizabeth'] # # # Add a entry to the dictionary: Kareem's number is 938-489-1234 # phonebook_dict['Kareem'] = '938-489-1234' # # # # Delete Alice's phone...
3d52beea7d5603fba9a0d36ce1b9df39988ee951
koneil612/Python-Exercises
/python201list.py
817
3.796875
4
# print a sum of numbers # numbers = [1, 5, 7, 36, 863, 26] # print sum(numbers) # print a max of numbers # numbers = [1, 5, 7, 36, 863, 26] # print max(numbers) # print a min of numbers # numbers = [1, 5, 7, 36, 863, 26] # print min(numbers) # print the even numbers # numbers = [1, 5, 7, 36, 863, 26] # for even in ...
add68f1223ebe14577bfaab07e95260c12946f29
koneil612/Python-Exercises
/Python301.py
377
3.734375
4
# import matplotlib.pyplot as plot # # def f(x): # return 2 * x + 1 # # def g(x): # return x + 1 # # xs = range(-3, 5) # fys = [] # for x in xs: # fys.append(f(x)) # # gys = [] # for x in xs: # gys.append(g(x)) # # plot.plot(xs, fys, xs, gys) # plot.show() name = 'Raj' age = 5 def sentence (): retu...
99e02fa63b997cb3156d5427da3833584a99d3c3
stogaja/python-by-mosh
/12logicalOperators.py
534
4.15625
4
# logical and operator has_high_income = True has_good_credit = True if has_high_income and has_good_credit: print('Eligible for loan.') # logical or operator high_income = False good_credit = True if high_income or good_credit: print('Eligible for a loan.') # logical NOT operator is_good_credit = True c...
3aa0135bb58e08f1b61c3601bb1821ab7e430379
manish123456424/Edyoda-Careall
/Elder.py
9,613
4.03125
4
import sqlite3 with sqlite3.connect('Edyoda.db') as db: c = db.cursor() class Elders:#Elder Class def __init__(self): self.Uname=str self.pwd=str self.eid=str def new_user(self,Name,Age,Contact,Uname,pwd):#login for new user "Sign Up" with sqlite3.connect('Edyoda.db') as db: c=db.cursor() c.execute(...
be643aa2ad49cdce83c9bd32c39010cf95b73c0e
Umakshi12/Python_Use_Cases
/count elements/count-elements.py
355
3.984375
4
from collections import Counter list1 = ['python', 'java', 'javascript', 'python', 'java', 'python'] list2 = ['python', 'java'] ans = Counter(list1) print("Count of all elements in list1 ---") print(ans) print() print("Count of elements of list1 which are present in list2 ---") for i in range(len(list2)): print(...
a879af6482c24ad04d75b748443fade756787f0a
Vestara/audiogame
/lib/AudioBox/SimpleInputBox.py
8,663
3.6875
4
# Author: Stephen Luttrell from lib.sound_pool import sound_pool import pygame import speech import time class SimpleInputBox: """ An input box interface which returns user input Attributes ---------- buttons : List A list of available interface buttons running : boolean The state of the interface sounds ...
3900fbf4b2eacc1e1c5f0b25cc56ae664efe8767
LuckPsyduck/Program-OFFER
/Interview-Program.py
13,600
3.640625
4
""" 2020.03.06 """ #Tree# class TreeNode(): def __init__(self, x): self.value = x self.left = None self.right = None def preOrder(self, root): stack, res, cur = [], [], root while stack or cur: if cur: res.append(cur.value) stack.append(cur.right) cur = cur.left else: cur = stack.pop...
ff374a1d18fc331f18f5840a25dda75f7cecad51
stefangui/test
/test11.py
195
3.53125
4
a = [1,4,6,9,13,16,19,28,40,100,200] print('原始列表为:',a,end=' ') number = int(input('插入的数字为: \n')) a.append(number) a.sort() print('排序后的列表为:',a,end=' ')
672871002e98f073f5909f9432106462b384457d
Sameer-Jha/wiki_cli
/main.py
4,286
3.703125
4
#!/usr/bin/env python3 import wikipedia as wiki from os import system from os.path import exists from string import ascii_lowercase from random import choice import argparse def rand_string_gen(len): sel_space = ascii_lowercase name = "" for i in range(len): name = name + choice(sel_space) ret...
d1c090090aa34872bd04efb8f6129ecfd164fff4
mario-balan/marathons-and-challenges
/uri/python/1074.py
345
3.953125
4
total = int(raw_input()) for i in range(total): n = int(raw_input()) if n > 0: if n % 2 == 0: print 'EVEN POSITIVE' else: print 'ODD POSITIVE' elif n < 0: if n % 2 == 0: print 'EVEN NEGATIVE' else: print 'ODD NEGATIVE' el...
0c99ef5eb8cda4756ffbff77bb96244a6c05ecb0
ChanwO-o/peg-solitaire
/psboard.py
3,798
3.5625
4
''' Created on Oct 28, 2018 @author: cmins ''' # Every coordinates of first value is rows and second value is col import psexceptions import psgamestate class PSBoard: def __init__(self): self._board = self.getNewBoard(7, 7) # Joowon Jan,04,2019 # Add variable to store the...
cc3760557bcc847bacf405f8a8481c408da6dcd9
francoismartineau/smtp_client_server
/serveur/ServerSocket.py
2,969
3.734375
4
import struct, pickle, socket """ Cette classe sert à établir la communication au serveur à permettre les demandes de connexions d'éventuels clients. Elle utilise un socket. Elle traduit les variables python en octets et vice versa via le module pickle. """ class ServerSocket: """ Initialisation d'un socket. ...
357bcd79a10764c236d66e1f131ef2e2f555b603
irvingr/python
/28_fechayhora.py
351
3.75
4
# Fecha y hora from datetime import datetime fechayhora = datetime.now() print(fechayhora) anio = fechayhora.year mes = fechayhora.month dia = fechayhora.day # hora hora = fechayhora.hour minutos = fechayhora.minute segundos = fechayhora.second microsegundos = fechayhora.microsecond print("La hora es {}:{}:{}".f...
46e42615822d4437dbec3471ccecfca356b1d3ec
irvingr/python
/22_funciones.py
727
3.59375
4
# Funciones - Bloque de código que se ejecuta cuando es llamado def saludar(): print("Buenos días") # Invoca a la función saludar. saludar() # Buenos días def saludo(nombre): print("Buenos días " + nombre) nombre = "José" # Invoca a la función saludo. saludo(nombre) # Buenos días José def sumar(numero1, nu...
b5eb750b63f976468b60997dadd2a8523dcfd844
irvingr/python
/ficheros/escribirfichero1.py
254
3.625
4
# Grabar en un fichero de texto con Python fichero = open("fichero_para_escribir.txt", "wt", encoding="UTF-8") texto_del_fichero = "Hola, esta es la línea que vamos a escribir en el fichero de texto." fichero.write(texto_del_fichero) fichero.close()
6d57d0946ae58846ff776922b6eebce65ed2e01d
ReubenMonkeyFan/01_Lucky_Unicorn
/05_token_generator_v4.py
905
4.09375
4
import random # main routine goes here STARTING_BALANCE = 100 balance = STARTING_BALANCE # testing loop to generate 20 tokens for item in range (0,100): chosen_num = random.randint(1,100) # adjust balance # if the random number is between 1 and 5, # user gets a unicorn (add $4 to balance) if 1 <...
368a08835f7daf3ee71bf2780f4eeabcf8c27766
xuancong84/linux-home
/bin/cut3.py
1,295
3.53125
4
#!/usr/bin/env python3 # coding=utf-8 import os,sys,argparse,re def select_fields(line, delimiter, fields): token_list=line.rstrip("\r\n").split(delimiter) out = [] for arg in fields: if type(arg)==int: out.append(token_list[arg]) else: out.extend(token_list[arg]) return delimiter.join(out) def parse_...
43c653597a45d7900dda419e3068d763a2323c1f
jhyoung09/BUMS
/BUMS.py
3,092
3.84375
4
################################################## # # James Hunter Young # 2020 # # BUMS - Back Up My Shtuff # # # ################################################## # imports import logzero from logzero import logger, logfile # global variables def ask(): logger.debug('### STARTING ASK ###') ...
30df550381e8d53c752760956ee0dffb1e6cf9c0
bxio/stuff-to-build
/lists/00/01/BottlesOfBeer.py
607
3.90625
4
#!/usr/local/bin/python3 bottles_to_count = 99 for bottle in range(bottles_to_count, 0, -1): if bottle > 2: print(f"{bottle} bottles of beer on the wall, {bottle} bottles of beer,\ntake one down, pass it around, {bottle-1} bottles of beer on the wall.\n") elif bottle == 2: print(f"{bottle} bott...
1a2af3243979eaea8cee8558ca777440d54b046f
vishalbelsare/housing-model
/src/main/resources/validation-code/HousingWealthDist.py
5,054
3.6875
4
# -*- coding: utf-8 -*- """ Class to study households' housing wealth distribution, for validation purposes, based on Wealth and Assets Survey data. @author: Adrian Carro """ from __future__ import division import pandas as pd import numpy as np import matplotlib.pyplot as plt def readResults(file_name, _start_time...
c9a01d9c5933b4f5995cc551f2b7525525cb408c
Curtainial/cbaradar
/kkllll.py
4,641
4
4
#!/usr/bin/python3 # # Assignment 3 # CMPS 5P, Fall 2016 # # Cyrus Baradaran-Azimi # cbaradar@ucsc.edu #commits import random start = float((input("What is the starting number (1-499)? " ))) while start < 1 and start > 499: start = float((input("What is the starting number (1-499)? " ))) #these lines prevent ...
7a1741debc37744f21fbf29784ecd40ea9aa499f
TheCYBORGIANpulkit/assignment1
/Second pyhton.py
399
3.65625
4
print("Plesae enter your age: " ) x = input() print(x) print ( "I am " + x + " years old. ") print( "I am " + x + " years old.") print(int(x)) print(int(x) + 5) print() x = int(x) print(x + 5) y = input() y = float(y) print(int(y)) y = str(int(x)) + 'Pulkit' print(y) print( "please enter the DCKBDC "...
3437745cc76a77c43032785dd9a929df01c38136
fferas/coursera-using_python_to_access_webdata
/week4_1.py
606
3.71875
4
# Using Python to access web data course - Week 4 assignment 1 import urllib from bs4 import BeautifulSoup url_input = raw_input("Enter the url, or 1 or 2:\n>") if url_input == '1': url_input = 'http://python-data.dr-chuck.net/comments_42.html' elif url_input == '2': url_input = 'http://python-data.dr-chuck.n...
02cad5fcdaa64e469534ae0b0c8a5e0578c4f6af
jirapat09/python
/week2/work2.4.py
1,076
3.75
4
price = [25,30,45,55,60],[45,45,75,90,100],[60,70,110,130,140] car = ["รถยนต์ 4 ล้อ","รถยนต์ 6 ล้อ","รถยนต์มากกว่า 6 ล้อ"] print("โปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์") print("รถยนต์ 4 ล้อ กด 1") print("รถยนต์ 6 ล้อ กด 2") print("รถยนต์มากกว่า 6 ล้อ กด 3") a = int(input("เลือกประเภทยานภาหนะ :")) print(car[a...
0310ba493b0762d75bd31fcf01b4e22b989a64c5
jirapat09/python
/all1.py
969
4.09375
4
""" name =input('What is your name?\n') print ('Hi,%s.'%name) print ('Welcome to Python.') a = 90 b = 9 if a > b : print("a > b") print("ok") name =input('Name ') surname =input('Surname ') year =input('Year ') code =input('Code ') print(name) print(surname) print(year) print(code) x = 20 y = 35.24 z = 1j a...
562140b0ed8032a3444e7ec03bc707f851a0884d
PaulT-oth/todolist
/sqlite_chores.py
824
3.625
4
import sqlite3 connection = sqlite3.connect('chores.db') def save_chore(chore): cursor = connection.cursor() save_chore = (chore['desk'], chore['person'], int(chore['status'])) ex = cursor.execute('INSERT INTO chores("desk", "person", "status") VALUES (?,?,?)', save_chore) lastrowid = cursor.lastrowid...
465401739659d19fb6998f0b6f00e11f04a5f90b
ARNisUsername/TextClassification
/MovieRating/getData.py
2,037
3.734375
4
#Import neccessary modules import numpy as np import pandas as pd import requests from bs4 import BeautifulSoup #Read the first 2000 parts of the dataset number_titles = 2000 movie_text = pd.read_csv('movies_metadata.csv', low_memory=False)[:number_titles][['original_title','overview']] movie_text = movie_text.fillna(...
c39c795cf8b2f2db4ba4d946f1a6e5d8da21ae79
huseyinjkilic/Numpy-Data-Science-Related-Problem-Solutions
/UdacityIndexArrayExample.py
1,703
3.65625
4
import numpy as np # Change False to True for each block of code to see what it does # Using index arrays if False: a = np.array([1, 2, 3, 4]) b = np.array([True, True, False, False]) print a[b] print a[np.array([True, False, True, False])] # Creating the index array using vectorized operati...
2eb1b3ad46b237163ef1251b79ca9b1fa5afc920
johnathanachen/cs1
/Grade_Book/Students.py
1,164
3.5
4
import os student_list = os.path.isfile("./db/students.txt") class Student(object): def __init__(self, name, student_ID): self.name = name self.student_ID = student_ID self.grade_average = None self.assignments = {} if student_list: with open('./db/students.txt',...
99ea4fcb52da4c5bed7907b52f6e1311eccfa64c
vamsichitturi472/Python_Practice
/Basics/Basic_Syntax/if-elif-else.py
654
3.765625
4
if __name__ == "__main__": # using string direction = "Right" if (direction == "Right"): print("going Right") elif (direction == "Left"): print("going Left") else: print("Unable to Navigate") # using numbers value = 0 if (value): print("non-zero will be...
98ccaa1ee53498229e98654539f398e928ce7fb1
vamsichitturi472/Python_Practice
/Machine Learning/Anomaly_Detection/custom_logic.py
3,551
3.625
4
""" this will find mean value and standard deviation and finds minimum values and maximum values based on those. any point greater then maximum or lesser then minimum will be an outlier """ from matplotlib.pyplot import legend, plot, scatter, show, title from numpy import append, array, mean, std from sklearn.li...
caf7ce1a2ffdbd95bd65ddff9a3383725e9cdfbf
lucasheber/p2p
/server/server.py
1,465
3.65625
4
# coding: utf-8 ''' O Programa abaixo faz a implementação do servidor P2P. Por enquanto o nome do arquivo está sendo enviado pelo cliente é um nome que escolhi. O ideal é que o primeiro envio do cliente seja o nome do arquivo. Python: 2.7 Autor: Lucas Heber ''' import socket print "Server" # I...
95edf90cebfd0728a3279c6167639161070b24bc
sodevious/developer-notes
/happy/test.py
285
3.84375
4
import json words = [ "adjective", "noun1", "noun2" ] stored_words = {} for word in words: answer = raw_input("Please enter a %s:" % word) stored_words[word] = answer j = json.dumps(d, indent=4) f = open('sample.json', 'w') print >> f, j print stored_words f.close()
5ea574ac318ccdf4338e7494150f558ca226e4d3
danielmansueto/Programming2-Daniel
/Problem Sets/sorting_problems.py
3,478
3.890625
4
# Problem 1 - Value Swap (2pts) # Swap the values 18 and 38 in the list below. Print the new list. import random my_list = [27, 32, 18, 2, 11, 57, 14, 38, 19, 91] print() print("Problem #1:") print() my_list[2], my_list[7] = my_list[7], my_list[2] print(my_list) print() # Problem 2 - Selection Sort (8 pts) # Make a...
5f3796f0b66250188d274871012c66e0380950a7
danielmansueto/Programming2-Daniel
/kivy/gravity calculator/main.gravity.py
2,066
4.0625
4
# kivy Universal Gravity Calculator (30pts) # When we learned about exceptions, I asked you to make a Universal Gravity calculator # G is the universal gravity constant (6.674×10−11 N m^2 / kg^2) # m1 is the mass of object 1 in kg # m2 is the mass of object 2 in kg # r is the distance between the two objects in meter...
015985586a2b531942203a176d3863c73563fc32
osHamad/answers_for_advent_of_code_2020
/day_2_puzzle_2/main.py
1,116
3.65625
4
def format(input): num1 = '' num2 = '' letter = '' password = [] move_num = False is_password = False for i in input: if i.isdigit() and not move_num: num1 += i elif i.isdigit() and move_num: num2 += i elif i == '-': move_num = True...
e009f39c823ea57875e93683e5a8c1761a32c6e3
jmccann2000/Learning-To-Code
/lesson000/file_reader.py
892
3.96875
4
''' @brief This module contains the FileReader class, which provides the basic functionality for reading a code file and decomposing it into its whitespace separated tokens. ''' class FileReader(object): def load_tokens_from_file_path(self, file_path): ''' This function reads in the contents...
c557a0847300970310bd8c3963b3dfc9acece269
wzlwit/jac_spark
/lecture2/task3.py
2,175
3.703125
4
# Task 3: Skeleton of an ML program: Transformer, Estimator, Parameters # Objective: Understand the building block of any ML application with the example of predicting the role of an IT professional is developer by looking at his experience and annual salary #Read data # df = spark.read.csv("/home/s_kante/spark/data/...
e3f62b017d18c0aaae72a567b9c67fa1e2d44506
darvitol/example
/farm.py
4,022
3.671875
4
import typing from decimal import Decimal class Amount(object): def __init__(self, count: Decimal): self.count = count class Sort(object): def __init__(self, name: str, sort_id: int): self.name = name self.sort_id = sort_id class Product(object): def __init__(self, name: str, ...
7c7f7af91bacd95300c33bbf8f9f356575af07b6
darvitol/example
/little-progs-python/100years.py
382
3.6875
4
import time import datetime from day import now name = input("Введите имя: ") age = int(input("Сколько Вам лет? ")) ''' res = 100 - age today_day = datetime.datetime.today() today_day_int = time.strftime("%Y") in100 = int(today_day_int) + res print ("Вам будет 100 лет в ", in100, 'году') ''' year = str((now.year - ...
ddd1ce81e238006660551f7b83f4f3dae32b35d2
sferro/excercises
/python/collatz.py
323
4.0625
4
#!/usr/bin/python # -*- coding: utf-8 -*- def collatz(number): if (number % 2) == 0: return number // 2 else: return 3 * number + 1 print('Input a number') inputNumber = int(input()) while True: if inputNumber == 1: break inputNumber = collatz(inputNumber) print(inputNumbe...
ebde3a4def2606ecb06ff858f14274e7bf2077d4
sferro/excercises
/python/isPhoneNumber.py
849
4.03125
4
#!/usr/bin/python # -*- coding: utf-8 -*- import sys def isPhoneNumber(text): if len(text) != 12: return False if not text[0:3].isdecimal(): return False if text[3] != '-': return False if not text[4:7].isdecimal(): return False if text[7] != '-': return...
8ce85156c5cd03bf70b6cbaab8df254d3f6616de
amber-meinke/amber-meinke.github.io
/adventure.py
3,548
4.375
4
# Maze Adventure Game # # User chooses between left, straight, or right for 10 turns # # This program: # -randomly generates required numbers for l, s, & r # -keeps counters for how many times the user selects l, s or r # -if they ever exceed the amount for any direction, they will # run into some k...
84b1661d7ae6a953e69284e168c663f8f746a75e
amankapur/pdish
/lab2.py
1,850
3.53125
4
import serial import math import time import urllib2 import urllib """ We use a web server to display the results. Post_to_server is simply doing a HTTP POST request to the url provided with the values given to it. """ def post_to_server(url, values): if values['opacity'] != None and values['number'] != None: da...
56236af80732ceb61ca8552fa77948efe1003e0c
RocketDonkey/nes_sprite_reader
/example_reader.py
3,356
4.15625
4
"""NES Sprite Reader - Example using Super Mario Brothers 3. A simple example of how to use the SpriteReader, which involves loading in a ROMs sprite map and palettes and then writing the sprites. """ from roms.smb3 import smb3_sprites from roms.smb3 import smb3_palettes import nes_sprite_reader def main(): """R...
fa537f900f5a5f23c8573e1965895df2dd3b3706
jhreinholdt/caesar-cipher
/ceasar_cipher.py
1,693
4.125
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 21 15:33:33 2017 @author: jhreinholdt Caesar cipher - Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th nex...
09da9df46b788582693c535b71ed5da4198c5e26
Helik36/data_and_algo
/3hw3/task_4.py
1,208
3.578125
4
""" Задание 4. Реализуйте скрипт "Кэширование веб-страниц" Функция должна принимать url-адрес и проверять есть ли в кэше соответствующая страница, если нет, то вносит ее в кэш Подсказка: задачу решите обязательно с применением 'соленого' хеширования Можете условжнить задачу, реализовав ее через ООП """ from uuid imp...
994d5470d143edd613cb8bbf5dfc2347a703b609
Helik36/data_and_algo
/2hw2/task_6.py
1,751
4.09375
4
""" 6. В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток. После каждой неудачной попытки должно сообщаться больше или меньше введенное пользователем число, чем то, что загадано. Если за 10 попыток число не отгадано, то вывести загаданное число. Реши...
7cda0f517255efcb24fc516dbefa9200070cfb5d
NyakuSelom/Lab_Python_03
/Lab03_1.py
897
3.796875
4
"""newnumber=2 for number in range (0,500,1): if (number%2 !=0) and (number>2): for n in range(2,number,1): if number%n ==0: break else: newnumber= newnumber,number, print "the first 50 prime numbeers are ",newnumber """ print 'first 50 prime num...
551f297e21fe8b3ca8fef50ced45048ea895be98
lorenz075/py_beginner_projects
/higherLower_pj14/higherLower_pj14.py
1,825
4.03125
4
from os import system, name import random from data_logo import data, logo, vs def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') def format_data(account): account_name = account["...
83f0d3f125ac8cb01a4ed7729b99fa6c20c9e7da
Olenatko/codewars
/order.py
297
3.953125
4
def in_asc_order(arr): sort_arr = sorted(arr, key=int) bad_sort = sorted(arr, key=int, reverse=True) if arr == sort_arr: return True elif arr == bad_sort: return False if arr != sort_arr and arr != bad_sort: return False print(in_asc_order([3, 2, 6]))
b23872fc16fce959f6c2af41fa9467ee1d9d4ca3
Olenatko/codewars
/transponov.py
325
3.84375
4
def transpose(arr): matrix = [] if len(arr) == 0: return [] if arr[0] == []: return [[]] for i in range(0, len(arr[0])): for j in range(0, len(arr)): if j == 0: matrix.append([]) matrix[i].append(arr[j][i]) return matrix print(transpose...
d6fa84d27255bf0c69c765af1ec4899304ec50f4
Son-Guhun/GUI-extreme
/testeando2.py
1,804
3.84375
4
import Tkinter as tk class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) self.choices = ("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", ...
6d552cc0b2cbd7a7943563b4cbe5c02133733266
madhuriagrawal/python_assignment
/task3/removeEvenNumbers.py
156
3.65625
4
List = [1, 5, 6, 8, 9, 4, 2] outputList = [] for i in range(len(List)): if (List[i] % 2) != 0: outputList.append(List[i]) print(outputList)
a1630a7269267d0e0c473dc25f05065b023d3b22
madhuriagrawal/python_assignment
/task3/dictWithSquareValues.py
76
3.609375
4
myDict = {} n = 5 for i in range(1, n+1): myDict[i] = i*i print(myDict)
6859227a4b6aed9621f0a7182401af096a0639a9
madhuriagrawal/python_assignment
/task4/showNumbers.py
155
3.703125
4
def showNumbers(limit): for i in range(limit): if i%2==0: print(i,"EVEN") else: print(i, "ODD") showNumbers(4)
fd5d0602a635cc7f492c76ed2df9548da2ec29dc
madhuriagrawal/python_assignment
/swapTwoNumbers.py
231
4.25
4
def swapingUsingThirdVariable(): x=2 y=6 z=x x=y y=z print(x,y) def swapingWithoutThirdVariable(): x = 2 y = 6 x,y=y,x print(x,y) swapingUsingThirdVariable() swapingWithoutThirdVariable()
42fb86754b05689be2170dd6968c2f9eca4b767e
madhuriagrawal/python_assignment
/task4/outputOfFollowingCode.py
323
3.578125
4
def foo(): try: return 1 finally: return 2 k = foo() print(k) # it will give indentation error because try block is not inside the function foo() def a(): try: f(x, 4) finally: print('after f') print('after f?') a() # it will give indentation error because try block is not inside the function a...
fa5b107b5331c4744ac8004c1c2d77a1a898645a
madhuriagrawal/python_assignment
/inputFromUser.py
267
3.5625
4
def enterUsernamePython2(): username = raw_input("Enter username:") print("Username is: " + username) def enterUsernamePython3(): username = input("Enter username:") print("Username is: " + username) enterUsernamePython2() enterUsernamePython3()
b5ef510664c1bc6be3d00d751e322bd943a5837a
rockse/martian-robots
/game.py
1,850
3.984375
4
# import evaluate_guess from engine import random class Game(): """Game class""" def __init__(self, length): self.pattern = [] self.length = length self.__generate_pattern() self.guess = [] def __generate_pattern(self): self.pattern = random.sample(range(0, 9), sel...
9866a4f1500553efc31541b7f8c568c20e7645db
emplam27/Python-Algorithm
/프로그래머스/월간 코드 챌린지 시즌1 - 두 개 뽑아서 더하기.py
199
3.609375
4
def solution(numbers): N, answer = len(numbers), set() for i in range(N - 1): for j in range(i + 1, N): answer.add(numbers[i] + numbers[j]) return sorted(list(answer))
17fc0aa973f9a8cd2c6460a9b06472ffa416f7b1
lbildzinkas/DataSourcesAlgorithms
/Python/Arrays/anagram_check.py
846
3.921875
4
# Given two arrays, check if they are anagrams of each other def check_anagram(list1, list2): list1.sort() list2.sort() for i in range(len(list1)): if list1[i] != list2[i]: return False return True def check_anagram1(list1, list2): dic = {} for i in range(len(list1)): ...
58185c8ed1fbceae5dbb44fc547712f101f17e21
Meenal-goel/assignment_7
/fun.py
2,238
4.28125
4
#FUNCTIONS AND RECURSION IN PYTHON #1.Create a function to calculate the area of a circle by taking radius from user. rad = float(input("enter the radius:")) def area_circle (r): res = (3.14*pow(r,2)) print("the area of the circle is %0.2f"%(res) ) area_circle(rad) print("\n") #Write a function “perfect()” t...
58e685e06033004ac48b5308906f34c01204da80
abhijitbangera/SmallPythonPrograms
/imageFileScanner.py
521
3.609375
4
''' Author: Abhijit Bangera Python version: Python 3.x Description: Below code scans for images (.png,.jpg) in a given folder and then copies them to a new destination folder Pre-setup: Manually create a empty DestinationFolder in your destination path. ''' import os import shutil src='C:\\Users\\xyz\\Deskto...
f5b9e07a1cfdd407616073a40faf980ecd530f37
croccanova/CS372
/File Transfer/ftclient.py
5,655
3.75
4
#!/bin/python # Christian Roccanova # CS372 # Fall 2018 # Project2 - client side portion of a file transfer system import sys from socket import * # based on example seen here: https://docs.python.org/2/howto/sockets.html under section "creating a socket" def createSocket(): # -l command will t...
89942978e296ac7de1c9e8e9f5e0bcaa67971e16
zjn0810/pythonL
/algorithm/linedata/queue/lianbiao.py
407
3.796875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 6 00:55:50 2021 @author: zhangjn """ import sys sys.path.append('/home/zhangjn/software/pythonSpace/algorithm/') from pythonds.basic.unorderedList.myunorderedlist import UnorderedList m_list = UnorderedList() showlist = [] for i in range(100): ...
833994a2e77655b22525d4cf4e8d3d3a6ab93cc4
JustineRobert/TITech-Africa
/Program to Calculate the Average of Numbers in a Given List.py
284
4.15625
4
n = int(input("Enter the number of elements to be inserted: ")) a =[] for i in range(0,n): elem = int(input("Enter the element: ")) a.append(elem) avg = sum(a)/n print("The average of the elements in the list", round(avg, 2)) input("Press Enter to Exit!")
6d5df0f168de7754256123f6e536920605356ff5
JustineRobert/TITech-Africa
/Program to Exchange the Values of Two Numbers Without Using a Temporary Variable.py
214
4
4
a = int(input("Enter the value of the first variable: ")) b = int(input("Enter the value of the second variable: ")) a = a+b b = a-b a = a-b print("a is: ", a, "b is: ", b) input("Press Enter to Exit!")
365fc5dfb09d4d3e7f14e1d10f25f6319559b4f7
JustineRobert/TITech-Africa
/Program to Check if a Date is Valid and Print the Incremented Date if it is.py
790
4.0625
4
date = input("Enter the date please: ") dd, mm, yy = date.split('/') dd = int(dd) mm = int(mm) yy = int(yy) if (mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12): max1 = 31 elif(mm==4 or mm==6 or mm==9 or mm==11): max1 = 30 elif(yy%4==0 and yy%100!= 0 or yy%400==0): max1 = 29 else:...
646bd434bf1ca289e6d8aeadc0cab2bbba5e9fc5
gonfalons/python-blackjack
/FrenchDeck.py
1,169
3.828125
4
""" Build a standard playing card deck from scratch, built for Blackjack Shuffled (insecurely) on instantiation """ from random import shuffle class Cards: """ Simulated French Deck, with the standard 52-card deck capabilities. Used for "single-shoe" (one deck) blackjack simulation """ _card_ra...
28b5de0f6d21ae7b62ec06d6e2c72c004d883b5d
caoxiang104/DataStructuresOfPython
/Chapter1_Programming_Basics/example8.py
1,128
3.890625
4
# coding=utf-8 """ 编写一个程序,它允许用户在文件的文本行中导航。程序提示用户输入一个文件名, 并且输入想要放入到列表中的文本行。然后,程序进入到循环中,它会输出文件的行 数,并且提示用户输入一个行号。实际的行号范围是从1到文件的行数。如果用户的输 入是0,程序退出。否则,程序输出和该行号相关的行。 """ import sys def file_write(filename): f = open(filename, 'w') print("Please enter lines which will save in file:") lines = sys.stdin.readlines(...
7b0899ab71aa19daed1db31c430aa9992ab114ed
caoxiang104/DataStructuresOfPython
/Chapter1_Programming_Basics/example6.py
1,437
3.734375
4
# coding=utf-8 """ 工资部门将每个支付周期的雇员信息的列表保存到一个文本文件中。该文件的每一行格式如下: <last name><hourly wage><hours worked> 编写一个程序,让用户输入一个文件名并且向终端输入报表,展示在给定的周期应该向每一个雇 员支付的工资。这个报表应该是表格形式,并且具有相应的表头。每一行一个包含雇员的名称、 工作的小时数,以及该周期所支付的工资 """ import sys from prettytable import PrettyTable def build_txt(txt_name): f = open(txt_name, '...