blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
9675fabd0c4e3c7a443cee4304c49457961f3eb3 | Twoody/CtCI_v6_Python | /2_linkedLists/questions/q3.py | 514 | 4.03125 | 4 | '''
3. Delete Middle Node
Implement an algorithm to delete a node in the middle of a
singly linked list, given only access to that node.
The middle is any node but the first and last node, not
necessarily the exact middle.
Example:
I: the node c from the linked list:
a -> b -> c -> d -> e -> ... |
9f939317f636304f2ca575332bce620f17b1f16d | Twoody/CtCI_v6_Python | /500Questions_intPrep/knightstour_V4.py | 4,189 | 3.6875 | 4 | '''
'''
def sortByLowestNeighbor(akms):
''' Need to visit corners and borders first '''
''' Will INSERTION SORT by a custom `weight` of moves available neighbors '''
''' '''
for cur in akms:
moves = akms[cur]
nmoves = []
for move in moves:
weight = len(akms[move])
if weight == 8 or nmoves == []:
nm... |
5b431d4f88cee8a15a82025664253ddfc4c563c8 | Twoody/CtCI_v6_Python | /20181113_prep/heaps.py | 4,268 | 3.984375 | 4 | '''
Tanner Woody
20181112
Purpose:
heapify.py is meant to show that a heap is a complete binary tree.
heapify.py is meant to teach what a heap is, and lead to a heap sort.
Core Principals on Heaps:
1. Heap must be Complete Binary Tree (CBT)
2. Heap weight must be greater than weight of any child
'''
class Node:... |
6014df3a20629be8e80096cc780a81e8cb6b490d | Twoody/CtCI_v6_Python | /500Questions_intPrep/mergesort_twounsortedarrays.py | 1,130 | 4.09375 | 4 | def mergeTwo(arr1, arr2, args=None):
returntuple = False
if args is None:
args = {}
if 'returntuple' in args and args['returntuple'] == True:
returntuple = True
''' Assuming arr1 and arr2 are sorted at this point '''
if arr1 is None:
if arr2 is None:
return []
return arr2
if arr2 is None:
return arr1... |
3acd49be1964d9f9c794f97ab9cc1269471a1b44 | Twoody/CtCI_v6_Python | /2_linkedLists/questions/q1.py | 266 | 3.546875 | 4 | '''
1. Remove Dups
Write code to remove duplicates from an unsorted linked list.
Follow up:
How would you solve the probem if a temporary buffer is
not allowed?
'''
def q1():
print('PASSED ALL TESTS')
return True
if __name__ == "__main__":
q1()
|
43dc2d778d68dedf09430d0e6a8fb65b633ca9eb | Twoody/CtCI_v6_Python | /randoms/inttest.py | 1,568 | 3.765625 | 4 | '''
for n>0 and n<1000, solve all instances of:
a^3 + b^3 = c^3 + d^3
a**3 + b**3 = c**3 + d**3
Brute force would look like for i, for j, for k, for l... which would
run as 1000**4 iterations about.
NOT OPTIMAL
A better solution is to make a set of all of the cubed numbers first.
'''
def getcubes(n=0):
mList =... |
4dab177838a46c84b505b84805375fe8826848a2 | datorre5/CIS2348-FALL2020 | /3.18.py | 808 | 3.828125 | 4 | # Daniel Torres
# PSID: 1447167
# Zybooks 3.18
wall_height = int(input('Enter wall height (feet):\n'))
wall_width = int(input('Enter wall width (feet):\n'))
wall_area = wall_height * wall_width
print('Wall area:',wall_area,'square feet')
gallons = wall_area / 350
cans = round(gallons)
print('Paint needed:','{:.2f}'... |
a41b9059446e0700fda503cd0647712d6c95a55d | datorre5/CIS2348-FALL2020 | /12.7.py | 677 | 4.0625 | 4 | #Daniel Torres
#PSID: 1447167
# Take age input form user
def get_age():
age = int(input()) # take age input
if 18 <= age <= 78:
return age
else:
# raise a exception
raise ValueError("Invalid age.")
# Calculate fat burning heart rate
def fat_burning_heart_rate():
age = get_a... |
f25ecf69bcb1c5f168f74fd923d72b9a53248763 | MomSchool2020/show-me-your-cool-stuff-LisaManisa | /Lesson3.py | 583 | 4.15625 | 4 | print("Hello World!")
# if you have a line of text that you want to remove,
#"comment it out" by adding in a hashtag.
# print("Hello World!")
# text in Python is always in quotation marks
print("Lisa")
print("Hello World. Lisa is cool")
print("Lisa said, 'I love you'")
print('Lisa said, "I love you"')
# if you put anyt... |
aa3df860a775d8f74eaf59c7e54fde713a4698f0 | sankeerthmamidala/python | /draw_S.py | 281 | 3.65625 | 4 | from turtle import *
pen1 = Pen()
pen2 = Pen()
pen1.screen.bgcolor('#3ec732')
pen1.goto(0,300)
pen1.goto(150,150)
pen1.goto(300,300)
pen1.goto(300,0)
pen.up()
pen.goto(350,0)
pen.down()
for i in range(0,250):
pen2.backward(3)
pen2.right(1)
pen1.fd(3)
pen1.right(1)
|
040c8f1d7abaee1063000a4811771828addb8f0f | sankeerthmamidala/python | /first.py | 65 | 3.65625 | 4 | a = int(input(print('enter the nummber',' ')))
a= a+1;
print(a);
|
ab9b610a947309886e99d0678eba60e11b426a76 | mihabin/wmctf-register | /src/region.py | 495 | 3.546875 | 4 | from country_list.country_list import countries_for_language
region_code = [i[0] for i in countries_for_language('zh_CN')]
def list_region(lang: str = 'en_US'):
try:
return countries_for_language(lang)
except:
return countries_for_language('en_US')
def get_region_name(region_code = 'CN', lang... |
821f16b00b90c79867dfbfbf7f93d92d9ce3a23b | agray998/qa-python-assessment-example | /exampleAssessment/Code/example.py | 503 | 4.5625 | 5 | # <QUESTION 1>
# Given a string, return the boolean True if it ends in "py", and False if not. Ignore Case.
# <EXAMPLES>
# endsDev("ilovepy") → True
# endsDev("welovepy") → True
# endsDev("welovepyforreal") → False
# endsDev("pyiscool") → False
# <HINT>
# What was the name of the function we have seen which change... |
344b74138c8d12653ae2c8c5403248e1009fe8aa | luxmeter/sudokusolver | /sudokusolver/model/iterators.py | 1,004 | 3.75 | 4 | """Provides iterators to iterate through
the nodes of the rows and columns of the ConstraintMatrix."""
class ColumnIterator(object):
"""Iterates through a sequence of vertically connected nodes."""
def __init__(self, start, reversed=False):
self._current = start
self._reversed = reversed
... |
6ee37c9ee3b0227b623f669fe828473d75ec716d | ramnathpatro/Python-Programs | /Algorithm_Programs/monthlyPayment.py | 581 | 3.765625 | 4 | import re
from Algorithm_Programs.utility import algorithm
ref = algorithm
def monthly_payment():
P1 = input("Enter the principal loan")
Y1 = input("Enter the Year")
R1 = input("Enter the interest")
cheack_P = re.search(r"^[\d]+$", P1)
cheack_Y = re.search(r"^[\d]{1}$", Y1)
cheack_R = re.searc... |
8fae5343cbecfcf4f25e57a9a4b5ebbdedebc67c | ramnathpatro/Python-Programs | /Functional_Programs/Coupon_Numbers.py | 506 | 3.703125 | 4 | import random
import re
inp = input("How much coupon you want")
generated_cop = []
coupon = 0
x = re.search(r"^[\d]+$", inp)
rang = 1000
if x:
inp = int(inp)
if inp <= rang:
while coupon < inp:
coupon_gen = random.randrange(rang)
if coupon_gen not in generated_cop:
... |
ca24b56a383926f19ef37888caa487424ecd81a5 | ramnathpatro/Python-Programs | /Functional_Programs/Flip_Coin.py | 473 | 3.9375 | 4 | import re
import random
inp = input("how many time you flip the coin")
heads = 0
tails = 0
flip_coin = 0
check = re.search(r"^[\d]+$", inp)
#print(check.group())
if check:
inp = int(inp)
while flip_coin < inp:
flip_coin += 1
coin_tos = random.randrange(2)
if coin_tos == 0:
... |
6e8a31960b340922a3feed81385e27d501f12244 | dillanmann/AdventOfCode2019 | /py/day4_bonus.py | 878 | 3.625 | 4 | # run with `cat <input_file> | py day4_bonus.py`
import sys
def never_decreases(digits):
last = digits[0]
for digit in digits:
if digit < last:
return False
last = digit
return True
def valid_doubles(digits):
has_double = False
for i in range(1, len(digits)):
... |
0d5dac3a095a6aaa2025d2d3f463b568a90fe276 | IgorCrepo/AiSD | /kopiec.py | 1,851 | 3.8125 | 4 |
class Heap(object):
def __init__(self):
self.heap = [0]
self.currentSize = 0
def __str__(self):
heap = self.heap[1:]
return ' '.join(str(i) for i in heap)
def Up(self, index):
while (index // 2) > 0:
if self.heap[index] < self.heap[index /... |
57c2fe53bdc866ad125d4076372da7cb33b677b9 | 0uterHeaven/FoodProject | /What to eat.py | 453 | 3.875 | 4 |
import random
hungry = input('What do you want to eat: Thai, Italian, Chinese, Japanese, Continental, Mexican, Junk, homemade or random? ')
ethnicity = ['Thai', 'Italian', 'Chinese', 'Japanese', 'Continental', 'Mexican', 'Junk', 'Homemade']
if hungry == 'random':
print(random.choice(ethnicity))
#e... |
99e4b05aed5a6ddf6bc9cd994edbb043ac530915 | Chukak/python-algorithms | /sorting/insertion.py | 373 | 4.09375 | 4 | """ Insertion sort """
array = [234, 345, 4, 32, 45455, 56, 76, 345, 46, 8678676, 567, 43, 2, 5, 8, 105, 4, 17]
def insertion_sort(array):
for i in range(len(array)):
x = i
for j in range(i + 1, len(array)):
if array[x] > array[j]:
x = j
array[x], array[i] = ar... |
13d0a7f9f92d01d9075eda1875e3e4eeb84a729f | Chukak/python-algorithms | /sorting/quicksort.py | 773 | 4.09375 | 4 | """ Quicksort sorting """
import random
array = [234, 345, 4, 32, 45455, 56, 76, 345, 46, 8678676, 567, 43, 2, 5, 8, 105, 4, 17]
def quicksort(array):
if not array:
return []
element = random.choice(array)
less = list(filter(lambda x: x < element, array))
equally = list(filter(lambda x: x == ... |
231b812ebd89cf804f350a03e3ca5d0b11023cb8 | TonaGonzalez/CSE111 | /02TA_Discount.py | 1,162 | 4.15625 | 4 | # Import the datatime module so that
# it can be used in this program.
from datetime import datetime
# Call the now() method to get the current date and
# time as a datetime object from the computer's clock.
current = datetime.now()
# Call the isoweekday() method to get the day
# of the week from the current... |
a3991ade1335bc3b3004d40131a6f075937e88d2 | dhockaday/melodically | /melodically/rhythm.py | 2,720 | 4 | 4 | def get_durations(bpm):
"""
Function that generate a dictionary containing
the duration in seconds of various rhythmic figures.
:param bpm: beat per minutes
:return: rhythmic dictionary
"""
beat_time = 60 / bpm
return {
'1': beat_time * 4,
'2': beat_time * 2,
'4'... |
292da9f51f3a824f1dd98f55d406eda2571dcc04 | mosheb3/WorldOfGames | /SevenBoom.py | 367 | 3.828125 | 4 | ## Moshe Barazani
## Date: 04-02-2020
def play_seven_boom():
num = input("Enter Number: ")
while not num.isdigit():
num = input("Enter Number: ")
for x in range(int(num)):
x+=1
if not (x % 7):
print("BOOM!")
else:
if "7" in str(x):
pr... |
db35406d0a741624cba50bdfafd0734cde28f68c | Tom-Oosterbaan/C21-Think-Code-level-1 | /Eindopdracht/Eindopdracht.py | 228 | 3.8125 | 4 | guess = input("why was 6 afraid of 7? ")
if guess == "because 7 ate 9":
print("funny, right?")
else:
print("Nope, That's not it!")
print("Thanks for playing!")
def smiley():
print(":)")
smiley()
smiley()
smiley() |
26d11ca3eb7dbf0e0c295fcb0521a76278cf8d03 | Pablo-D-P-C/ficha_empleados | /datos.py | 694 | 3.875 | 4 | print("Completa el formulario para añadir un nuevo usuario")
while True:
nombre = input("Nombre: ").upper()
edad = input("Edad: ")
localidad = input("Localidad: ").upper()
provincia = input("Provincia: ").upper()
salario = input("Salario: ")
dni = input("DNI: ").upper()
print("Dece... |
656224c5e11814b8d58d01949dc467aa9c63e6e1 | nyhyang/Lab-14 | /app/models.py | 1,312 | 3.515625 | 4 | import sqlite3 as sql
def insert_user(nickname, email):
with sql.connect("app.db") as con:
cur = con.cursor()
cur.execute("INSERT INTO user (nickname, email) values (?, ?)",
(nickname, email))
con.commit()
def insert_trip(user_id, destination, name_of_trip, trip_dat... |
9707ab2fe38a9cf9a45659c488c323731d589cf0 | gabrieldsumabat/DocSimilarity | /tests/TestSimilarity.py | 1,176 | 3.515625 | 4 | import unittest
from code.Similarity import find_euclidean_distance, get_doc_distance_list, sort_sublist_by_element_desc
class TestSimilarity(unittest.TestCase):
def test_find_euclidean_distance(self):
dummy_dict1 = {
"a": 1,
"b": 2,
"c": 3
}
dummy_dic... |
6553c371c8c1cc2e6671ad3c357e35dfb15e1b23 | bsvonkin/Year9DesignCS4-PythonBS | /GuiDemo04.py | 374 | 3.5 | 4 | import tkinter as tk
root = tk.Tk()
lab = tk.Label(root, text = "Enter a number:")
lab.grid(row = 0, column = 0)
ent = tk.Entry(root)
ent.grid(row = 1, column = 0)
btn = tk.button(root, text = "Press Me")
btn.grid(row = 2, column = 0)
output = tk.Text(root)
output.configure(state = "disable")
output.grid... |
7956465a4c4703780cd7fbcecf28f230f042d271 | bsvonkin/Year9DesignCS4-PythonBS | /TakingInputInt.py | 166 | 3.9375 | 4 | #Input
#Assignment Statement
r = input("What is the radius")
r = int(r)
h = int(input("What is the height"))
#Process
sa = 2*3.14*r*r + 2*r*h*3.14
#Output
print(sa)
|
ec25ab4e6785ea9456a4c00c7945f40e5f111181 | Yuanty378/shiyan01 | /test1.py | 348 | 3.890625 | 4 | #message = "hello word!";
#print(message)
"""
a = int(input("请输入: "))
b = int(input("请输入: "))
print("input获取的内容: ",a+b)
"""
"""
练习:通过代码获取两段内容,并且计算他们长度的和。
"""
a = input("请输入: ")
b = input("请输入: ")
c = len(a)
d = len(b)
print("两段字符串的长度和是: ",c+d)
|
dd39e4444900ca40c744ec7860f916145be46d66 | Hyperboloider/lab9 | /lab9f.py | 614 | 3.796875 | 4 | def matches(string, symbols):
match = []
for word in string:
for symbol_f in symbols:
if word[0] == symbol_f:
for symbol_l in symbols:
if word[-1] == symbol_l:
match.append(word)
return match
def inp(msg = ''):
temp =''
... |
8b64b9e9b17445193dbd8e9973620fc2d95a570c | reget17/Python_Lessons | /lesson_003/00_bubbles.py | 1,001 | 3.8125 | 4 | # -*- coding: utf-8 -*-
import simple_draw as sd
sd.resolution = (1200, 600)
# Нарисовать пузырек - три вложенных окружностей с шагом 5 пикселей
# Написать функцию рисования пузырька, принммающую 2 (или более) параметра: точка рисовании и шаг
def bubble(point, step):
radius = 50
for _ in range(3):
... |
29efd589cc6dcf5299f9e67d7f8149d871294d6f | reget17/Python_Lessons | /lesson_003/08_smile.py | 1,595 | 3.625 | 4 | # -*- coding: utf-8 -*-
# (определение функций)
from random import random
import simple_draw
import random
import math
import numpy as np
# Написать функцию отрисовки смайлика в произвольной точке экрана
# Форма рожицы-смайлика на ваше усмотрение
# Параметры функции: кордината X, координата Y, цвет.
# Вывести 10 сма... |
c3881ca019e5cbd81b9a1cacccd0249fdbb942b3 | mrajibrm/PYTHON | /random22.py | 5,625 | 4 | 4 | import random
import matplotlib.pyplot as plt
import math
import numpy as np
import matplotlib.patches as mpatches
# Problem 1.4
# In Exercise 1.4, we use an artificial data set to study the perceptron
# learning algorithm. This problem leads you to explore the algorithm further
# with data sets of different sizes and... |
fc808427cd358046e223304d41d129e66c3e2b9b | AleksandrSarkisov/sort-methods | /sort_methods.py | 2,370 | 4.09375 | 4 | def sort_select(a:list):
'''
Сортирует массив методом выбора
'''
if len(a) <= 1:
return a
i = 0
while i < (len(a)-1):
for j in range(i+1, len(a)):
if a[i] > a[j]:
a[i], a[j] = a[j], a[i]
i += 1
return a
def sort_insert(a:list):
'''
Сортирует массив методом вставки
'''... |
c619969b5428467ad282834a205dd840fb710826 | Edinas09/Challenges | /CountsDown.py | 263 | 4.03125 | 4 | # Please write a program, in any language, that counts down from 100 to 0 in steps of 2,
# and prints the numbers to the console or screen.
def counts_down():
for value in range(100, 0, -2):
print(value)
if __name__ == '__main__':
counts_down()
|
4ee46d33355e847ecdfd0bf756afb09c4e57897b | Edinas09/Challenges | /MakingAnagramas.py | 1,055 | 3.796875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the makeAnagram function below.
def makeAnagram(a, b):
list_a = Counter(a)
list_b = Counter(b)
countador_a = 0
countador_b = 0
resultado = 0
for key, value in list_a.items():
... |
d63166b955a07b1f19c0a9f23cd8e02925ce0ceb | Edinas09/Challenges | /itaretesNumber.py | 597 | 4.03125 | 4 | # Write a program, in any language (incl pseudocode) that iterates the numbers from 1 to 100.
# For any value divisible by 4, the program should print "Go".
# For any value divisible by 5, the program should print "Figure".
# For any value divisible by 4 and 5, the program should print "GoFigure".
def iterates_numbe... |
3ea78de4a3085d9463d8900cde3e1151947340a7 | Edinas09/Challenges | /SwapNodesALGO.py | 1,928 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
#
# Complete the 'swapNodes' function below.
#
# The function is expected to return a 2D_INTEGER_ARRAY.
# The function accepts following parameters:
# 1. 2D_INTEGER_ARRAY indexes
# 2. INTEGER_ARRAY queries
#
class... |
05f560e6687bb95d517bb651acec2e3568bcb02a | b55888938/270201050 | /lab8/example2.py | 245 | 4.03125 | 4 | def get_reversed(lists):
reverse_list = []
n = len(lists) - 1
if n < 0:
return reverse_list
else:
reverse_list.append(lists[n])
return reverse_list + get_reversed(lists[:n])
print(get_reversed([1,2,3,4])) |
195d9760157a5b0a063c440e1f905c9f832d7baa | b55888938/270201050 | /lab4/example5.py | 210 | 4.0625 | 4 |
numb_numb = int(input("How many fibonacci numbers?"))
sum_1 = 0
sum_2 = 1
print(sum_1)
print(sum_2)
for i in range(numb_numb - 2):
sum_3 = sum_1 + sum_2
sum_1 = sum_2
sum_2 = sum_3
print(sum_3) |
feaf4b357c323a5099219062a09918416b6c5c1c | b55888938/270201050 | /lab4/example1.py | 87 | 3.828125 | 4 | a = int(input("Enter an integer."))
for i in range(1, 11):
print(a, "X", i, "=", a*i) |
62295fb7d63d29becc26c4ac978f13fae9f16ef2 | b55888938/270201050 | /lab3/example1.py | 218 | 3.71875 | 4 | numb = input("Please enter a number.")
a = len(numb)
sum = 0
if int(numb[a-2]) == 0:
for i in range (a-1 ,a):
sum += int(numb[i])
print(sum)
else:
for i in range (a-2 ,a):
sum += int(numb[i])
print(sum) |
a31958f6182b3968efbae1d271c1a26d7fb28efb | Chris-Slade/CS1538-Team-Project | /event.py | 6,243 | 3.90625 | 4 | """Classes of events in the simulation, and an event queue."""
import heapq
import drinks
import util
from person import Person
class EventQueue(object):
"""A priority queue for Events."""
def __init__(self):
self._queue = []
def push(self, event):
"""Add an event to the queue."""
... |
2c5ac096ec3a632930f550114f504dee8fb4ef87 | enrib82/Pr-ctica-2 | /Numero mayor.py | 164 | 3.875 | 4 | a=int(input("Ingrese un numero: "))
b=int(input("Ingrese un numero: "))
if a > b:
print "el numero mayor es" ,a,
else:
print "el numero mayor es" ,b,
|
349ab833260612e5a8a095f7bb6e81d51e36e1a0 | KnightApu/Dynamic-Programming | /edit-distance2.py | 1,337 | 3.859375 | 4 |
# coding: utf-8
# In[17]:
import json
with open('E:\Spell and Grammar Checker\MS Word Add-in\csvtconvertson/miniDictionary.json', encoding="utf8") as f:
data = json.load(f)
str1 = "দেশর"
for i in range (len(data)):
print(data[i]['words'])
print (editDistance(str1, data[i]['words'], len(str1), len(data[i... |
09b5e0397a0ff3776aed37f44fda22069263005b | berge156/Database-Managment-Chapman-University | /assignment_2/databaseFunctions.py | 1,720 | 4.0625 | 4 | import sqlite3
from Students import Students
def SelectAllFunction(cursor):
cursor.execute("SELECT * FROM Students")
all_rows = cursor.fetchall()
print(all_rows)
def SelectMajor(cursor, user_major):
cursor.execute("SELECT * FROM Students WHERE Major = ?", (user_major,))
all_rows = cursor.fetchall... |
2c39ed3bf73a4c5728a039b11f6d782129941be3 | DegtyarBo/Portfolio | /calculator(ASCII)/calculator(ASCII).py | 3,946 | 3.796875 | 4 | first_value = input('Enter the first value: ')
second_value = input('Enter the second value: ')
operation = input('Operation: ')
# Первое Значение
if len(first_value) == 1:
n1 = (ord(first_value[0])-48) * 1
n0 = n1
if len(first_value) == 2:
n1 = (ord(first_value[0])-48) * 10
n2 = (ord(first_value[1])-48) * 1
n... |
bcb8b80ca2f312ce7b3158ab9712260a902cd6c6 | Novi0106/IronAndre | /Week 7/GNOD/.ipynb_checkpoints/GNOD_Functions-checkpoint.py | 5,666 | 3.546875 | 4 | #!/usr/bin/env python
# coding: utf-8
# %%
def billboard_scraper():
#import libraries
import requests
from bs4 import BeautifulSoup
import pandas as pd
from tqdm.notebook import tqdm
#set parameters
url = "https://www.billboard.com/charts/hot-100"
response = requests.get(url)
r... |
4674bc6ed28801e9264776de99b83af367aa9e01 | tkakar/DataPrep | /Python Codes for Projects/Python Minor Coding Tasks/miscellaneous.py | 1,634 | 3.765625 | 4 | ####### print frizzbuzz question
for i in range(1,101):
if i%3==0 and i%5==0:
print (i, "frizzBuzz")
elif i%3==0:
print (i, "Buzz")
elif i%5==0:
print (i, "frizz")
else: print (i)
### return indices of two numbers whose sum add to a target number
nums = [1, 2, 7, 11, 15, 19];... |
44fde5a47ac4b018cd39bd3a83b80d8f5612d9d3 | afcummings/python-challenge | /pypoll/main.py/main.py/pypoll.py | 1,614 | 3.5 | 4 | import csv
candidates = []
total_votes = []
num_votes = 0
with open('election_data.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
column = next(csvreader,None)
for column in csvreader:
num_votes = num_votes + 1
candidate = column[2]
if candidate in candida... |
fb0055af02a4823c00e6baeaa1c44c3089dacd4a | hovell722/eng-54-python-practice-exercises | /exercise_102.py | 610 | 4.3125 | 4 | # # Create a little program that ask the user for the following details:
# - Name
# - height
# - favourite color
# - a secrete number
# Capture these inputs
# Print a tailored welcome message to the user
# print other details gathered, except the secret of course
# hint, think about casting your data type.
name ... |
d2d41bc519f79737818c852306c97b988e89ace7 | hovell722/eng-54-python-practice-exercises | /exercise_107.py | 1,370 | 4.46875 | 4 | # SIMPLEST - Restaurant Waiter Helper
# User Stories
#1
# AS a User I want to be able to see the menu in a formated way, so that I can order my meal.
#2
# AS a User I want to be able to order 3 times, and have my responses added to a list so they aren't forgotten
#3
# As a user, I want to have my order read back to ... |
7c6ffcf1b39e3bdb6f8e581113d9e5b3650e680b | iaq2/Apriori | /Apriori.py | 648 | 3.8125 | 4 |
import pandas as pd
from itertools import combinations
excel_file = "dba_1.xlsx"
database = pd.read_excel(excel_file, header=None)
#print(database)
#min_support = input('Enter Minimum Support Value')
#Gets all unique items
unique_items = set()
for i, entry in database.iterrows():
for item in entry:
... |
e010f17673b3fd82118f26a92283d0f4639f48af | longjiazhen/Python | /MergeSort.py | 1,998 | 3.890625 | 4 | import random
# 递归求列表中最大值
# def getMax(list, L, R):
# if L == R: # base case,停止递归的地方
# return list[L]
# mid = int((L+R)/2) # 如果要防溢出,可以写成 L + ((R-L)/2)
# maxLeft = getMax(list, L, mid)
# maxRight = getMax(list, mid+1, R)
# return max(maxLeft, maxRight)
#
#
# list = [3, 5, 7, 1, 0 ]
# maxIt... |
12bfab7e083f2b0326e72ec60cd53c42be2dd280 | monicajoa/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | 425 | 4.15625 | 4 | #!/usr/bin/python3
"""This module holds a function
From JSON string to Object
"""
import json
def from_json_string(my_str):
"""function that returns an object (Python data structure)
represented by a JSON string
Arguments:
my_str {[str]} -- string to convert to object
Returns:
... |
eb8ac907b35bacba795aae007f4d3adb03a77e23 | monicajoa/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 703 | 4.5 | 4 | #!/usr/bin/python3
"""
This module hold a function that prints a square with the character #.
"""
def print_square(size):
"""
This function prints square by the size
Paramethers:
size: length of the square
Errors:
TypeError: size must be an integer
ValueError: size must be >= 0... |
321d3dffc80229b6788fd004f0baade38341a580 | monicajoa/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 333 | 4 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
if matrix == [[]]:
print("")
else:
for x in matrix:
for j in range(0, len(x)):
if j < len(x) - 1:
print("{:d}".format(x[j]), end=" ")
else:
print("{:d}".f... |
05280ad60cef6f657051257bf420db4722a1ee48 | sakshipadwal/python- | /Python/pyrmaid1.py | 167 | 3.796875 | 4 | def pattern(n):
k= 2 * n-2
for i in range (0, n):
for j in range (0, i + 1):
print("*", end=" ")
print("\r")
pattern(5) |
63dac65210c83675bf6c7b07e055231e7434a8ec | enkefalos/PythonCourse | /hw1_question3.py | 1,184 | 4.28125 | 4 | def compare_subjects_within_student(subj1_all_students :dict,
subj2_all_students :dict):
"""
Compare the two subjects with their students and print out the "preferred"
subject for each student. Single-subject students shouldn't be printed.
Choice for the data structu... |
21d86ad1c6ebf2a3e65014f59a79202004f2bbb8 | hanshiqiang365/turtle_demo | /turtle_sakuragray.py | 1,032 | 3.515625 | 4 | #author: hanshiqiang365 (微信公众号:韩思工作室)
from turtle import *
from random import *
from math import *
import pygame
import time
def tree(n, l):
pd()
t = cos(radians(heading() + 45)) / 8 + 0.25
pencolor(t, t, t)
pensize(n)
forward(l)
if n > 0:
b = random() * 15 + 10
c = random() * ... |
ad657663dfafaf32f7865234f01722a59b9983bc | absheth/elem_of_AI | /game_of_chance/yahtzee.py | 1,951 | 3.59375 | 4 | # Akash Sheth, 2017 || Game of Chance
# Ref[1]: https://stackoverflow.com/questions/2213923/python-removing-duplicates-from-a-list-of-lists
# Ref[2]: https://stackoverflow.com/questions/10272898/multiple-if-conditions-in-a-python-list-comprehension
# Ref[3]: https://stackoverflow.com/questions/25010167/e731-do-... |
f84afd95a94c6b3fc8c33c6bcd890819558d028b | tyteotin/codewars | /6_kyu/shorten_number.py | 1,759 | 4.09375 | 4 | """
Ok, here is a new one that they asked me to do with an interview/production setting in mind.
You might know and possibly even Angular.js; among other things, it lets you create your own filters that work as functions you put in your pages to do something specific to her kind of data, like shortening it to display ... |
14f7a544807a575b1ee39c99bfbdad6c7efd90b1 | tyteotin/codewars | /6_kyu/is_triangle_number.py | 1,168 | 4.15625 | 4 | """
Description:
Description:
A triangle number is a number where n objects form an equilateral triangle (it's a bit hard to explain). For example,
6 is a triangle number because you can arrange 6 objects into an equilateral triangle:
1
2 3
4 5 6
8 is not a triangle number because 8 objects do not form an equila... |
7d25f5294b8795457921e6a1f72c7bd10b3c3a07 | Daizt/Python-Learning-Notes | /dynamic_programing/Shortest Common Subsequence.py | 598 | 3.78125 | 4 | # Shortest Common Subsequence
# 最短公共父列
# SCS[i,j] denotes the length of SCS of a[0:i] and b[0:j]
def SCS(a,b):
m,n = len(a),len(b)
scs = [[0 for _ in range(n+1)] for _ in range(m+1)]
scs[0] = list(range(n+1))
for i in range(m+1):
scs[i][0] = i
for i in range(1,m+1):
for j in range(1,n+1):
if a[i-1] == b... |
c09107e56d1e89be10428f08e5395588fdd40d23 | Daizt/Python-Learning-Notes | /dynamic_programing/Travelling Salesman Problem.py | 799 | 3.59375 | 4 | # Travelling Salesman Problem
# Using DP: C(S,i) denotes the cost of minimum cost path visiting each vertex in
# set S exactly once, starting at 0 ending at i(Note that i belongs to S). Thus the
# anwer to our problem is C(S,0), where S contains all the given cities.
def shortestPathDP(pos):
pos = [0,0] + pos
N = ... |
727cc50b1e1907d34daa0cb0b8e4eb7c9af0fb87 | 3point14thon/bill_analyzer | /src/html_cscale.py | 1,384 | 3.515625 | 4 | def mk_color_span(vals, txts, lower_bound=0, upper_bound=1):
'''
Generates a string of html spans whos background colors
corospond to the values in vals. Larger numbers have a
greener color smaller have a redder.
Inputs:
vals (iterable of floats): Values to be used in generating
the... |
2dc9ad367da6489f01198d757997b1d154747f0c | Hersh500/Dynamic-Programming-Practice | /edit_distance.py | 1,293 | 3.90625 | 4 | ''' Edit Distance Problem: Given two strings of size m, n and set of operations replace (R), insert (I) and delete (D) all at equal cost.
Find minimum number of edits (operations) required to convert one string into another.'''
def print_matrix(matrix): #prints all rows in a two dimensional array
for row in matrix... |
24ff0eaf61ebecc102e3769515330bb14c3f007d | genesysrm/Python_DataScience | /calculadorafiesta.py | 1,031 | 3.6875 | 4 | class Festa:
def _init_(self, c,s,d):
self.comida = c
self.suco = s
self.deco = d
def comida(self, qua):
c = 25 * qua
return c
def suco(self, qua, saudavel):
if(saudavel):
s = (5 * qua)
#suco = suco - (suco*0.05)
else:
s = ... |
2b39a42620f4699c51c7d2679b042cd55dc6e1d3 | genesysrm/Python_DataScience | /medianotas.py | 478 | 3.609375 | 4 | notas = [5,5,6,6,7,7,8,8,9,9]
print( sum(notas) / float(len(notas)) )
notas= {"tati":[5,9,9], "luiz":[5,4,3],"paula":[6,6,6],"genesys":[6,8,9],"mutu":[7,7,7] }
def media(notas):
soma = 0
for n in notas:
soma = soma + n
return (soma / len(nota)
/////////////////////////////////////////
soma=0
for... |
d60efd85d0348706c2262820706a4234a775df1a | Sairahul-19/CSD-Excercise01 | /04_is_rotating_prime.py | 1,148 | 4.28125 | 4 | import unittest
question_04 = """
Rotating primes
Given an integer n, return whether every rotation of n is prime.
Example 1:
Input:
n = 199
Output:
True
Explanation:
199 is prime, 919 is prime, and 991 is prime.
Example 2:
Input:
n = 19
Output:
False
Explanation:
Although 19 is prime, 91 is not.
"""
# Implement t... |
2d3f726b72caa4fb12fdd762e24577c5ca2b805d | AiramL/Comp-II-2018.1 | /aula01/Exercicio03.py | 754 | 3.84375 | 4 | from Exercicio01 import montarGradeCurricular
from Exercicio02 import inserirDisciplina
def ler_csv(arquivo):
grade = []
for linha in arquivo:
lista = linha.split(',')
codigo = lista[0]
nome = lista[1]
numRequisitos = lista[2]
requisitos = []
if nu... |
67cf5bd31636ab5f273983e058e620c3b995cb94 | Cegard/Exercises | /Python/fibonacci.py | 1,227 | 4.03125 | 4 | #!/usr/bin/env python
__author__ = "Cegard"
def fibo(n):
"""función iterativa de los n primeros
números de la serie Fibonacci"""
lst = []
a = 0
b = 1
counter = 0
while counter < n:
lst.append(b)
a,b = b,a+b
counter += 1
return lst
def fibo_r(n):
"... |
24052748fcbb908a8072d7338c7f0f8c452144ca | arvin1209/python | /basic_google_siri.py | 293 | 3.796875 | 4 | #This should reply hello or 1 depending on what you type
c=str(input("Type something to Pybuddy in quote marks"))
b="hello"
d="what is one times one"
e="what is 1*1"
f="what is 1 times 1"
g="what is one*one"
if c == b:
print("Hello to you too")
if c==d or e or f or g:
print("1")
|
ded4c7f00ce98b8dfcd5a16a0838cffd854c5a83 | MFori/partions_generator | /set.py | 3,179 | 3.75 | 4 | # Set partitions generator
# Author: Martin Forejt
# Version: 1.0
# Email: forejt.martin97@gmail.com
import sys
import random
# generate all partitions for given N
MODE_ALL = 1
# generate one random partition for given N
MODE_RANDOM = 2
# generate the next partition for given current partition
MODE_NEXT = 3
SUPPORTE... |
f07f8e409d49a168b31dc24f0864eeeabb751b43 | nduprincekc/animation | /Animation.py | 254 | 3.75 | 4 | import turtle
turtle.bgcolor('lightpink')
turtle.pensize(12)
turtle.speed(0.2)
color = ['red','yellow','blue','orange']
for a in range(9):
for i in color:
turtle.color(i)
turtle.circle(50)
turtle.left(10)
turtle.mainloop()
|
9a5edf7340e74a986b4b3955386dd417524eb105 | q13245632/CodeWars | /Moving Zeros To The End.py | 393 | 3.96875 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-09
def move_zeros(array):
zeros = []
lst = []
for i in array:
if (type(i) == int or type(i) == float) and int(i) == 0:
zeros.append(0)
else:
lst.append(i)
lst.extend(zeros)
return lst
def move_zeros(ar... |
71b1332c26e6f3c998ff0bfa825bacf38b10e2bf | q13245632/CodeWars | /Double Cola.py | 407 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-20
def whoIsNext(names, r):
n = len(names)
if r < n:
return names[r - 1]
i = 0
f = n * (2 ** i)
r -= f
while r > 0:
i += 1
f = n * (2 ** i)
r -= f
r += (n * (2 ** i))
return names[(r / (2 ** i))]
... |
d5003983716fb6640b9b34eed0f8ad1fee260967 | q13245632/CodeWars | /Booleanlogic.py | 918 | 3.59375 | 4 | # -*-coding:utf8-*-
# 自己的解法
def func_or(a,b):
if a:
return True
else:
if b:
return True
return False
def func_xor(a,b):
if a:
if not b:
return True
else:
if b:
return True
return False
# Test.describe("Basic tests")
# Test.ass... |
35276bd8d0bde54d510607b3bddc516175edabdd | q13245632/CodeWars | /Characterwithlongestrepetition.py | 1,002 | 3.859375 | 4 | # -*-coding:utf8 -*-
# 自己的解法
def longest_repetition(chars):
if chars is None or len(chars) == 0:
return ("",0)
pattern = chars[0]
char = ""
c_max = 0
count = 1
for s in xrange(1,len(chars)):
print chars[s]
if chars[s] == pattern:
count += 1
else:
... |
e8f3a4b8488bc263cf35d953261b0faf8fb4669a | q13245632/CodeWars | /Directions Reduction.py | 1,709 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-14
def dirReduc(arr):
lst = []
for i in arr:
if len(lst) <= 0:
lst.append(i)
continue
if i == 'NORTH':
if lst[-1:][0] == 'SOUTH':
lst.pop()
else:
lst.append(i... |
cec3d32d73c63985e62eb3bd2a7f32a38f074037 | q13245632/CodeWars | /First non-repeating letter.py | 1,548 | 3.84375 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-27
from collections import Counter
def first_non_repeating_letter(string):
string_copy = string.lower()
counter = Counter(string_copy)
index = len(string)
ch = ""
for k,v in counter.items():
if v == 1 and string_copy.index(k) < index:
... |
29f08f68b75f30dc980f8529d1ab5ee555787747 | q13245632/CodeWars | /Formattothe2nd.py | 723 | 3.90625 | 4 | # -*-coding:utf8-*-
# 自己的解法
def print_nums(*args):
max_len = 0
if len(args) <= 0:
return ''
else:
for i in args:
if max_len < len(str(i)):
max_len = len(str(i))
string = '{:0>' + str(max_len) + '}'
return "\n".join([string.format(str(i)) for i in a... |
b9b8c049ca9962375210716f57ecfdd7b9af6472 | q13245632/CodeWars | /WhatTheBiggestSearchKeys.py | 1,909 | 3.765625 | 4 | # -*-coding:utf8 -*-
# author: yushan
# date: 2017-02-26
# 自己的解法
def the_biggest_search_keys(*args):
if len(args) == 0:
return "''"
lst = []
maxlen = 0
for i in args:
if len(i) == maxlen:
lst.append("'"+i+"'")
elif len(i) > maxlen:
maxlen = len(i)
... |
c2db75efb101720de872fbd9d22b16b7fa4e0af4 | q13245632/CodeWars | /Permutations.py | 326 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# author: yushan
# date: 2017-03-23
import itertools
def permutations(string):
lst = itertools.permutations(string)
lst = list(set(["".join(i) for i in lst]))
return lst
import itertools
def permutations(string):
return list("".join(p) for p in set(itertools.permutations(str... |
b382a3fab0bf42f3309b54065556330e3054b3d7 | huajh/python_start | /image_denoising/anisotropic_diff.py | 3,178 | 3.515625 | 4 | import numpy as np
import warnings
from matplotlib import pyplot as plt
def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.), option=1):
"""
Anisotropic diffusion.
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter ... |
a02d06dd30aef52d2d19d7d3f6c1dbbf20b112fa | ogsf/Python-Exercises | /Python Exercises/src/Ch3_Examples.py | 1,243 | 4.03125 | 4 | '''
Created on May 25, 2013
@author: Kevin
'''
filler = ("String", "filled", "by", "a tuple")
print "A %s %s %s %s" % filler
a = ("first", "second", "third")
print "The first element of the tuple is %s" % (a[0])
print "The second element of the tuple is %s" % (a[1])
print "The third element of the tuple is... |
3e93376c30710a336310de2da0d89be71e1f782b | freerangehen/AoC2019 | /day4.py | 668 | 3.859375 | 4 |
def is_valid(number):
number = str(number)
prev_digit = None
have_double = False
for each_digit in number:
if prev_digit:
if each_digit == prev_digit:
have_double = True
if each_digit < prev_digit:
return False
else:
... |
dd60ca87e05fa1755e80fd0a1711a97bb84c0767 | Guilherme-Artigas/Python-intermediario | /Aula 15.5 - Exercício 70 - Estatísticas em produtos/ex070_.py | 1,132 | 3.625 | 4 | from time import sleep
controle = True
total = Produto = menor_preco = 0
print('*-' * 13)
print(' * LOJA SUPER BARATEZA * ')
print('*-' * 13)
print()
while controle == True:
nome = str(input('Nome do Produto: '))
preco = float(input('Preço: R$ '))
total += preco
if preco > 1000:
Produto +=... |
a720bebe341646da8e5d7c76f21a25bb617a5a22 | Guilherme-Artigas/Python-intermediario | /Aula 14.1 - Exercício 57 - Validação de Dados/ex057_.py | 675 | 3.859375 | 4 | """
Minha solução...
r = 's'
while r == 's':
sexo = str(input('Sexo [M/F]: ')).strip().upper()[0]
if (sexo == 'M'):
r = 'n'
print('Dado registrado com sucesso, SEXO: M (Masculino)')
elif (sexo == 'F'):
r = 'n'
print('Dado registrado com sucesso, SEXO: F (Feminino)')
else... |
aef6e912e8e89b1edaeb56492c51ca1a2d52dda7 | Guilherme-Artigas/Python-intermediario | /Aula 13.9 - Exercício 54 - Grupo da Maioridade/ex054_.py | 237 | 3.640625 | 4 | q = 0
for c in range(1, 8):
anoN = int(input('Digite o ano de nascicmento da {}º pessoa: '.format(c)))
idade = 2020 - anoN
if (idade < 21):
q += 1
print('Quantidade de pessoas menores de idade:{} pessoas'.format(q))
|
ac9ed5d3670dc1612bd3f0bf6a8e7e28146739c1 | Guilherme-Artigas/Python-intermediario | /Aula 12.4 - Exercício 39 - Alistamento Militar/ex039_.py | 1,589 | 4.09375 | 4 | from datetime import date
ano_atual = date.today().year
sexo = str(input('Digite seu Sexo [Homem / mulher]: '))
if (sexo == 'Homem') or (sexo == 'homem') or (sexo == 'H') or (sexo == 'h'):
ano_N = int(input('Digite o ano do seu nascimento: '))
idade = ano_atual - ano_N
print()
print('Quem nasceu e... |
cc7a4308797597975dcf0029e34c707aabdfda38 | Guilherme-Artigas/Python-intermediario | /Aula 13.5 - Exercício 50 - Soma dos pares/ex050_.py | 173 | 3.875 | 4 | somaP = 0
for c in range(1, 6):
n = int(input('Digite um valor: '))
if (n % 2 == 0):
somaP += n
print('Soma dos valores pares digitados = {}'.format(somaP))
|
5d499ce12bdb550033ce907c61bbd5c44debbbb7 | gmastorg/CTI110 | /M2T1_SalesPrediction_Canjura.py | 217 | 3.6875 | 4 | #CTI 110
#M2T1 - Sales Prediction
#Gabriela Canjura
#08/30/2017
#calculate profit margin
totalSales= int(input('Enter total sales: '))
annualProfit = float(totalSales*.23)
print ('Annual sales = ',annualProfit,'.')
|
2044a3f44b9af55830532e836ddd2505dd5346b3 | gmastorg/CTI110 | /M6T2_FeetToInchesConverter_Canjura.py | 500 | 4.25 | 4 | #Gabriela Canjura
#CTI110
#10/30/2017
#M6T2: feet to inches converter
def main():
#calls a funtions that converts feet to inches and prints answer
feet = float(0)
inches = float(0)
feet = float(input("Enter a distance in feet: "))
print('\t')
inches = feet_to_inches(f... |
1098b2cb56836f9ef77cb4a563a62b5bc02d432e | hypatiad/codefigthtstests | /checkPalindrome.py | 494 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Given the string, check if it is a palindrome.
For inputString = "ana", the output should be
checkPalindrome(inputString) = true;
For inputString = "tata", the output should be
checkPalindrome(inputString) = false;
For inputString = "a", the output should be
checkPalindrome(inputString) = t... |
7d2b7c33e756b60003d97b54bb495aebb2c8cf31 | bitf14m513/schedulingalgo | /Preorityscheduling.py | 4,349 | 4 | 4 | print("------------------------Priority Scheduling Non Preempting-------------------")
t_count = int(input("Enter Total Number of Process : -> "))
jobs = []
def take_input():
for process in range(0, t_count):
at = 0
bt = 0
job_attr = {"process_name": "None", "AT": 0, "BT": 0, "ST"... |
7b549d7fad13846b90a4f439379c9dbfa7017207 | alimovAN19/1-3-9Test | /1-3-9NameGame.py | 1,493 | 3.890625 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
'''Alter the code to produce a different output if your name is entered. As always, start a log file
test your code. When it works, upload the code without changing the file name. Upload the log file to
the classroom alonf with your code'''
def w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.