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 |
|---|---|---|---|---|---|---|
350d07f154c8892b7bba29caabdfd3e131cd18b9 | bs4/LearnPythontheHardWay | /ex15drill3.py | 567 | 4.03125 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
finally:
txt.close()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
finally:
txt.close()
# The two halves of the... |
f704e650212e38ef27a82208b9b65faccc5b60fe | bs4/LearnPythontheHardWay | /ex08.py | 969 | 4 | 4 | formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sin... |
8ba142c74997a10c79bf39bcfca62307c8f3eb89 | bs4/LearnPythontheHardWay | /ex32drill.py | 2,263 | 4.625 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits:
print "A fruit of type %s" % ... |
5958d7e44c80a44c98a28c64c9451631525f27c5 | bs4/LearnPythontheHardWay | /ex06drill.py | 2,124 | 4.125 | 4 | # The below line gives a value for variable x, the value is a string that has a formatter in it
x = "There are %d types of people." % 10
# The below line gives a value for the variable "binary", I think doing this is a joke of sorts
binary = "binary"
# The below line gives a value for the variable "do_not", the value i... |
ada0873f48aba1239e05d845c2bb457cda744af4 | bs4/LearnPythontheHardWay | /ex18drill.py | 1,643 | 4.5 | 4 | # this one is like your scripts with argv. The below line has a *, it tells python to take all arguments to the function and put them in args as a list
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_tw... |
2e8e243cd4555828ae12e133f5b536c5a2026e37 | Shavezz/Python-Tech-Degree-Project3-Phrase-Hunters | /phrasehunter/character.py | 435 | 3.625 | 4 | class Character:
def __init__(self, char1):
self.original_char = char1
was_guessed_character = False
def update(self, guess):
if guess == original_char:
was_guessed_character == True
def show_character():
if was_guessed_character == True and len(origin... |
62695a4cea77bb70269f043be685d83d177c5d9b | Jongy/knesset-committees-data | /utils.py | 215 | 3.546875 | 4 | from typing import List
def to_words(text: str) -> List[str]:
if text == "":
return []
filtered = filter(lambda w: w != "-", text.split(' '))
return list(map(lambda w: w.strip('.'), filtered))
|
cd90267f4ff6c80a760a295e7087a4658b85fe70 | Chloe0112/0307 | /hw1220.py | 197 | 3.703125 | 4 | import turtle
turtle.pensize(2)
turtle.pencolor("red")
for i in range(12):
turtle.circle(120,30)
turtle.right(30)
turtle.pencolor('yellow')
turtle.forward(80)
turtle.mainloop()
|
719905bb7025deda97885e91a1eabbd3692a2464 | alexander-held/advent-of-code-2020 | /01/puzzle.py | 839 | 3.59375 | 4 | def read_input(fname):
with open(fname) as f:
lines = f.readlines()
x = [int(l) for l in lines]
return x
def sum_to_2020(x):
for val in x:
val_needed = 2020-val
if val_needed in x:
print(f"{val}, {val_needed}")
return [val, val_needed]
def three_to_2020(... |
c42e33e7a3dcf9177b430bfe57a674f9fc23198d | lluidesia/liuda-checkio | /Elementary/3-even-last.py | 715 | 4.09375 | 4 | #https://checkio.org/mission/even-last
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
l=0
for i in array:
l=i
print('ar:',array)
print("l:",l)
s=0
for item in array[0::2]:
print('i:',item)
s=s+item
... |
ff1fbf5b4af569540c6faecedb863ee8e772eff4 | tanman13/oopljpl | /examples/Assignment.py | 4,015 | 4.15625 | 4 | #!/usr/bin/env python3
# -------------
# Assignment.py
# -------------
print("Assignment.py")
#i, j = 2 # TypeError: 'int' object is not iterable
#i, j = 2, 3, 4 # ValueError: too many values to unpack
i, j = 2, 3
assert i == 2
assert j == 3
#i, j = "a" # ValueError: need more than 1 value... |
4661186354d15a8fe621f1939d5028ce5851013f | tanman13/oopljpl | /myExercises/count_01.py | 748 | 3.8125 | 4 | #!/usr/bin/env python3
# --------
# Count.py
# --------
from unittest import main, TestCase
class count () :
def __init__(self, i, j=1):
self.i = i
self.j = j
def __iter__(self):
return self
def __next__(self):
v = self.i
self.i = v + self.j
... |
c81d8560221b75cc2065733daff70f50c5709835 | tanman13/oopljpl | /exercises/StDev2.py | 2,844 | 3.796875 | 4 | #!/usr/bin/env python3
# ---------
# StDev2.py
# ---------
# https://docs.python.org/3/library/statistics.html
from functools import reduce
from math import sqrt
from statistics import mean, stdev, StatisticsError
from unittest import TestCase, TestLoader, TestSuite, TextTestRunner
def stdev_f... |
605b5978373f0cf9879473d49fec8d2d2b61e96c | kavinandha/kavipriya | /prg24.py | 164 | 3.6875 | 4 | def sortir(arr,m):
for i in range(m):
arr[i]=i+1
if __name__=="__main__";
arr=[10,7,9,2,3,5,4,6,1]
m=len(arr)
sortit(arr,m)
for i in range(m):
print(arr[i],end="")
|
83cf84a173ac21a7801299887f5dc1b22cbb6b7e | kavinandha/kavipriya | /prg3.py | 274 | 4.28125 | 4 | ch = input("please enter your own character:")
if(ch =='a' or ch =='e' or ch =='i' or ch =='o' or ch =='u' or ch =='A' or ch =='E' or ch =='I' or ch =='O' or ch =='U'):
print("the given character",ch,"is a vowel")
else:
print("the given character",ch,"is a consonant")
|
260e79ab29f5671b8ee2ad1d01ad2e4d37fa046c | kavinandha/kavipriya | /prg82.py | 227 | 4.03125 | 4 | n=int(input("enter the number:"))
m=int(input("enter the number:"))
print("\noriginal number:",x)
print("formatted number with sign: "+"{:+.2f}".x);
print("original number:",y)
print("formatted number with sign:"+"{:+.2f}".y);
|
84c2d1028c0db58267aad55116bbfd85e2ad7239 | kavinandha/kavipriya | /prg108.py | 133 | 3.84375 | 4 | def large(arr,m):
arr.sort(reverse=true)
for i in range(m):
print(arr[i],end="")
arr=[1,23,12,9,30,2,50]
n=len(arr)
m=3
large(arr,m)
|
db29a3b868bc28c32029e8d0d305c296093b7bf9 | kavinandha/kavipriya | /prg90.py | 199 | 3.9375 | 4 | import re
def extract(input):
numbers = re.findall('\d+',input)
numbers = map(int,numbers)
print max(numbers)
if __name__==" __main__":
alpha=input("enter the alpha numeric:")
extract(alpha)
|
d4dfa71ac260d35c46305fa9924f51d3c88a2ea0 | kavinandha/kavipriya | /prg95.py | 163 | 3.796875 | 4 | principal=int(input("enter the number:"))
time=int(input("enter the number:"))
rate=int(input("enter the number:"))
simple=(principle*time*rate)/100
print(simple)
|
3ab146267536a5109e17fffe7d6d9e34de5f85f9 | kavinandha/kavipriya | /prg25.py | 170 | 3.9375 | 4 | num=[1,2,3,4,5,]
m=len(num)
num.sort()
if m%2==0:
median1=num[m//2]
median2=num[m//2-1]
median=(median1+median2)/2
else:
median=num[m//2]
print("median is:"+str(median))
|
66ee2995cfee404b46fe0e5e6bc838bb85a4e181 | Asmita-Malakar/PythonProjects | /Lab10P3.py | 424 | 3.578125 | 4 | # Asmita Malakar
# 07/04/2021
# Lab 10 Problem 3: Writing text file
def main():
water = open("water.txt", "w+")
for i in range(4):
water.write(input("Enter account number: "))
water.write(" ")
water.write(input("Enter R for residential, B for business: "))
water.write(" ")
... |
94c876fad09895149ee125ff06a3155826543809 | Asmita-Malakar/PythonProjects | /Lab04P1.py | 903 | 3.921875 | 4 | #Asmita Malakar
#June 5, 2021
#Lab 4 Problem 1: Implementing the while function
# plasma level input
plasma_level = int(input("Enter fasting plasma glucose level: "))
if plasma_level > 125:
print("The patient has diabetes")
# detecting whether patient has diabetes
elif 100 < plasma_level <= 125:
print("The pa... |
c58d0ff46c571486de6babc8c9e39a0d31c83032 | Asmita-Malakar/PythonProjects | /manage_course/course.py | 635 | 3.8125 | 4 | #Asmita Malakar
#7/11/2021
#Course Management Project
class Course:
def __init__(self, course_code, max_size):
self.course_name = course_code
self.size = int(max_size)
self.enrollment = 0.0
def add_student(self):
if self.enrollment >= self.size:
print("Course alrea... |
092d63c73875ba78ae098b8dbc5e0b2324bd3f3c | Asmita-Malakar/PythonProjects | /Lab09P2.py | 1,065 | 3.75 | 4 | #Asmita Malakar
#06/30/2021
#Lab 9 Problem 2: Comparing two lists
import random
list1 = []
for i in range(4):
num = random.randint(1, 10)
list1.append(num)
list2 = []
print("You are asked to pick 4 unique numbers in the range of 1 to 10.")
for i in range(4):
number_input = int(input("Enter a number: "... |
653175fc97f8be20c35f53278d952eb444051678 | Asmita-Malakar/PythonProjects | /Lab07P1.py | 369 | 3.78125 | 4 | #Asmita Malakar
#6/23/2021
#Lab 7 Problem 1: Kilowatts used cost
kHW = 0
def main():
kWH = int(input("Enter kilowatt hours used: "))
bill_calculator(kWH)
def bill_calculator(kWH):
if int(kWH) <= 500:
print(f"Please pay this amount:{round(kWH * 0.12,2)}")
else:
print(f"Please pay thi... |
8b49cc48f2a596343611c26b71116b8d67b5abf7 | Asmita-Malakar/PythonProjects | /Lab13P02/Water_bill.py | 670 | 3.828125 | 4 | class Water_bill:
def __init__(self,name, address):
self.name = name
self.address = address
self.total = 0
self.gallons = (0)
def calculate_charge(self):
self.gallons = input("How many gallons of water were used? ")
if self.gallons <= str(6000):
self.... |
a1cc58d56b49198446ce3d05aaa14577b4854660 | Asmita-Malakar/PythonProjects | /Lab05P06.py | 448 | 3.53125 | 4 | #Asmita Malakar
# 6/30/2021
#Top score function
import random
top_scores = []
all_scores = []
for i in range(50):
rand_num = random.randint(0,100)
all_scores.append(rand_num)
if len(top_scores) < 5:
top_scores.append(rand_num)
elif len(top_scores) == 5:
if rand_num > min(top_score... |
f30c80da1a3ca8b3c3b34359cc1f7ecb6f0004bc | alinabalgradean/algos | /insertion_sort.py | 413 | 4.25 | 4 | def InsertionSort(lst):
"""Basic Insertion sort.
Args:
lst [list]: The list to be sorted.
Returns:
lst [list]: Sorted list.
"""
for index in range(1, len(lst)):
position = index
temp_value = array[lst]
while position > 0 and lst[position - 1] > temp_value:
lst[position]... |
8dd255cbd492106fcfde67c9221698df5a85045f | andrewlidong/PythonSyntax | /Top18Questions/11_determineValidNum.py | 2,176 | 4.125 | 4 | '''
11. Determine if the number is valid
Given an input string, determine if it makes a valid number or not. For simplicity, assume that white spaces are not present in the input.
4.325 is a valid number.
1.1.1 is NOT a valid number.
222 is a valid number.
is NOT a valid number.
0.1 is a valid number.
22.22. is N... |
fd8ea6ece01e686a8beef54bc5af3b8dfab593bf | andrewlidong/PythonSyntax | /Top18Questions/3_sumOfTwoValues.py | 1,277 | 4.21875 | 4 | '''
3. Sum of two values
Given an array of integers and a value, determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists and return false if it does not.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return... |
384b1ef0a787f8b5c8c89926f07106180ba2c81e | andrewlidong/PythonSyntax | /Top18Questions/7_checkTwoBinaryTreesIdentical.py | 1,582 | 4.03125 | 4 | '''
7. Check if two binary trees are identical
Given the roots of two binary trees, determine if these trees are identical or not. Identical trees have the same layout and data at each node.
Example
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Inpu... |
44d90410859321ed401bc635ba5249b61b801c8a | Itsdcz1/wheretogohideandseek | /app2.py | 292 | 3.65625 | 4 | from time import sleep
import random
print("1 end of area")
print("2 start of area")
print("3 middle of area")
print("4 random place")
print("5 everywere")
n = input("Go? (y/n): ")
if n == "y":
sleep(0.8)
print(random.randint(1, 5))
if n == "n":
print("Ok.")
|
bbcc866382ac2ab1642b31334ee7b53b0d85bac7 | mariajosegaete/Python_Projects | /Property_scraper/menu.py | 1,020 | 4.15625 | 4 | from app import houses
USER_CHOICE = '''
Please enter one of the following:
- 'b' to view all houses
- 'n' to view next book in catalogue
- 'c' to view 10 cheapest houses
- 'q' to quit
---->
'''
def print_houses():
'''house_prices = sorted(books, key=lambda x: (x.rating * -1, x.price))[:10]'''
for house i... |
a178973105a6944d58a870857779b8796f476656 | xilara/Language-Structure | /prg4/pyPrg4.py | 1,663 | 3.96875 | 4 | # Xiana Lara
# September 28, 2020
# Programming 4: Comparing interpreted and compiled codes
# Original Sources
# https://rosettacode.org/wiki/Gaussian_elimination#Python
# Current Purpose:
# Comparing interpreted and compiled languages by measuring
# the time it takes to run the programs with different data sizes
# ... |
c66d3c7dc9a86483bb07705fa052479176e35b8b | qorud02/changwonai | /for_test.py | 99 | 3.515625 | 4 | for i in (1,2,3,4,5,6) :
pass
print(i)
for i in range(5) :
print(i)
print(type(range(5))) |
b2b683c42418dcc782890da0463a05986d643f1f | sameerarora/python-workshop | /src/main/python/lists/merge_intervals.py | 464 | 3.5 | 4 | def merge(intervals):
result = [intervals[0]]
counter = 1
res_idx = 0
while counter < len(intervals):
left, right = result[res_idx], intervals[counter]
if left[1] >= right[0]:
result[res_idx] = (left[0], max(left[1], right[1]))
else:
result.append(right)
... |
515e5a0375664533d6fa8ffcd4753e830c2625d3 | sameerarora/python-workshop | /src/main/python/iterables_generators/generator_ex.py | 628 | 3.890625 | 4 | def fibonacci(lower_bound, upper_bound):
prev, curr = 0, 1
while prev + curr < upper_bound:
prev, curr = curr, prev + curr
if prev + curr >= lower_bound:
yield prev + curr
f_generator = fibonacci(20, 1000)
# for i in f_generator:
# print(i)
from math import sqrt
# 1, 3, 5 ,... |
f78aff7635d64d052eead1bfed1f12337633a546 | sameerarora/python-workshop | /src/unittest/python/hello/read_file_tests.py | 225 | 3.640625 | 4 | from unittest import TestCase
from hello.regex_assignment import pluralize
class Test(TestCase):
def test_pluralize(self):
assert pluralize('anomaly') == 'anomalies'
assert pluralize('test') == 'tests'
|
6638ba55943fa25090cd0d8e0e0ddeeaf2e65cfd | tobiolatunji/HackerRank | /isBalanced.py | 835 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 5 18:56:30 2018
@author: 1Air
"""
class Node(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def isBalanced(root):
l = treeHeight(root.left)
r = treeHeight(root.ri... |
c10d21c763a0ec3f8f9634c7d6e717dc9bbfbd74 | xuan11235813/combinatorial | /Blatt 1/graph.py | 7,381 | 3.609375 | 4 | import time
import math
class Graph:
def __init__( self, path ):
#read the data from files
self.nodes = []
self.edges = {}
try:
self.graphFile = open(path, 'r')
status = 0
for line in self.graphFile:
if 'label' in line:
status = 1
elif 'weight' in line:
status = 2
if status == 1... |
e622c139f4dfcdef898aee7db197b463f561cba9 | kpradyumna095/python-exercises | /list_comprehensions.py | 4,630 | 4.40625 | 4 | fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# Exercise 1 - rewrite the above example code using list comprehension syntax.
# Make a variable named uppercased_fruits to hold the output of the list ... |
41710051f4d07f94ca89c831fbc30c7e7fa91811 | luisfergr/Python-Basico-seccion-F | /Hoja de trabajo1/Ejercicio1.py | 245 | 3.9375 | 4 | print('\n')
print('Ejercicio 1: Triangulo Rectangulo')
print('\n')
print('Ingrese un numero entero positivo:')
num=int(input())
print('\n')
for i in range(1,num+1):
for j in range(i):
print("*", end="")
print()
|
e93d0ce781eb3ff8e8ed1515c3ccc49fb0c47dd9 | drewAdorno/Algos | /Python Algos.py | 2,200 | 4.125 | 4 | import math
'''Sara is looking to hire an awesome web developer and has received applications from various sources. Her
assistant alphabetized them but noticed some duplicates. Given a sorted array, remove duplicate values.
Because array elements are already in order, all duplicate values will be grouped together. As w... |
e68fabaf8e14347755d44c7ce5a81a14dbb11261 | xianyang27200/Python-Hangaman | /HANGMAN/Play.py | 1,967 | 3.9375 | 4 | import words
def game(word):
shape = 5
guessed_letter = []
word_completion = ("-")*len(word)
terminate = True
print("lets play hangman game")
print(words.hangman(shape))
print("\n")
#print(word)
print(word_completion)
while shape > 0 and terminate != False:
guess... |
82d6bb6bdc42ee561af2ee21bf44dc4199f20f1d | alexYooDev/onl_jud_al | /pPyY_test.py | 236 | 3.640625 | 4 | def solution(s):
p_num, y_num = 0, 0
for i in range(0, len(s)) :
if s[i]=='p' or s[i]=='P':
p_num+=1
elif s[i]=='y' or s[i]=='Y':
y_num+=1
return p_num==y_num
print(solution("pPoyY")) |
f0c12976379a87f2dc77fa035f470cef1cdde095 | alexYooDev/onl_jud_al | /sum_divisors.py | 471 | 3.65625 | 4 | def get_divisor(n):
n = int(n)
divisors = []
for i in range(1, n+1):
if(n%i == 0):
divisors.append(i)
return divisors
def solution(left, right):
answer = 0
lists = []
arr = []
for i in range(left, right+1):
lists.append(i)
for i in lists:
arr.append(get_divisor(i))
... |
e0ed3f04599a3b1e290535eac8177965045f978d | alexYooDev/onl_jud_al | /reversed_int.py | 115 | 3.515625 | 4 | def solution(n):
arr = list(str(n))
arr.sort(reverse=True)
answer = int("".join(arr))
return answer |
23e75d12282de605874e1ab4492561dae24663ac | Andrcw/Pacman | /display.py | 4,868 | 3.5 | 4 | import pygame
import math
class Display:
def __init__(self, screen, pm):
"""Display score, and how many pacman left"""
self.font = pygame.font.SysFont("monospace", 40)
self.font_1 = pygame.font.SysFont("monospace", 25)
self.font_2 = pygame.font.SysFont("monospace", 100)
se... |
92ee941d1a25e34f7299d6717461bcb2de0152d6 | jmmoore/AdventOfCode2015 | /Day03Solution/Day03Solution.py | 2,138 | 3.5625 | 4 | #!/usr/local/bin/python3
import operator
import os
def setUpMovementLists(inputFile):
movementList = list(open(inputFile).read())
# Slice operator [::2] outputs every other value.
santaMovementList = movementList[::2]
roboSantaMovementList = movementList[1::2]
return movementList, santaMovementList, r... |
ab3c28488f84bb2057a8a81a3caff74f82ae3f8f | hugkoala/LeetCode | /Solution/Python/generateParenthesis.py | 1,393 | 3.828125 | 4 | class Solution:
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
results = list()
return self.recParenthesis(n, '', 0, 0)
def recParenthesis(self, n, result, left, right):
if left > n or right > n:
return ''
... |
13c2f91c6ef041accf6a9ddad2d62df6d579fc88 | grzesk075/PythonSandbox | /basics/decorators.py | 548 | 3.78125 | 4 | from functools import wraps
def decorator_name(f):
@wraps(f)
def decorated(*args, **kwargs):
if not can_run:
print('Function will not run')
else:
print('before')
f(*args, **kwargs)
print('after')
return decorated
@decorator... |
c3e440945b254533261b2a67ad250446718c4b64 | grzesk075/PythonSandbox | /basics/scopes.py | 997 | 3.921875 | 4 | def scope_test():
def do_local():
spam = "local spam" # only inside this function
def do_nonlocal():
nonlocal spam # outer scope
spam = "nonlocal spam"
def do_global():
global spam # global scope
spam = "global spam"
spam = "test spam"
do_lo... |
e733be2b522c264643d1d5abc03e1e80900237ec | Kinzar97/OOP-in-Python | /Create_class.py | 1,019 | 3.609375 | 4 | from random import randint
class Warrior:
health = 100
def damage(self):
h = self.health - 20
print('У противника осталось:', h, "здоровья", end='\n\n')
return h
warrior1 = Warrior()
warrior2 = Warrior()
print('Привет, человек!\n\nТы попал в игру "Гладиаторы". В этой игре тебе ниче... |
aa6d693f642dcaacfe749efe184ed752ebbc0d67 | yulizhou/arctic-panther | /core/likert.py | 3,029 | 3.890625 | 4 | __author__="Aaron"
class Likert:
"""A dictionary of lists - holding survey data.
This class holds survey data in a dictionary
Keys are the levels
Values are lists of questions with a response at that level
For example, geog data might be a dictionary like:
{"Never":["Place 1","Place 3"], "Hard... |
28f1254e7e4f41b134c839d7521d49e0ca1693a6 | evansceo/greentalentkenyasite | /Python/news/newsapi/tests/article_test.py | 982 | 3.828125 | 4 | import unittest
# from app.models import Article
class Article:
"""
'''
Article class to define Article Objects
'''
"""
def __init__(self,id,name,author,url,title,urlToImage,content,publishedAt):
self.id =id
self.name = name
self.author = author
self.url = url... |
9170d4a9e04a2a1b6ce081cf9fd2010d82baa5b9 | n-nicholas-s/Toddler-Companion-Bot | /Lastest/simple-motormovement.py | 1,104 | 3.671875 | 4 | import os
from threading import Thread, Event
import time
prev = 0
x = 0
# It sends signals from one to another thread
bridge = Event()
def func():
global x
while True:
x = input("Forward/Backward/Left/Right/Measurements? 8/2/4/6/0 \n").upper()
motorMovement(x)
time.sleep(0.1... |
246a22c72c6caf92808e7dcecfb3057f0db0d0f0 | s1syphus/talkingDataKaggle | /src/neural_network_approach.py | 583 | 3.59375 | 4 | """
Neural network approach
"""
from keras.models import Sequential
from keras.layers import Dense, Activation
def train_and_test(train, test):
print(train)
print(test)
'''
model = Sequential()
model.add(Dense(output_dim=10, input_dim=))
model.add(Activation("relu"))
model.add(Dense(ou... |
26394efcef246c8ef0f58731b53138569ff3ac3f | Laurens117/programming1 | /Les 8/pe 8_5.py | 171 | 3.5 | 4 | def tafels(x,y):
for i in range(x,y):
for j in range(1, 11):
print('{:02}'.format(i),'x','{:02}'.format(j),'=','{:02}'.format(i*j))
tafels(1,11)
|
2ffb7ba5e16d3cd40805f7d6ca26e653d9efee87 | Laurens117/programming1 | /Les 9/pe 9_5.py | 566 | 3.59375 | 4 | def namen():
namenlijst = {}
count = 0
naam = input("Geef een naam: ")
while naam!='':
if namenlijst.get(naam):
namenlijst[naam] = namenlijst[naam] + 1
else:
namenlijst[naam] = 1
count = count + 1
naam = input("Volgende naam: ")
for name in n... |
347e1ec7ca005ff50c8d7836e18a603072ef4f69 | shiyingyuxianshu/deep_learning | /DL01_1_from_WhaleChen.py | 682 | 3.578125 | 4 | # 上交作业的时候,才发现自己理解错误了,向WhaleChen学习了相关内容
# 打开文件,读取文件
with open('./happiness_seg.txt') as f:
file = f.read()
import collections
filelist = file.split()
filelist2 = list()
for i in range(len(filelist)-1):
#定义每个独立的词即为 长度需要至少为2的词
#当然,这可能是一种过度的简化
#这样的好处是对于标点符号也自然被去除
if (len(filelist[i]) > 1 and len(file... |
6f5f430174e45f945b59b7cdc3f95629f89b209b | Erika001/CYPErikaGG | /libro/ejemplo2_8.py | 396 | 3.84375 | 4 | CATE = int(input("Determine la categoria del empleado (1-4): "))
SUE = float(input("Determine el sueldo del empleado; "))
NSUE = 0
if CATE == 1:
NSUE = SUE * 1.15
elif CATE == 2:
NSUE = SUE * 1.10
elif CATE == 3:
NSUE = SUE * 1.08
elif CATE == 4:
NSUE = SUE * 1.07
print(f"La categoria de el empleado es ... |
e7a28a7d73b9d305c44af2cdd77748c1fe890130 | Erika001/CYPErikaGG | /libro/problemas_resueltos/capitulo3/problema3_1.py | 407 | 3.8125 | 4 | SUMPAR = 0
SUMIMP = 0
CUEPAR = 0
for i in range(1,271,1):
NUM = int(input("Ingrese un numero entero: "))
if NUM != 0:
if (-1) ** NUM > 0:
SUMPAR += NUM
CUEPAR += 1
else:
SUMIMP += NUM
else:
PROPAR = SUMPAR / CUEPAR
print(f"El promedio de los numeros p... |
4b4e12d559b8c774b9fbdd26647a38790a868ed1 | Erika001/CYPErikaGG | /funciones.py | 1,647 | 3.953125 | 4 | def sumar(x , y):
z = x + y
return z
def restar(x , y):
return x - y
def mi_print(texto):
print(f"Este es mi print: {texto}")
def multiplica(valor , veces):
if veces == None:
print("Debes enviar el segundo argumento de la funcion")
else:
print(valor * veces)
def comanda(mesa ... |
e406509894fee6ffb175e967e7c88bf0bce8f835 | Erika001/CYPErikaGG | /libro/problemas_resueltos/capitulo1/problema1_6.py | 121 | 3.65625 | 4 | DIAS = int(input(“Determine un número de días”))
SEG = DIAS * 24 * 60 *60
print(f”En {DIAS}, hay {SEG} seg.”)
|
434a69165a75e71a157fa92cef111911f5b577ec | Erika001/CYPErikaGG | /listas2.py | 1,396 | 4.40625 | 4 | # arreglos
# lectura
# escritura / Asignacion
# actualizacion : inserccion, eliminacion, modificacion
# ordenamiento
# busqueda
# escritura
frutas = ["Zapote", "Manzana", "Pera", "Aguacate", "Durazno", "Uva", "Sandia"]
# lectura, el selector [indice]
print(frutas[2])
# lectura con for
# for opcion 1
for indice in ra... |
caaf716fa4f7424e1384a9cd0633381337557d11 | Erika001/CYPErikaGG | /libro/problemas_resueltos/capitulo1/problema1_7.py | 350 | 3.84375 | 4 | L1 = float(input(“Determine el primer lado del triangulo:”)
L2 = float(input(“Determine el segundo lado del triangulo:”)
L3 = float(input(“Determine el tercer lado del triangulo:”)
S = (L1 + L2 + L3)/2
AREA = (5* (5 – L1) * (5 – L2) * (5 – L3)) ** O.5
print(f”El área del triangulo con lados {L1}, {L2}, {L3}, es de: {AR... |
bf7eab18a528fa2b4e44ff759a5e4e3ce6215f6e | Erika001/CYPErikaGG | /libro/problemas_resueltos/capitulo2/problema2_2.py | 230 | 3.65625 | 4 | P = int(input("Introduzca una variable entera: "))
Q = int(input("Introduzca otra variable entera: "))
EXP = P ** 3 + Q ** 4 - 2 * P ** 2
if EXP < 680 :
print(f"Las variables fueron: {P}, {Q}.")
print("Fin del programa")
|
c7afc05ed86771635fbef4f499bd6087bf22ce45 | Mycleung/dailyprogrammer | /243easy.py | 528 | 3.546875 | 4 | with open("243easyinput", "r") as f:
input = [int(line) for line in f.readlines()]
def abundeficient(num):
factorsum = num
for ii in range(1, num):
if (num % ii) == 0:
factorsum += ii
return factorsum - (num * 2)
for num in input:
perfection = abundeficient(num)
if perfec... |
ed8a334e761488c74567177d7943645875315beb | Raman281990/Learning_Python | /classesInPython.py | 322 | 3.6875 | 4 | class Cat:
def __init__(self, color, legs):
self.color = color
self.legs = legs
def bark(self):
print("boww!!")
flex = Cat("ginger", 4)
print(flex.color)
flex.bark()
# classes can have other
# trying to access the attribute of class that is not defined causes AttributeError
#flex.wid... |
c949f694f2b79bc0d3a5506aa5dfa472820c2d27 | Raman281990/Learning_Python | /fileHandling.py | 674 | 4.09375 | 4 | ##Reading lines from a txt file and removing new line character
fileHandle = open("Arrays.txt")
for lines in fileHandle:
lines = lines.rstrip()
if lines.startswith("find"):
print(lines)
## Reading a file and calculating average of extracted data
fname = input("Enter file name")
fileX = open(fname)
to... |
b82db46892094bb0697546d8f854c5b342ae4a82 | maddie143/Python-project | /Lab/Domain/Student.py | 1,852 | 4 | 4 | '''
Created on Nov 25, 2015
@author: Mada
'''
class Student():
def __init__(self,nume,grupa,ID):
self.nume = nume
self.grupa = grupa
self.ID = ID
'''
Returneaza numele studentului
'''
def Get_Stud_Name(self):
return self.nume
'''
Returneaza gru... |
10278247596c7f6f78078b74714ab5cf0a938a28 | larvaproject/mysite | /functions/claroshop.py | 838 | 3.5 | 4 | import pandas as pd
from datetime import datetime, date, timedelta
def getFecha():
#Traemos la fecha
x = datetime.now() - timedelta(days=1)
dia = str(x.strftime("%d"))
mes = str(x.strftime("%m"))
anio = str(x.year)
date = dia + '-' + mes + '-' + anio
return date
date = getFecha()
nombre = 'claroshop-' + ... |
03d6669774a26c01ff4058fd9f2ac8d9d47cdeea | singhkakan/LearningPython | /circumference.py | 121 | 3.828125 | 4 | #!/usr/bin/python
pi = 3.14159
radius = 3
c = pi * radius ** 2
print "The circumference of a circle of radius 3 is ", c
|
0705a6b331883e33c9fb69a9749b737c41d38af1 | brmaciel/Battleship | /Board.py | 922 | 3.546875 | 4 | class Board(object):
__size = 10
def __init__(self, nome):
self.nome = nome
self.__tabuleiro = []
self.__defineBoard()
def __defineBoard(self):
for n in range(self.__size):
self.__tabuleiro.append(['_'] * self.__size)
def printBoard(self):
for rows ... |
3bb64b4540bed752e3f748ce0af80e2657d373e4 | carcagi/hpython | /part1/P2_looping.py | 1,393 | 4.25 | 4 | # while loops
# Not i++ avaiable
i = 0
while i <= 5:
# print(i)
i += 1
# break and continue
i = 0
while i <= 5:
i += 1
if i == 2:
continue
print(i)
if i == 4:
break
# else
i = 0
while i <= 5:
i += 1
print(i)
else:
print('Is more than 5')
# if you break before else ... |
91126a580d1917ea7351a5dda506b8370f2dcbbd | bhamshu/Code-comparator | /comparator.py | 1,353 | 3.609375 | 4 | def compare(thepath, args, sol = None):
'''takes a directory and a list of files in it and finds points of differences'''
f = [None]*len(args)
for i in range(len(args)):
theoutput = args[i]
print(args[i])
with open(thepath+"/"+theoutput) as l:
f[i] = l.read().split("\n")
if sol!=None:
with ope... |
575617625d8ba29a27eebc80b953330d8e20fb9f | famd92/python | /FizzBuzz.py | 565 | 4.3125 | 4 | ###Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz" ####
def fizzbuzz(number):
if (number%3 ==0 and number%5 ==0):
output ... |
236fd9c15ab31725323f02c99671f89d3220a974 | saramhse/Python-Challenge | /pypoll/main.py | 2,846 | 4 | 4 | import os
import csv
#write a get the names of the candidates and place them in a list
#in other words remove the duplicates from the candidate names column
def duplicate_remover(candidate_name_column):
unique_candidates=[]
for i in candidate_name_column:
if i not in unique_candidates:
uniq... |
af0d11f8336857408a067de03690dd4f87eaf7bb | mstites/POE | /lab2/analyzeData3D.py | 1,760 | 3.5 | 4 | import serial
import numpy as np
import pickle
def analogToDistance(analog):
"""Convert an analog reading from the IR
distance sensor to inches
analog: Analog reading
returns: distance in inches"""
return 5805.99102955023*(analog**-1.03380467328515)
def getSpherical(data):
"""Determine the pol... |
495cf926664814bde06e56929de66d0e25891883 | leah-ewing/Wordcount.py | /wordcount.py | 439 | 3.703125 | 4 | # put your code here.
def wordcount(input):
#input = open("test.txt")
input_var = open(input)
letter_counts = {}
for line in input_var:
line = line.rstrip()
line = line.split(' ')
for word in line:
letter_counts[word] = letter_counts.get(word, 0) + 1
... |
698c99fa164da86083f1dd78139adbb13cb8d182 | raspoli/Prisoner-s-dilemma-Network-Effect | /numbers_of_strategies.py | 505 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 2 12:19:47 2020
@author: asus
"""
import numpy as np
import matplotlib.pyplot as plt
def area(strategy_list):
'''return a list of numbers of strategies
---- input : strategy list
---- out put :list of numbers of each strategy
'''
unique_elements, c... |
a469a17d2b45db437b60bd4feab347757352c328 | cmaher92/interview-prep | /fixthestack.py | 737 | 3.984375 | 4 | # stacked plates incorrectly
# first two items were always placed in the wrong order
# write a function that takes a stack as input and swaps the bottom two items
# mutate stack, don't return a new one
# push, pop, peak, size
stack = [2, 1, 3, 4, 5, 6, 7]
def fix_the_stack(stack):
temp_stack = []
second_to_la... |
de32bca8a89b6829be5b6ac3d173349ec155fd1b | Nancy-tayal/internity_python | /Day8.py | 5,696 | 4.25 | 4 | '''
NumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc. from
the given elements in the array. The functions are explained as follows −
numpy.amin() and numpy.amax()
These functions return the minimum and the maximum from the elements in the... |
22fd4db624183128283fd16e31c754077dbd9f78 | xrounder/minicop | /gnn/DynamischesSystem.py | 637 | 3.90625 | 4 | import matplotlib.pyplot as plt
def loop(x):
t = 0.01
t_max = 10
x_values = []
y_values = []
t_start = 0
while t_start < t_max:
x_neu = x + t*(x-(x**3))
x = x_neu
print(x_neu)
print("Vergangene Zeit", t_start)
t_start = t_start + t
x_values.appe... |
9c7ba5ce8f42ca0b8d1c5fe543b3bf1b2fd989cf | michaelNinh/inventus | /Models/Creator.py | 1,471 | 3.5 | 4 | from Models.Video import Video
class Creator:
"""Class data model for youtube creator"""
def __init__(self, channelTitle, creatorId, totalSubscribers, totalViews, availableVideoIds, email, totalComments, videoCount, discoveryKeyword, reachOut, country, notes):
self.channelTitle = channelTitle
... |
e53cb59fea32dd2efedb3f89f1ad6e4278da0c04 | imrod/imrod | /python/OddOccurrencesInArray.py | 443 | 3.53125 | 4 | #!/usr/bin/python
def solution(B):
freq = {}
for num in B:
# print "num = %d" % num
if num not in freq:
freq[num] = 1
elif freq[num] == 2:
freq[num] = 1
else:
freq[num] += 1
for k, v in freq.iteritems():
if v == 1:
re... |
f68bbf2081859c517b8dd03155db11dd242ae3bb | mjanibelli/projetos-iniciantes | /projetos/projeto-mercado/mercado.py | 1,263 | 4.03125 | 4 | import os
nome_arquivo = "lista.txt"
while True:
print(" Lista de compras de mercado ".center(45, "="))
qnt_itens = int(input("\nDigite a quantidade de itens que deseja inserir na sua lista: "))
lista_mercado = dict()
for item in range(qnt_itens):
nome_item = input(f"\nDigite o nome do {item... |
8857dd572a333f0dd6ea437b128ae88dd03e6d1f | mjanibelli/projetos-iniciantes | /projetos/projeto-gerador-senha/senha_modulo.py | 1,208 | 4.125 | 4 | """Verifica tamanho da senha e a gera.
Atributos:
alfabeto (list): Lista que possui as letras do alfabeto.
numeros (list): Lista dos números de 0 a 9.
chars_especiais (list): Lista de caracteres especiais.
"""
import random
import string
alfabeto = list(string.ascii_letters)
numeros = list(string.digits)... |
8cd7cb941e13be12f84b7249976d53ef21402a85 | mjanibelli/projetos-iniciantes | /projetos/projeto-conta-banco/conta.py | 1,538 | 3.796875 | 4 | import os
import conta_modulo
print(" Conta Bancária ".center(30, "="))
nome = input("Digite seu primeiro nome: ")
sobrenome = input("Digite seu último sobrenome: ")
cliente = conta_modulo.ContaBancaria(nome, sobrenome)
os.system("cls")
while True:
print("Menu:\n[1] -> Depositar\n[2] -> Sacar\n[3] -> Conta\n[0]... |
bdc89049220c829618f1bd0162a896007a7070c8 | hamdi3/Python-Practice | /Statments.py | 937 | 3.96875 | 4 | #for statments
l = [1,2,3,4,5]
sum = 0
for num in l :
sum += num
print(sum)
string = "This is a String"
for s in string:
print(s)
l2= [(1,2),(3,4),(5,6)]
for t in l2 :
print (t)
for (t1,t2) in l2:
print(t1,t2)
#Excersises
#ex1: giving only the words that start with an S in a long string.
s1 = ... |
b4ed82079b3ad9ae8e9e2628c7570668215044b3 | hamdi3/Python-Practice | /Formatting.py | 783 | 4.53125 | 5 | #Formatting in python
str="string"
print("this will type a %s" %(str)) # in %() whatever you write will be changed to a string
print("this will type a %s , %s" %("hello" ,3)) # you can use %s 2 times and more but you use one %() with a comma for diffrient ones
print("this will type a float %1.2f" %(13.4454)) # %1.2f me... |
0b6103ea1debe86a77d965bd71a94bd497c66e6f | zhangxl97/leetcode | /101_200/Q121_130.py | 8,141 | 3.5625 | 4 | from tabulate import tabulate
from singly_linked_list import ListNode, connect_nodes, print_nodes
from tree import TreeNode, Node
from typing import List
class Solution:
# 121 Best Time to Buy and Sell Stock, Easy
# one transaction
def maxProfit1(self, prices: List[int]) -> int:
size = len(prices)... |
591fb93f6bf76519edca5535d72e2042fb6ab6a2 | zhangxl97/leetcode | /1_100/Q81_90.py | 8,928 | 3.703125 | 4 | from typing import List
from tabulate import tabulate
from singly_linked_list import ListNode, print_nodes, connect_nodes
class Solution:
# 81. Search in Rotated Sorted Array II, Medium
def search(self, nums: List[int], target: int) -> bool:
size = len(nums)
if size == 0:
return Fa... |
c9eba7faa4c9c5c88a0d1a3deb4c1b2b803d864e | ZoroSpace/LeetCode | /258AddDigits.py | 174 | 3.640625 | 4 | class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
return 9 if (num % 9 == 0 and num != 0) else num % 9
|
8b973f493bb1ed6c09f8c628b8a09728b0f850b3 | Shivangi97sahni/acadview | /loops.py | 1,037 | 4.03125 | 4 | #1
i=0
while(i<5):
num=input("enter the number")
print(num)
i=i+1
#2
while True:
print("INFINITE")
#3
numbers=[]
for i in range (0,8):
num=int(input("enter the number"))
numbers.append(num)
print("the list is",numbers)
squares=[]
for num in numbers:
sq=num*num
squ... |
7d967af60fd82ab89d78f0448c68dae0f35e6941 | Shivangi97sahni/acadview | /exception.py | 1,225 | 4 | 4 | #1
#exception occured is ZeroDivisionError
try:
a = 3
if(a<4):
a = a/(a-3)
print(a)
except ZeroDivisionError:
print("num is divided by 0")
#2
#exception occured is IndexError
try:
a=[1,2,3]
print(a[3])
except (ZeroDivisionError,IndexError):
print("num is divided by 0")
... |
42d7cd6a8b5b5c7e83ef663a223ca66ee62e21d5 | Shivangi97sahni/acadview | /classes.py | 2,060 | 3.796875 | 4 | #1
class Circle():
def __init__(self,radius):
self.radius = radius
def getArea(self):
print(3.14*self.radius*self.radius)
def getCircumference(self):
print(self.radius*2*3.14)
c = Circle(radius=4)
c.getArea()
c.getCircumference()
#2
class student():
def __init_... |
17dc742bc04ecdbf2e521dbf047afe5e3d3fbdc5 | raulito28/Ejercicioclase6 | /Ejercicios/Ejercicio6 clase 2opcion.py | 288 | 3.671875 | 4 | def contar_vocales(palabra):
contador = 0
for letra in palabra:
if letra.lower() in "aeiou":
contador += 1
return contador
palabra = input("Dime una palabra: ")
cantidad = contar_vocales(palabra)
print(f"En la palabra '{palabra}'' hay {cantidad} vocales") |
65a504a72c98cee8474027cbf398a67f0147ec6d | wangzhi102001/GitHub | /myproject/myproject/Employees.py | 285 | 3.59375 | 4 | class Employee(object):
"""description of class"""
def __init__(self, first,last,salary_by_year):
self.first=first
self.last=last
self.salary_by_year= salary_by_year
def give_raise(self,addnum=5000):
self.salary_by_year+=addnum
|
73ffc1fc311f0ddcbfe0d994ef393e68a3fd468d | s1bel/Loan_Calculator | /Problems/Count up the squares/main.py | 248 | 3.734375 | 4 | numbers = []
simple_sum = 0
square_sum = 0
while True:
numbers.append(int(input()))
simple_sum += numbers[-1]
square_sum = square_sum + numbers[-1] ** 2
if simple_sum == 0:
break
print(square_sum if numbers[0] != 0 else 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.