blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
728fb7a3ab0805e9824230ea27c3133bc4c15a72 | prajwalacharya016/CrackingCodingInterviewSolutions | /quest3.2.py | 593 | 3.84375 | 4 | import sys
def peek(list):
return list[-1]
class stackwithmin:
def __init__(self):
self.stack = []
self.minstack = [sys.maxint]
def push(self, data):
if data<peek(self.minstack):
self.minstack.append(data)
self.stack.append(data)
def pop(self):
da... |
cecf7b57a57c59d3686d747e5158e5c1d86c8634 | prajwalacharya016/CrackingCodingInterviewSolutions | /quest4.2.py | 611 | 3.890625 | 4 | class Node:
def __init__(self,str):
self.next=[]
self.visited = False
self.name = str
def search(node):
if node.visited == True:
return
else:
node.visited=True
for n in node.next:
search(n)
def depthfirstsearch(nlist):
for node in nlist:
sear... |
493dac3f8c0d9d29c85836bd632d9397369c5379 | prajwalacharya016/CrackingCodingInterviewSolutions | /quest1.2.py | 136 | 4.125 | 4 | #In Python its kinda easy to reverse the string using extended slicing
def reverse(str):
return str[::-1]
print reverse("Prajwal") |
ef12d03520e0ed74313bfb78f46f2cd4ce51341e | ara-dhanak/Python_sel_Projects | /Codingdojo/height.py | 380 | 3.515625 | 4 | #Ha = 2 Hb = 6
#Ha = 2*3 = 1way, addition, 2^2 + 2
#Maximum ways to find out height
inp = ['o',' ','m',' ','a',' ','ra']
op= "omara"
str1 = "2,2,0,7,9,6,0,0,0,9,1"
li = list(str1)
c = 0
for i in range(0,len(li)):
if li[i] == 0:
li.remove(i)
c += 1
print(li)
else:
continue
for i... |
7a03710220eb846599b541e35f98b948c740d02d | Missyor/13.-Conditional-Statements | /main.py | 10,363 | 4.21875 | 4 | # #### Practice if/else statements
# #####Loyalty Card
# loyalty = input("Do you have a loyalty card? Y/N: ")
# if loyalty =="Y":
# print("Please scan")
# #elif loyalty == "N":
# #print("Do you want one?")
# else:
# print("Do you want one? Y/N: ")
# #########################
# ##Payment
# #At register, asks i... |
ad634ba3c28896451c79a879e98a0b9daaa2bed1 | eewig/smart-calculator | /tests.py | 4,121 | 3.703125 | 4 | import unittest
from .calculator import Calculator
class TestCalculator(unittest.TestCase):
def test_sign_checker1(self):
calc = Calculator()
signs = [
'--', '-----', '+++++', '-+++++', '+++-', '----'
]
result = (
'+', '-', '+', '-', '-', '+'
)
... |
0665ad8cca7a4600529862c641cb4d75d2a4edfe | Deadsaref/python | /4 lesson/2 task.py | 160 | 3.578125 | 4 | numbers = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
bigger = [i for i in numbers if (i > numbers[numbers.index(i)-1] and i != numbers[0])]
print(bigger) |
cedbc7be6f1278c4cb41416245ce4ac62ead726f | Deadsaref/python | /3 lesson/4 task.py | 704 | 4.09375 | 4 | def my_func(x, y):
if x > 0 and y < 0 and type(y) == int:
# y = abs(y)
result_1 = x**y
print(f'Результат первым способом {result_1}')
''' Второй способ без оператора ** через дополнительную переменную z'''
z = x
for i in range(y-1):
z *= x
result_... |
689a87bb7fb07c5a9c7feca15dcb1889c233ed45 | joshmalek/Algorithm-examples | /Lab1/recurse.py | 152 | 3.65625 | 4 | import sys
def fib1(n):
if n == 0: return 0
if n == 1: return 1
return fib1(n-1) + fib1(n-2)
n = int(sys.argv[1])
print(fib1(n))
|
48afcbf3ad03532c072fe48adcd2612a6139f3dc | joshmalek/Algorithm-examples | /Lab4/problem_1.py | 839 | 3.78125 | 4 | def max_(A, B):
if len(A) > len(B):
return A
elif len(B) > len(A):
return B
else:
return A
def longest_palindrome_sequence (L):
n = len(L)
T = [[ [] for t in range(n) ] for i in range(n)]
X = [[ 0 for t in range(n) ] for i in range(n) ]
for i in range(n):
X[i][i] = 1
... |
b4392829743d5330d381dafb56d90e2464a41e6c | causten/iZombie | /pvz.py | 3,880 | 3.578125 | 4 |
TICSPERSECOND = 3
STEPSPERBLOCK = 3
BITESPERSECOND = 2
class zombie():
def __init__(self, zb, blockpos):
self.zb = []
self.zb = zombiesTable[zb]
self.xpos = STEPSPERBLOCK*blockpos
self.name = zb
def printStats(self):
print(self.name, 'Speed=',self.zb[0], ", Damage=", self.zb[1], ", He... |
3bc5e9cc103559035aa22af77921ef9779ca999f | Ingram7/SourceCodeOfBook | /第2章/program/function.py | 594 | 3.65625 | 4 | # def func_example_1():
# a = 1 + 1
# return a
# b = 2 + 2
# print(b)
#
#
# def func_example_2(x):
# if x <= 0:
# return x
# elif 0 < x <= 1:
# return x * 10
# else:
# return 100
#
# print(func_example_1())
a = [1, 2, 3]
b = 0
def change_list(para):
para.appen... |
2f373e168b093b3057388a38b4b8615c4827bc24 | dmitryfry/python_lessons | /lesson_4/issue_7.py | 203 | 3.78125 | 4 | from itertools import count
def factorial():
res = 1
for x in count(1):
res = x*res
yield res
x = 1
for el in factorial():
print(el)
x += 1
if x > 15:
break
|
2bdc45a874d1356d4dc0a54ca57a94877e224101 | dmitryfry/python_lessons | /lesson_3/issue_2.py | 439 | 3.796875 | 4 | def user_data(firstname, surname, birth_year, town, email, phone):
print(firstname, surname, birth_year, town, email, phone)
firstname, surname, birth_year, town, email, phone = input("введите имя, фамилию, год рождения, город почту и телефон через пробел: ").split()
user_data(firstname=firstname, surname=surname... |
bfcff6e6c4acbe85561fd8705202a53c4f817c66 | pingchoy/Sydney-Suburbs-Information-API | /API/stations/preprocess.py | 2,058 | 3.5625 | 4 | """
preprocess.py
University of New South Wales - Term 3, 2019
COMP9321 - Data Services Engineering
Assignment 2 - Team Degenerates
Import and clean data to be used by the train stations API endpoint.
- Clean/prepare train station data for calculations
- Save cleaned dataset in local directory
Dataset used:
Publ... |
f98d61d0d133dd9e93bc6a191da2cd5c88b6eb6e | pingchoy/Sydney-Suburbs-Information-API | /API/fuel/fuel.py | 4,016 | 3.53125 | 4 | """
fuel.py
University of New South Wales - Term 3, 2019
COMP9321 - Data Services Engineering
Assignment 2 - Team Degenerates
An API endpoint for fuel prices
"""
import re
import math
import json
import pandas as pd
from flask import Flask
from flask_restplus import Resource, Namespace, inputs, reqparse, fields
app = ... |
479fabfce877ffa01226203793db2646c44a17d7 | sudiptakarmakar/algae | /src/algae/clrs/utils/__init__.py | 1,164 | 3.515625 | 4 | from typing import List
from algae.clrs.common import TreeNode
from algae.clrs.common import ListNode
def create_tree(nodes: List[int]) -> TreeNode:
"""
This is ideal for leetcode type binary tree visualizer
"""
if not nodes:
return None
root = None
if nodes[0] is not None:
ro... |
8849df7852749c85d1a8c8d1774d32bd8a0e7b40 | sudiptakarmakar/algae | /src/algae/epi/arrays.py | 13,482 | 4.0625 | 4 | import bisect
import collections
import itertools
import math
import random
from typing import List, Any, Generator
def dutch_national_flag(numbers: List[int], index: int):
"""Write a program that takes an array A and an index i into A, and
rearranges the elements such that all elements less than A[i] (the "... |
b998fbf5c287740cde3bf3cfbe5f1de76f102fd3 | amitparmar01/python-learn | /practicepython/input-age.py | 417 | 3.84375 | 4 |
def main():
name = input('Please enter your name: ')
age = int(input('Now enter your age: '))
if age > 100:
cent = age - 100
year100th = 2015 - cent
print('Hello, ' + name + '. You turned 100 in the year ' + str(year100th))
else:
cent = 100 - age
year100th = 2015 + cent
print('Hello, ' + name + ... |
2e7ae63986b115133c8cac646784e8607d3d789e | amitparmar01/python-learn | /practicepython/fibonacci.py | 448 | 4.15625 | 4 |
def fibonacci(num):
if num == 0:
return 0
elif num == 1:
return 1
fSum = fibonacci(num-1) + fibonacci(num-2)
return fSum
def main():
length = int(input('How many fibonacci numbers to generate? '))
series = []
total = 0
for i in range(length + 1):
series.append(fibonacci(i))
print('Series :')
... |
d9587a07182f5f6517447d75377851d99a402a0b | genrobaksel/Home_Work_2 | /03_favorite_movies.py | 800 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Есть строка с перечислением фильмов
my_favorite_movies = 'Терминатор, Пятый элемент, Аватар, Чужие, Назад в будущее'
# Выведите на консоль с помощью индексации строки, последовательно:
# первый фильм
# последний
# второй
# второй с конца
# Переопределять my_f... |
9a33e57c3481fc1332fb5a9af178b9f5cdf57f4c | isabella232/Functions-Python | /sum_list.py | 601 | 4.1875 | 4 | # Note: Please uncomment each part of the exercise when you want to run it/play around with it,
# while making sure all other sections are commented.
# # 1: Basic function:
def sum_list(my_list):
sum = 0
for x in my_list:
sum += x
# # 2: Adding a return statement:
# def sum_list(my_list):
# sum =... |
d48a52135af0886eb5c951f3ee03c0238a188948 | waikato-datamining/wai-bynning | /src/wai/bynning/binners/_MinSizeBinner.py | 1,589 | 3.578125 | 4 | from typing import List
from .._Binnable import Binnable
from ._TwoPassBinner import TwoPassBinner
class MinSizeBinner(TwoPassBinner[int, int]):
"""
Binner which bins items by their size, placing items in
indexed bins until they exceed a certain minimum total
size.
"""
def __init__(self, min_... |
497230854a71d70dbadccabc87f35e79b2b8e24b | guava90/Sodoku-solver | /forced_chain.py | 471 | 3.5 | 4 | # Forced chain module
def find_guess(sodoku):
for i in range(9):
for j in range(9):
if sodoku[i][j][0] == " ":
guess = sodoku[i][j][1:]
break
return guess, i, j
def forced_chain(sodoku):
try:
guess ,i, j = find_guess(sodoku)
for k in gues... |
af03a44b81cd53c69cfd544f45d60c37d9b91767 | chandanbrahma/Decisiontree | /fraud_check.py | 2,774 | 3.734375 | 4 |
###importing the dataset
import pandas as pd
data = pd.read_csv("E:\\assignment\\decisiontree\\Fraud_Check.csv")
data.head()
data.describe()
data.info()
##lets convert all the non catagory columns into catagory format and replacing them into the dataframe
##catagorising the income column as >30000 is goo... |
e29f0967b5262e72ad58ec6c5faf50dbbd821f0d | malarc01/Data-Structures | /queue_and_stack/find_middle.py | 1,270 | 3.515625 | 4 | from doubly_linked_list import DoublyLinkedList
# return the middle node of the DLL, if there are two nodes, return the left one
# no empty list , length >= 1
# not sorted
# we do not know length!
# only one pass through
# 1-2-3: 2
# 5-2-3-5: 2
# Understand - not sorted
# Plan:
# - floor division
# - get length by... |
d82c39e29700827f8dc5acf5aa450c653daae7da | ThakurSarveshGit/CrackingTheCodingInterview | /Chapter 1 Arrays and Strings/1_8.py | 864 | 4.5 | 4 | # coding=utf-8
# Problem 1.8
# Assume you have a method isSubstring which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using
# only one call to isSubstring (i.e., “waterbottle” is a rotation of “erbottlewat”)
# Implemented Book's Solut... |
69500ed75cda6023eadd9358ce591a129db946cb | ThakurSarveshGit/CrackingTheCodingInterview | /Chapter 2 - Linked Lists/2_2.py | 1,052 | 4.375 | 4 | from linked_list import LinkedList
# Problem 2.2
# Implement an algorithm to find the nth to last element of a singly linked list.
# Algorithm:
# Step 1: find the length of the linked list
# Step 2: Print out the element at (length - n)th index.
# Solution:
# Step 1::: Finding Length
def find_length(h... |
5362bd3cab1d72eaca979d9406a710066c097397 | MDBarbier/Python | /dice_roller/dice.py | 901 | 3.546875 | 4 | #!/user/bin/python3
import random
import sys
print('loaded dice.py')
def roll_dice(varDiceType, numDice):
random.seed()
results = []
for x in range(numDice):
if varDiceType == "d6" or varDiceType == "D6":
varRoll = random.randint(1,6)
elif varDiceType == "D4" or varDi... |
e90bc37193c6f5ae3e37ecc8e64f46fe1788943c | one-trick/aoc2018 | /day4/day4.py | 4,669 | 3.6875 | 4 | #!/usr/bin/python
import re
from datetime import datetime
file_contents = []
input_file = "input.txt"
fh = open(input_file, 'r')
# First thing we need to do is read in our data and sort it by timestamp
for line in fh:
line = line.rstrip()
file_contents.append(line)
file_contents.sort()
# Now we need to parse the... |
1af5ec2822bc8ce2b1c245f37285eefe23141d32 | inlightus/py | /sudoku/backtrack_solver.py | 2,069 | 3.578125 | 4 |
backtracks = 0
def findNextCellToFill(grid):
for x in range(0, 9):
for y in range(0, 9):
if grid[x][y] == 0:
return x, y
return -1, -1
def isValid(grid, i, j, e):
rowOk = all([e != grid[i][x] for x in range(9)])
if rowOk:
columnOk = all([e != grid[x][j] f... |
e667bc02954e45b18aaca7de53dd4405bb626a7b | inlightus/py | /machine_learning/linear_regression/diabetes.py | 1,213 | 3.578125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
diabetes = load_diabetes()
# print(diabetes)
# print([i for i i... |
b0c55c7a163f235b71b4543b3d883a6bd6c37153 | inlightus/py | /scratches/runLengthEncoding.py | 796 | 3.75 | 4 | class RunLengthEncoding:
def encoding(self, text):
if not text:
return ""
else:
i = 0
while i < len(text) and text[0] == text[i]:
i += 1
return str(i) + text[0] + self.encoding(text[i:])
def decoding(self, text):
if not te... |
1d7ebc1b65ba02e23c43c2750360a2b7d9367cb0 | jadamsowers/arc-reactor | /Python/breathe.py | 2,174 | 3.625 | 4 | # breathe.py by J. Adam Sowers
# Generates an array of RGB values to make a NeoPixel device appear to
# 'breathe', similar to the sleeping MacBook LED indicator.
import math
import sys
import colorsys
r,g,b = 0x40,0xD0,0xFF # blue-ish glow
numSteps = 128
#colorsys expects RGB values in the range [0,1]
r,g,b = [ x ... |
49e3d0ad577d055b65ab465742900162a764de0e | Rachel-X/friction-sim | /basic_calculations.py | 4,810 | 3.75 | 4 | """Some simple calculations needed for the friction simulator.
Sources for the value of mu in coefficients.csv and MATERIALS
were https://www.engineersedge.com/coeffients_of_friction.htm
and Nelson Physics 11 textbook. Where ranges were given,
the lowest value was chosen. For the value of aluminum on ice,
the recommen... |
5e7fee8bda1b37ce5ab7a2721587c768d87f3220 | rishabmamgai/Image-Reduction-with-K-means | /extract_image.py | 898 | 3.53125 | 4 | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
def get_pixel_mat(file):
image = Image.open(file)
mat = np.array(image)
# Reshaping original 3D pixel matrix of image to 2D matrix, where column represents RGB
pixel_mat = np.reshape(m... |
130eeeee06eef846acd9528546c5b03642e7aa02 | sqluo2972/Algorithm | /others/Display Table of Food Orders in a Restaurant..py | 3,822 | 4.5 | 4 | # -*- coding: utf-8 -*-
from typing import List
"""
Created on Thu Sep 17 14:05:24 2020
@author: c0096
Display Table of Food Orders in a Restaurant
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where c... |
5279b959f90eace94f71283ae43e3c4af7f02acd | sqluo2972/Algorithm | /Linked List/Reverse Linked List.py | 1,135 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 10 18:08:20 2020
LeetCode
206. Reverse Linked List
Reverse a singly linked list.
Example:
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?
"""
# Definition f... |
3942fba2acc2586b2dd87e1b612c328cdb249e53 | asattelmaier/FlappyPython | /flappy_python/classes/fp_events.py | 1,056 | 3.5625 | 4 | import pygame
class FpEvents(object):
"""Handles all pygame events.
Events in this context are user key inputs.
"""
def handle_user_input(self, fp_player):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit_game()
if (self.ifKeyU... |
3ee2655f539b353d1ff7bbc06c8aa6e0c8ad0ae7 | christeenwoo/DMI | /python/sin_caur_summu_ver5.py | 647 | 3.546875 | 4 | # -*- coding : utf-8 -*-
from math import sin
# a0, a1, a2, a3 -> a
x = 1.* input("Lietotaj, ludzu, ievadi argumentu (x): ")
y = sin(x)
print "sin(%.2f) = %6.2f"%(x,y)
k = 0
a = (-1)**0*x**1/(1)
S = a
print "a0 = %6.2f S0 = %.2f"%(a,S)
#while k <= 3: # 0<=3 (1), 1<=3 (2), 2<=3 (3), 3<=3 (4)
while k <=3:
k = k ... |
54bd6ab0541a1be5802d52e88f36aec5195f06c7 | Nynergy/horizon | /draw.py | 750 | 3.5625 | 4 | """
This module aims to provide a nice suite of wrappers for drawing on curses
windows. Window must be provided to each function.
"""
import curses
from util import Point
def char(p, ch, win):
win.addch(p.y, p.x, ch)
def string(p, s, win):
win.addstr(p.y, p.x, s)
def h_line(p1, p2, ch, win):
if (p1.y !... |
7ff0044ba5d13d9be7770e31ac86ee768d2180de | Damishok/PP2 | /TSIS2/Lecture6/01.py | 115 | 3.609375 | 4 | def max_of_3(a, b, c):
return max(max(a, b), c)
a, b, c = map(int, input().split())
print(max_of_3(a, b, c)) |
5f4c83d79d8f7700c8c1b46afc778fdd6d1e4baa | Damishok/PP2 | /TSIS2/Lecture5/Task 1/14.py | 162 | 3.546875 | 4 | with open('b.txt') as fh1, open('a.txt') as fh2:
for line1, line2 in zip(fh1, fh2):
# line1 from b.txt, line2 from a.txt
print(line1+line2) |
a3a6f960c2590cd6aef763fe8e5daee3a6bc9c0f | Damishok/PP2 | /TSIS2/Lecture6/08.py | 180 | 3.65625 | 4 | def unique_list(list):
ans = []
for i in list:
if i not in ans: ans.append(i)
return ans
list = list(map(int, input().split()))
print(unique_list(list)) |
b07c4ddf7d827f3bbf75ed9062e998253d8629d8 | Damishok/PP2 | /TSIS1/13.py | 573 | 4.0625 | 4 | #1
a = 50
b = 10
if a > b:
print("Hello World")
#2
a = 50
b = 10
if a != b:
print("Hello World")
#3
a = 50
b = 10
if a == b:
print("Yes")
else:
print("No")
#4
a = 50
b = 10
if a == b:
print("1")
elif a > b:
print("2")
else:
print("3")
#5
a = 5
b = 5
c = 9... |
0a4e895907eede65c61d2a91baa6a4081901c575 | Saptarshidas131/Python | /p4e/exercises/ex4_6.py | 729 | 4.21875 | 4 | """
Exercise 6: Rewrite your pay computation with time-and-a-half for over-
time and create a function called computepay which takes two parameters
(hours and rate).
"""
# function to calculate pay given hours and rate as parameters
def computepay(hours,rate):
# check for overtime, if hours more than 40 add ex... |
8bae43d6438f6c118d5c2c0f876e5587ac75f493 | Saptarshidas131/Python | /p4e/exercises/ex6_5.py | 424 | 4.59375 | 5 | """
Exercise 5: Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the
colon character and then use the float function to convert the extracted
string into a floating point number.
"""
string = 'X-DSPAM-Confidenc... |
34979be18ceeebeffbcae5d52a376c5afe722814 | os2var/python_class | /menu_aritmetica.py | 719 | 4.09375 | 4 | #Ejercicio menu calculadora
import os # Importar librerias del sistema
os.system("cls")
print("Menú principal")
print ("1. sumar números")
print ("2. restar números")
print ("3. multiplicar números")
print ("4. dividir números")
print (".:::digite su opcion")
num1= int(input("ingrese el primer numero"))
num2= int(inp... |
4f19ea555877f94f95624016d6f9d7d3d6685a69 | os2var/python_class | /calculadora_avanzada.py | 748 | 3.890625 | 4 | #funcion para operaciones aritmeticas
def MENU ():
print(":::MENU ARITMETIO:::")
print("1.suma")
print("2.resta")
print("3.multiplicacion")
print("4.division")
print("5.Raiz cuadrada")
def operaciones():
if opc==1:
print("El resultado es:",a+b)
elif opc==2:
print("el d... |
ae170a1de0d51b94fc565343ffda5d05367709f3 | SarangMohaniraj/ChanceMe | /train.py | 4,015 | 3.953125 | 4 | import numpy as np
import pandas as pd
from preprocessing import inputs,outputs,inputs_test,outputs_test,college,min_year,max_year
from matplotlib import pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_prime(x):
return sigmoid(x) * (1-sigmoid(x))
#log loss
def error_formula(y, output):
... |
3ffa9fa4e13a7d61b4c4a5089dbf5c17c34df4f5 | rohitj205/Python-Basics-Code | /Variables.py | 2,910 | 4.375 | 4 | #Variable and Strings.
#Variables are used to store values.
#A String is a series of characters, surrounded by single or double quotes
#Printing Hello world
print("Hello world!")
#Printing Msg with a variable
msg = "Hey! This is My First Program in Python"
print(msg)
#Concatenation (combining strings)
... |
f33cfcb5c1722cf1b3bc970d28a4bdab7de03b1a | alicexue/softdev-hw | /hw08/sets.py | 504 | 3.5625 | 4 | c = [2, 4, 15, 5, 3]
d = [3, 2, 52, 1, 3]
def union(a,b):
return a + [x for x in b if x not in a]
print union(c,d)
def intersection(a,b):
return [x for x in a if x in b]
print intersection(c,d)
def setDiff(u,a):
return [x for x in u if x not in a]
print setDiff(c,d)
def symmetricDiff(a,b):
return... |
e2d647776fc55a166b2ec598c20e62b4a2dedd3b | asheba/NLP | /Exercise8/python/Wiki.py | 5,735 | 3.578125 | 4 | import sys, traceback
import re
class Wiki:
# reads in the list of wives
def addWives(self, wivesFile):
try:
input = open(wivesFile)
wives = input.readlines()
input.close()
except IOError:
exc_type, exc_value, exc_traceback = sys.exc_info()
... |
dba7f504efc7c16e98f107491a1207bd86d040b1 | cornjacket/python_poker | /poker_02_01.py | 7,333 | 3.953125 | 4 | def poker(hands):
"Return the best hand: poker([hand, ...]) => hand"
return allmax(hands, key=hand_rank)
def his_allmax(iterable, key=None):
#why call it iterable, so that it is a generic function not tied to poker
"Return a list of all items equal to the max of the iterable."
# Your code ... |
2f838ddd04f86ab81721c5308385aa798d03b493 | AviModi/4-4s | /four fours.py | 606 | 3.8125 | 4 | import math
import random
print("Did You Know That You Can Make Any Number From Four 4's")
number=random.randint(1,100)
user_input = input("Try Making {} Using Four 4's: ".format(number))
user_input=user_input.replace("fact","math.factorial")
user_input=user_input.replace("sq","math.sqrt")
user_input=user_input.replac... |
42029ff56fe4971e0ff939599da1ccec87db078d | BrichtaICS3U/assignment-2-logo-and-action-MoaizA | /action.py | 2,502 | 4.15625 | 4 | # ICS3U
# Assignment 2: Action
# <MOAIZ AHMAD>
# adapted from http://www.101computing.net/getting-started-with-pygame/
# Import the pygame library and initialise the game engine
# Don't forget to import your class
import pygame, random
from snow import Snow
pygame.init()
pygame.mixer.pre_init(frequency=44100, size=-... |
e5f74928455f02513b7feaa63103b98c6bd514f0 | mahmood-212/Snake-Game2 | /mali-merge-project-start/Mail Merge Project Start/main.py | 1,039 | 3.8125 | 4 | #TODO: Create a letter using starting_letter.txt
#for each name in invited_names.txt
#Replace the [name] placeholder with the actual name.
#Save the letters in the folder "ReadyToSend".
#Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
#Hint2: This method will also hel... |
019ee6a713ac9738e69ccb1104b13c778104beb6 | jesse-python/python-OOP | /bike.py | 638 | 4.1875 | 4 | class Bike(object):
def __init__(self, price, max_speed, miles):
print "New Bike"
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print "This bike's price is " + str(self.price) + ", max speed is " + str(self.max_speed) + ", and mi... |
86f1700723366548d44974dcbef970bda98e7231 | yoyokazoo/MagicArtDownloader | /stats_scripts/openPacks3.py | 1,203 | 3.625 | 4 | # calculates chance after opening N packs that you've opened at least one of each unique rare/mythic
import random
RARES = 53
MYTHICS = 15
CARDS_ON_SHEET = 121
PACKS_PER_TRIAL = 121
TRIALS = 100000
total_unique_rares = 0
total_unique_mythics = 0
total_successes_rare = 0
total_successes_mythic = 0
for t in range(TR... |
33a42fad7b55e1d255c66240832ed0ebdf3b65cc | amitrajitbose/algo-workshop-lhd19 | /stack/balance-brackets.py | 451 | 3.765625 | 4 | opp = {
'}':'{',
']':'[',
')':'('
}
for _ in range(int(input())):
exp = list(input())
stack = []
if len(exp) < 2:
print('not balanced')
continue
stack.append(exp[0])
for i in exp[1:]:
if i in opp and len(stack) and stack[-1] == opp[i]:
stack.pop(-1)
... |
d1a86b3ea51ba79855722fe624e01db11484691c | AlirezaMojtabavi/Python_Practice | /Elementary/2- functions and loops/Ex_3_max_Age.py | 202 | 3.921875 | 4 | initialAge = int(input())
age = 0
maxAge = initialAge
while (age != -1):
age = int(input())
if maxAge > age:
maxAge = maxAge
else :
maxAge = age
print(maxAge) |
bc5676eaffff928db239345f11a244f3b34a523a | bashir29143/edu | /coursera/python_spec/week1_task2.py | 91 | 3.625 | 4 | import sys
num = int(sys.argv[1])
for i in range(num):
print((num-i-1)*" " + (i+1)*"#")
|
8a846157858b1bdb1913eeb6e471ba8f47683836 | KxcCarter/python-pong | /main.py | 1,429 | 3.625 | 4 | from turtle import Screen
import time
from ball import Ball
from paddle import Paddle
from scoreboard import Scoreboard
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = Screen()
screen.bgcolor("black")
screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
screen.title("Pong")
screen.tracer(0)
GAME_IS_ON = True
r_paddle = Paddle... |
4f7383b74afb9d366442bcaa86e1019fe72a9465 | gthomas08/Data-Visualization-Project | /py_files/dataframe.py | 3,481 | 3.796875 | 4 | import pandas as pd # Analyze data
import calendar # Get the months
import sqlite3 # Manage the datatbase
def total_arrivals():
print("Calculating Total Arrivals...")
# Connect to database
conn = sqlite3.connect("../tourism.db")
# Get the dataframe from the database
df = pd.read_sql_query("SELEC... |
228681438325327c5b697623cb16e1f1d4e9b370 | RikoLi/isee-final-design | /codes/py_codes/tooth_detection.py | 8,974 | 3.515625 | 4 | '''
Definition of tooth detector class.
'''
import os
import itertools
import numpy as np
import cv2.cv2 as cv
import matplotlib.pyplot as plt
from utils import get_points
from scipy.ndimage.filters import gaussian_filter1d, maximum_filter1d
class ToothDetector:
'''
Create a tooth detector.
'''
def __i... |
f7d558e316b91d754b18e949deb74b94e7680007 | Leon0r/ProyectoSonido | /src/GameObjects/DraggableObject.py | 4,327 | 3.71875 | 4 | import pygame
from GameObjects.Sprite import Sprite
from GameObjects.GameObject import GameObject
from Utils.Utils import positionIsInsideRect
class DraggableObject(GameObject):
"""
This object contains a sprite to render, methods to modify that sprite and
the ability to be dragged around the screen by th... |
b1526fc48761f0101593b9de64e978f271569498 | nirbhaysinghnarang/CU_Boulder_DSA | /CLRS214.py | 564 | 3.703125 | 4 | #add two binary numbers represented by arrays
#CLRS Chapter 2.1, Problem 4.
def problem(a1,a2):
sum_1 = 0
sum_2 = 0
for j in range(0,len(a1)):
if(a1[len(a1)-j-1]==1):
sum_1+=2**(j)
for i in range(0,len(a2)):
if(a2[len(a2)-i-1]==1):
sum_2+=2**(i)
sum = sum_1+su... |
e95b7e697acdb2eddbff3a0d2107595014b93b88 | VitorTomazzi/py-practice | /PyPract/SecretWord.py | 412 | 4.15625 | 4 | secret_word = 'rave'
guess = ''
no_of_guesses = 1
out_of_guesses = False
while guess != secret_word and not out_of_guesses:
guess = input('Enter guess: ')
if guess == secret_word:
print('You guessed correct')
elif no_of_guesses == 3:
print('Out of Guesses')
out_of_guesses = True
... |
a41987ef5f9731c1a9cb6d7ce95d3269092e3474 | shaynemei/language-model-en | /script/build_lm.py | 3,464 | 3.578125 | 4 | import sys, re, math
def truncate(n, decimals=10):
multiplier = 10 ** decimals
return int(n * multiplier) / multiplier
def main():
with open(sys.argv[1], 'r') as f:
data = f.readlines()
unigram_dict = {}
bigram_dict = {}
trigram_dict = {}
for line in data:
line = line.... |
5cb7bfc87ba4ea36c69a15f3676f5f7eaffb0d18 | vimleshtech/mynewrepository | /Python/functionEx.py | 912 | 3.84375 | 4 | '''
input()
print()
max()
min()
sum()
sort()
append()
remove()
int()
str()
float()
split()
list()
replace()
subString()
a.upper()
a.lower()
'''
a = [444,323,2121,1,2233]
m = max(a)
print(m)
print(min(a))
print(sum(a))
a.sort()
print(a)
## remove
a = [3,4,432,2]
print(a)
a.remove(4)
print(a)
d = a[2]
a.remove(... |
5bcdb28a74df8cf615a232ac752c74cdde12519d | SimonJinaphant/Miscellaneous | /Morse Code/morse_encoder.py | 1,338 | 4.40625 | 4 | '''
A simple morse code encoding program
Social Studies 11 - Artifact 2
- Simon Jinaphant & Gopal Sharma
This program has simplified source code with comments explaining the process,
if you don't understand programming it's okay, the comments should be able to
guide you through what's happening
'''
table = ... |
4329f38d4534c179aadfe2e4683699f5a203e550 | BarbaraAFernandes/python | /CodesComplete/DataStructures/generator.py | 588 | 4.25 | 4 | import time
#generator function creates an iterator of odd numbers between n and m
def oddGen(n,m):
while n<m:
yield n
n+=2
#builds a list of odd numbers between n and m
def oddLst(n,m):
lst=[]
while n<m:
lst.append(n)
n+=2
return lst
#the time it takes to perform s... |
bc22f05ca1bc60774b88910a1bc0272e298d92fa | BarbaraAFernandes/python | /CodesComplete/Extras/maiusculas.py | 194 | 3.6875 | 4 | """
@author: vinimmelo
Select letters in uppercase
"""
def maiusculas(frase):
nova_frase = ""
for x in frase:
if x.isupper():
nova_frase += x
return nova_frase
|
734c0fa074a5f51ffec9435a4b36af6829e20950 | BarbaraAFernandes/python | /CodesComplete/Coursera/busca_sequencial.py | 136 | 3.5625 | 4 | def busca(lista, elemento):
i = 0
for x in lista:
if elemento is x:
return i
i += 1
return False |
d6dc38a06908b61e475f4910ab433f73e6a380a4 | BarbaraAFernandes/python | /CodesComplete/Extras/fizz_buzz.py | 268 | 4.0625 | 4 | """
Created on Nov 01
@author: vinimmelo
FizzBuzz test!
"""
for x in range(1, 101):
if (x % 3) == 0 and (x % 5) == 0:
print("FizzBuzz")
elif (x % 3) == 0:
print("Fizz")
elif (x % 5) == 0:
print("Buzz")
else:
print(x)
|
08da5580c77763a02bd23ebd675a792c8b5ca4e8 | BarbaraAFernandes/python | /CodesComplete/FluentPython/copy_test.py | 411 | 3.578125 | 4 | class Bus:
"""
The ideal Bus model, that makes a copy from the passed list,
and not an alias.
"""
def __init__(self, passengers=None):
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
def pick(self, name):
se... |
5eeec88ea8e3efd409e1a8b0eb9216d72be13799 | BarbaraAFernandes/python | /CodesComplete/CrashCourse/Dice.py | 513 | 4.03125 | 4 | """
Created on 17 December 2018
@author vinimmelo
Simple dice Class.
"""
from random import randint
class Die:
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
roll = randint(1, self.sides)
print(f"The dice of {self.sides} sides, rolls the number: {roll}")
if __nam... |
f2a83b0b6d6a295d0a5329926bdc2e39c79e2b3a | tp5uiuc/soft_systems_course | /lectures/08_povray/code/dump_snake.py | 2,916 | 3.5 | 4 | #!/usr/bin/env python3
""" Dumps the snake as a sphere sweep given data points and radii """
__author__ = "Tejaswin Parthasarathy"
__license__ = "GPL"
import numpy as np
def dump_snake_to_povray(t_step, t_pos, t_radius=0.01, t_prefix=""):
""" Dumps the rod for visualization in povray. Assumes that the
rod i... |
1146a1930fc3f34bee22ad5d06b630b3247ad969 | Degelzhao/python | /python_cc/fourth_part/while1.py | 575 | 3.765625 | 4 | 'practice'
__author__ = 'Degelzhao'
# way 1
prompt = "\nplease input your pizza toppings"
prompt += "\nor input 'quit' to end your order: "
message = ''
while message != 'quit':
message = input(prompt)
if message != 'quit':
print("we will add this " + message + " to pizza")
# way 2
prompt = "\nplea... |
c1d634ef699607ba03abc72f35ea8dd5a5718de6 | Degelzhao/python | /pro_thrd/process.py | 3,880 | 3.546875 | 4 | #fork():
#fork()调用一次,返回两次
#子进程永远返回0,而父进程返回子进程的ID
#一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID
#multiprocessing:
from multiprocessing import Process #multiprocessing模块提供了一个Process类来代表一个进程对象
import os
def run_proc(name):
print('Run child process %s (%s)...'%(name,os.getpid()))
... |
c31f35f8dfdebee364237cd60c4ef9d16dd9ec59 | Degelzhao/python | /batteries_included/use_hashlib1.py | 1,134 | 3.8125 | 4 | #use hashlib
#根据用户输入的口令是否正确,返回True或False
__author__ = 'Degel zhao'
import hashlib
#normal
def get_md5(password):
md5 = hashlib.md5()
md5.update(password.encode('utf-8'))
return md5.hexdigest()
def calc_md5(password):
return get_md5(password)
db = {
'michael': 'e10adc3949ba59abbe56e057f20f... |
749ccb61eeda26f11566ff57c8b806c631e091ea | Degelzhao/python | /python_interview/bubble_sort2.py | 462 | 3.53125 | 4 | arr = [7, 4, 3, 67, 34, 1, 8]
def bubble_sort(arr):
n = len(arr)
for j in range(0, n - 1):
for i in range(0, n - 1 - j):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
list = arr[:]
p = len(list)
a = 0
p -= 1
s = 0
while a < p:
... |
2e7e6ebfd79ce447b7fa269648b4d1b53aee3335 | Degelzhao/python | /pro_thrd/thread.py | 2,882 | 4.0625 | 4 | #多线程
import time, threading
# 新线程执行的代码:
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
prin... |
5e5eaec874100bb5301d0bdb6a57247a032ee1bf | Degelzhao/python | /python_basic/while.py | 189 | 3.59375 | 4 | sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
#the practice of while
L = ['Bart', 'Lisa', 'Adam']
n = 0
while n < 3:
print('Hello,%s'%L[n])
n = n + 1 |
6d86cbb72003a47af9ab863c14cccee4c5792820 | Degelzhao/python | /python_cc/seventh_part/pgm_survey.py | 317 | 3.890625 | 4 | filename = 'reason_pgm.txt'
while True:
reason = input('Would you please tell me why you like programming?')
with open(filename, 'a') as file_object:
file_object.write(reason + '\n')
repeat = input('Would you like to let another person response? (yes/no)')
if repeat == 'no':
break
|
bcb7bb4976fc98d86fc30c35cd1ac8772f8bfbb4 | Degelzhao/python | /in_output/parctice2.py | 294 | 3.578125 | 4 | s1 = 72
s2 = 85
r = (s2 - s1)/s1 * 100
print('小明的成绩相比去年提升了: %0.1f%%'%r)
print('小明的成绩相比去年提升了: {0:.1f}%'.format(r))
print('小明的成绩相比去年提升了: %.2f%%'%r)
print('小明的成绩相比去年提升了: {:.2f}%'.format(r)) |
b69ec24f0d3678e76099963aabb690cd41b704f4 | Degelzhao/python | /advanced_features/slice.py | 220 | 3.984375 | 4 | #使用切片来完成trim操作
def trim(s):
if s[:1] != ' ' and s[-1:] != ' ': #判断首尾是否为空
return s
elif s[:1] == ' ':
return trim(s[1:])
elif s[-1:] == ' ':
return trim(s[:-1])
|
598b7c6b652e8bc8a00e6c8ee8134ea5b2259ce9 | Degelzhao/python | /ASY_IO/use_async&await1.py | 908 | 3.59375 | 4 | # 用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后
# 在coroutine内部用yield from调用另一个coroutine实现异步操作
# 为了简化和更好的标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读
# 替换步骤:
#1.把@asyncio.coroutine替换为async
#2.把yield from替换为await
import time
import asyncio
now = lambda : time.time()
# async关键字定义了一个协程(coro... |
9e12660e01662696f31e6461e2d435fdbf0783db | Degelzhao/python | /OOP/inhe_poly.py | 2,162 | 4.46875 | 4 | #继承和多态
'inheritance and polymorphism'
__auothor__ = 'Degel zhao'
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Eating meat...')
class Cat(Animal):
def run(self):
print('Cat is... |
987a8fe075ffe3c7ebd201457d02c27ac3d701d7 | Degelzhao/python | /batteries_included/use_hashlib2.py | 700 | 3.96875 | 4 | #根据用户输入的登录名和口令模拟用户注册,计算更安全的MD5(add Salt)
'use hashlib'
__author__ = 'Degel zhao'
import hashlib
def get_md5(str):
md5 = hashlib.md5()
md5.update(str.encode('utf-8'))
return md5.hexdigest()
db = {}
def register(username,password):
db[username] = get_md5(password + username + 'the-Salt')
def lo... |
ab2c6b98f78e0aecd5168361b8c584a41519ec5d | vinitjfaria/Python | /HackerEarth/ArraySum.py | 671 | 4.03125 | 4 | '''You are given an array of integers of size . You need to print the sum of the elements in the array, keeping in mind that some of
those integers may be quite large.
Input Format
The first line of the input consists of an integer . The next line contains space-separated integers contained in the array.
Output... |
d9524511cfaf261ea21bbbeaee89a4585d204b9d | Tony363/Uni_homework | /w3resource.py | 2,733 | 3.890625 | 4 | import random
# Write a Python program to calculate the sum of a list of numbers
def sum_list(lst,total = 0):
total += lst[0]
del lst[0]
if len(lst) == 0:
return total
else:
return sum_list(lst,total)
# print(sum_list([i for i in range(11)]))
def recursion_list(lst,total = 0):
... |
f2e4b53d7f232f532df97a513f3bcd7189f8d685 | Tony363/Uni_homework | /skeleton (1)/skeleton/engi1006_simulator/course.py | 4,209 | 3.796875 | 4 | from statistics import mean
import matplotlib.pyplot as plt
from .student import Student
from .assignment import Assignment
from .utilities import skillToGrade
class Course(object):
def __init__(self, teacher):
self.teacher = teacher
self.students = []
self.assignments = []
self.gr... |
d55a369b665ec4997ecfcc3e8f15b4382d23b373 | chengyangwang0903/wang_codes | /practice2021_10_9.py | 2,498 | 3.9375 | 4 | '''
#1实现购物车程序
import sys
# keep the code below
goods = [
{"name": "Computer", "price": 1999},
{"name": "Mouse", "price": 10},
{"name": "Yachts", "price": 20},
{"name": "Airplane", "price": 998}
]
asset = int(sys.argv[1])
input_list = eval(sys.argv[2])
# write your code here
for i in input_list:
... |
1fc4ef58b86384ae5f867e896c00967855f7393a | kjhjh04003/studyPython | /chap06/loop_check.py | 729 | 3.921875 | 4 | # for문으로 리스트[3,2,1,0]출력
# lst = list()
# for n in range(3,-1,-1):
# lst.append(n)
# print(lst)
# guess_meㄹ 변수에 7을 할당, number 변수에 1 할당
# while문을 이용하여 비교
guess_me = 7
number = 1
while True:
if number < guess_me:
print("too low")
elif number > guess_me:
print("oops")
break
else:
... |
96101deb012e06ccbdbdb3e2b1307f2c334f872c | kjhjh04003/studyPython | /chap04/conditional.py | 1,548 | 3.78125 | 4 | # disaster의 값을 확인하고, 단어 출력
disaster = True
if disaster:
print("Woe!")
else:
print("Whee!")
# 중첩 if
furry = True
large = True
if furry:
if large:
print("It's a yeti")
else:
print("It's a cat!")
else:
if large:
print("It's a whale!")
else:
print("It's a human.Or a... |
91723806b7e4d21e734e2faf21237e48c4fb97de | Manishbatra4/python_tut | /basic/4. condition_operator.py | 196 | 4.03125 | 4 | marks = int(input("Enter Your marks : "))
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 60:
print("Grade C")
elif marks < 60:
print("Grade D")
|
4f05b7ff0ed3d1900da6b57a5fe24e387fbd23db | Manishbatra4/python_tut | /miscellaneous/04. List Comprehension.py | 67 | 3.71875 | 4 | list = [x ** 2 for x in range(20) if x ** 2 % 2 == 0]
print(list)
|
97b2a612357f037fcee09c8d34310e1d11491736 | DaniGarcia231/Cisco-Devnet-Courses | /Intro-Python/Part1/hands_on_exercise.py | 1,329 | 4.40625 | 4 | """Intro to Python - Part 1 - Hands-On Exercise."""
import math
import random
# TODO: Write a print statement that displays both the type and value of `pi`
pi = math.pi
x = type(pi)
print(x, pi)
# TODO: Write a conditional to print out if `i` is less than or greater than 50
i = random.randint(0, 100)
if(i < 50):... |
94c8d1d3269421c7bc0fd1876448c9ed1d159244 | sayuri-ey/letterboard_phrases | /Letterboard.py | 1,414 | 4.21875 | 4 | '''
Code to verify the possibility of writing phrases with available characters set in a letterboard.
It asks the user for a phrase (input) and it checks whether it is possible to write the phrase,
or if there are insufficient characters in the set to write the determined phrase
or if the user is using invalid charate... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.