blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
29bffe754e6bd303f1a533584676836245cbe9f1 | ameena63033/Non_Linear-Data-Structures | /Reversal_of_SLL_using_two_pointers.py | 1,478 | 4.25 | 4 | #node class for creating node object
class node:
def __init__(self,val = None):
self.val = val
self.next = None
#to create linked list object
class linkedlist:
def __init__(self,head = None):
self.head = head
#function for printing sll
def print_linked_list(ll1):
ptr = ll1.head
while ptr:
print(ptr.val , '-->' , end = '')
ptr = ptr.next
if(ptr.next == None):
print(ptr.val)
break
#function for printing reversal of sll
#reversing using two pointers
def printing_reversed_linked_list(ll1):
if(ll1.head==None):
print("empty linkedlist")
elif(ll1.head.next == None):
print(ll1.head.val)
else:
ptr1 = ll1.head
ptr2 = ptr1.next
ll1.head = ptr2
ptr1.next = None
while ll1.head:
ll1.head = ptr2.next
ptr2.next = ptr1
ptr1 = ptr2
ptr2 = ll1.head
ll1.head = ptr1
print_linked_list(ll1)
if __name__ == '__main__':
l1 = linkedlist()
n = int(input("enter number of nodes:"))
for i in range(0,n):
if(l1.head == None):
l1.head = node(int(input("enter node value:")))
p1 = l1.head
else:
p1.next = node(int(input("enter node value:")))
p1 = p1.next
print_linked_list(l1)
printing_reversed_linked_list(l1)
|
4e33f5d54fad7f93a7b7ca13e6db8b8abf75aae9 | MrzvUz/Python | /Python_Entry/movie_exercise.py | 3,376 | 4.625 | 5 | # Incomplete app!
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
# You may want to create a function for this code
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
# Create other functions for:
# - listing movies
def list_movies(movies):
return movies[movies]
print(list_movies(movies))
# - finding movies
# And another function here for the user menu
selection = input(MENU_PROMPT)
while selection != 'q':
if selection == "a":
pass
elif selection == "l":
pass
elif selection == "f":
pass
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
# Remember to run the user menu function at the end!
## The Solution No 1. This is better solution:
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
def add_movie():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def show_movies():
for movie in movies:
print_movie(movie)
def print_movie(movie):
print(f"Title: {movie['title']}")
print(f"Director: {movie['director']}")
print(f"Release year: {movie['year']}")
def find_movie():
search_title = input("Enter movie title you're looking for: ")
for movie in movies:
if movie["title"] == search_title:
print_movie(movie)
user_options = {
"a": add_movie,
"l": show_movies,
"f": find_movie
}
def menu():
selection = input(MENU_PROMPT)
while selection != 'q':
if selection in user_options:
selected_function = user_options[selection]
selected_function()
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
menu()
# The Solution No 2:
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
def add_movies():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def show_movies():
for movie in movies:
print_movie(movie)
def print_movie(movie):
print(f"Title: {movie['title']}")
print(f"Director: {movie['director']}")
print(f"Release Year: {movie['year']}")
def find_movies():
search_title = input("Please, enter the movie title that you are looking for: ")
for movie in movies:
if movie["title"] == search_title:
print_movie(movie)
user_option = {
"a" : add_movies,
"l" : show_movies,
"f" : find_movies
}
def menu():
selection = input(MENU_PROMPT)
while selection != 'q':
if selection in user_option:
selected_function = user_option[selection]
selected_function()
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
menu()
|
8b400a3d94acb9797454fdb0c7efae49c65c20af | LiJieSu0/LeetCode | /python/1275.FindWinnerTicTacToe Game.py | 910 | 3.640625 | 4 | def tictactoe(moves):
aList=moves[::2]
bList=moves[1::2]
aList.sort()
bList.sort()
if [0,0] in aList and [1,1] in aList and [2,2] in aList or [0,2] in aList and [1,1] in aList and [2,0] in aList:
return "A"
if [0,0] in bList and [1,1] in bList and [2,2] in bList or [0,2] in bList and [1,1] in bList and [2,0] in bList:
return "B"
axDict={}
ayDict={}
bxDict={}
byDict={}
for i in aList:
axDict[i[0]]=axDict.get(i[0],0)+1
ayDict[i[1]]=ayDict.get(i[1],0)+1
for i in bList:
bxDict[i[0]]=bxDict.get(i[0],0)+1
byDict[i[1]]=byDict.get(i[1],0)+1
for i in range(3):
if i in axDict:
if axDict[i]==3:
return "A"
if i in ayDict:
if ayDict[i]==3:
return "A"
if i in bxDict:
if bxDict[i]==3:
return "B"
if i in byDict:
if byDict[i]==3:
return "B"
if len(moves)==9:
return "Draw"
else:
return "Pending"
print(tictactoe([[0,0],[2,0],[1,1],[2,1],[2,2]]))
|
614f942da599ff50d2b8608b07f4f8a5a1cb218e | RaviMudgal/AlgoAndDataStructures | /recursion/SumList.py | 338 | 3.875 | 4 | def listSum(numList):
sum = 0
for i in numList:
sum += i
return sum
print (listSum([1,2,3,4,]))
# listSum using recursion
def listSumRecursion(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listSumRecursion(numList[1:])
print(listSumRecursion([3,4,5,6,7,7,8]))
|
7a01efbdfdff029b7468673718789857aabf584e | bossyjossy/IAmLearninPython | /exercises/LPTHW_Exercise6.py | 1,545 | 4.5625 | 5 | # This is my completed exercise for Learn Python The Hard Way Exercise 6
#
# This is slightly modified from the lesson so that I can test things out
# and really solidify what I learned.
#
# EXERCISE 6: Strings and Text
# Setting variable 'x' to a string. Also using string formatting operation to format a number within the string.
x = "There are %d types of people..." % 10
# Setting two other variables with string values
binary = "binary"
do_not = "don't"
# Using multiple variables within setting variable 'y'
y = "Those who know %s and those who %s." % (binary, do_not)
# Print these two variables.
print x
print y
# Print these two variables with other string formatting operations.
# The first line should print everything including all quotes.
print "I said: %r." % x
# This line should print just the contents with no quotes.
print "I also said: %s." % y
# This line should print just the contents with single quotes.
print "I also said: '%s'." % y
# More examples
# In this line, the variable is being set to the boolean value of "False"
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
# If I wanted to set the variable to a string, I would do this:
hilarious2 = "Not!"
joke_evaluation2 = "Isn't that joke so funny?! %s" #Note: I had to use double quotes because of the contraction
print joke_evaluation2 % hilarious2
# One more example to show connecting two variables which are strings.
w = "This is the left side of ..."
e = " a string with a right side."
print w + e |
2c588cb3ddeaf4b59f77397f6022c3dcff2214cd | kju2/euler | /problem044.py | 1,495 | 4.0625 | 4 | """
Pentagonal numbers are generated by the formula, P_n = n(3n - 1)/2. The first
ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their difference,
70 - 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, P_j and P_k, for which their sum and
difference is pentagonal and D = |P_k - P_j| is minimised.
What is the value of D?
"""
from itertools import count
from math import sqrt
def pentagonal_number(index):
"""
>>> map(pentagonal_number, range(10))
[0, 1, 5, 12, 22, 35, 51, 70, 92, 117]
>>> pentagonal_number(-1)
0
"""
if index < 0:
return 0
return int(index * (3 * index - 1) / 2)
def is_pentagonal(number):
"""
>>> all(map(is_pentagonal, [1, 5, 12, 22, 35, 51, 70, 92, 117]))
True
>>> any(map(is_pentagonal, [2, 3, 4, 6, 7, 8, 9, 10, 11, 23, 24]))
False
"""
if (sqrt(24 * number + 1)) % 6 == 5:
return True
return False
def main():
"""
>>> main()
5482660
"""
for k in count(2):
p_k = pentagonal_number(k)
for j in range(k - 1, 0, -1):
p_j = pentagonal_number(j)
difference = p_k - p_j
if is_pentagonal(difference):
summe = p_k + p_j
if is_pentagonal(summe):
print(difference)
return
if __name__ == "__main__":
import doctest
doctest.testmod()
|
99c382213340924219f3d48ec00cfd2b2e9c41cd | szweibel/szweibel.github.io | /workshops/pythonWorkshop/ex7.py | 359 | 4.53125 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count", number
# same as above
for fruit in fruits:
print "A fruit of type: ", fruit
# This loop has an 'if' clause
for fruit in fruits:
if 'ap' in fruit:
print fruit |
fe28bee82390c662f705673f76a604783f5c4223 | nasir-001/Week-One | /Vid_3.py | 290 | 3.546875 | 4 | "Naisr Lawal"
"Nasir is awesome"
"I don't think she's 18"
'she said, "What part of the cow is meatloaf from"'
"I don\'t think she's 18"
print("Hey now brown cow")
print(r'C:\\Nasir\Desktop\PythonWithTahir')
first_name = "Nasir"
first_name + " Lawal"
first_name + " Aliyu"
first_name * 5
|
65a4ce0289421d1271c0760ade58c7905f29a75d | omakasekim/2020_SoftwareDesign | /Code/2-2/2.py | 222 | 3.796875 | 4 | str1 = input()
str2 = input()
str3 = input()
strResult = str1 + str2 + str3
float1 = float(input())
float2 = float(input())
float3 = float(input())
floatResult = float1 + float2 + float3
print(strResult)
print(floatResult) |
6113d6812301b2c4e7a1ab8acf82a988fd58abf6 | hannahac/recursion | /recursions.py | 343 | 4.0625 | 4 | def power(number, power_to_raise):
#2^4 = 2*2*2*2
#2^4 = 2^3*2
if power_to_raise > 1:
power_to_raise = power_to_raise - 1
return number * power(number, power_to_raise)
elif power_to_raise < 0:
raise Exception("Math error")
else:
return 1
result = power(3, -4)
print(result) |
5e8f6c398b2204936f18edc1c081cb8231091b02 | Tandd2015/python_stack | /python_stack_2.7/Python OOP/mathdojo/mathdojo.py | 5,256 | 3.5625 | 4 | # part 1
class MathDojo(object):
def __init__(self):
self.equals = 0
def add(self, *args):
for add_int in args:
self.equals += add_int
return self
def subtract(self, *args):
for sub_int in args:
self.equals -= sub_int
return self
def result(self):
print self.equals
return self
md = MathDojo()
md.add(2).add(2,5).subtract(3,2).result()
# part 2
class MathDojoModify1(MathDojo):
def __init__(self):
super(MathDojoModify1, self).__init__()
def add(self, *args):
for add_int in args:
if type(add_int) == list:
add_list_equals = 0
for add_list_int in add_int:
add_list_equals += add_list_int
self.equals += add_list_equals
add_list_equals = 0
else:
super(MathDojoModify1, self).add(add_int)
return self
def subtract(self, *args):
for sub_int in args:
if type(sub_int) == list:
sub_list_equals = 0
for sub_list_int in sub_int:
sub_list_equals -= sub_list_int
self.equals += sub_list_equals
sub_list_equals = 0
else:
super(MathDojoModify1, self).subtract(sub_int)
return self
md1 = MathDojoModify1()
md1.add([1],3,4).add([3,5,7,8],[2,4.3,1.25]).subtract(2,[2,3],[1.1,2.3]).result()
class MathDojoModify2(MathDojoModify1, MathDojo):
def __init__(self):
super(MathDojoModify2, self).__init__()
def add(self, *args):
for add_int in args:
if type(add_int) == tuple:
for add_key, add_value in enumerate(add_int):
add_list_equals = 0
if type(add_value) == list:
for add_individual_value in add_value:
add_list_equals += add_individual_value
self.equals += add_list_equals
elif type(add_value) == tuple:
for add_value_key, add_value_value in enumerate(add_value):
add_value_list_equals = 0
if type(add_value_value) == list:
for add_value_individual_value in add_value_value:
add_value_list_equals += add_value_individual_value
self.equals += add_value_list_equals
else:
super(MathDojoModify2, self).add(add_value)
else:
super(MathDojoModify2, self).add(add_value)
else:
super(MathDojoModify2, self).add(add_int)
return self
def subtract(self, *args):
for sub_int in args:
if type(sub_int) == tuple:
for sub_key, sub_value in enumerate(sub_int):
sub_list_equals = 0
if type(sub_value) == list:
for sub_individual_value in sub_value:
sub_list_equals -= sub_individual_value
self.equals += sub_list_equals
elif type(sub_value) == tuple:
for sub_value_key, sub_value_value in enumerate(sub_value):
sub_value_list_equals = 0
if type(sub_value_value) == list:
for sub_value_individual_value in sub_value_value:
sub_value_list_equals -= sub_value_individual_value
self.equals += sub_value_list_equals
else:
super(MathDojoModify2, self).subtract(sub_value)
else:
super(MathDojoModify2, self).subtract(sub_value)
else:
super(MathDojoModify2, self).subtract(sub_int)
return self
md2 = MathDojoModify2()
md2.add([1],3,4).add([3,5,7,8],[2,4.3,1.25]).subtract(2,[2,3],[1.1,2.3]).subtract(([1,1,1],[1,1])).add(([1,1],([1,1,1]))).result()
# def add1(self, *args):
# for add1_int in args:
# if type(add1_int) == list:
# add1_list_equals = 0
# for add1_list_int in add1_int:
# add1_list_equals += add1_list_int
# self.equals += add1_list_equals
# elif type(add1_int) == int or type(add1_int) == float:
# self.equals += add1_int
# else:
# print "This is not a valid entry type"
# return self
# def sub1(self, *args):
# for sub1_int in args:
# if type(sub1_int) == list:
# sub1_list_equals = 0
# for sub1_list_int in sub1_int:
# sub1_list_equals -= sub1_list_int
# self.equals += sub1_list_equals
# elif type(sub1_int) == int or type(sub1_int) == float:
# self.equals -= sub1_int
# else:
# print "This is not a valid entry type"
# return self
|
bbf04ccc135e5e0fb9161c71cc5c4ee67dc7c209 | taka-rui/takasite | /class.py | 201 | 3.703125 | 4 | class Car:
class_name = "Car"
def __init__(self):
self.name = None
def show(self):
print(self.name)
car = Car()
car.name = "セダン"
car.show()
print(Car.class_name) |
f876a69b0758ec1faf800c70e3403a2e39b7b8c9 | StephanRaab/pythonProgramming | /lesson2.py | 3,046 | 4.09375 | 4 | # for i in [2, 4, 6, 8, 10]:
# print("i = ", i)
#
# for i in range(0, 11, 2):
# print (i)
#
# # problem 1: print odds from 1 - 20
# for i in range(1, 21):
# if (i % 2) != 0:
# print(i)
#
# your_float = input("Enter a float: ")
# your_float = float(your_float)
# print("Rounded to 2 decimals: {:.2f}".format(your_float))
#
# # problem 2: have the user enter their investment amount and expected interest earned each year
# # each your their investment will increase by their investment + their investment * interest rate
# # print out earnings after a 10 year period
#
# investment = input("How much would you like to invest: ")
# interest_rate = input("What is the interest rate: ")
#
# investment = float(investment)
# interest_rate = float(interest_rate) * .01
# # My solution
# for i in range(11):
# print("In year {} your investment earnings would be {:.2f}".format(i, investment))
# investment += investment * interest_rate
#
# # Derek's Solution
# for i in range(10):
# investment += investment * interest_rate
# print("Investment after 10 years: {:.2f}".format(investment))
#
# import random
# rand_num = random.randrange(1, 51)
# i = 1
#
# while (i != rand_num):
# i += 1
#
# print("The random value is: ", rand_num)
#
# i = 1
# while i <= 20:
# if (i % 2) == 0:
# i += 1
# continue # this means any code below here doesn't run, it loops back to the beginning
# if i == 15:
# break # I don't want the loop to continue, stop/break here
# print("Odd: ", i)
# i += 1
# Problem 3: Draw a pine tree on the screen
# how tall is the tree
# use 1 while loop and 3 for loops
#
###
#####
#######
#
# 4 space : 1 hash
# 3 space : 3 hash
# 2 space : 5 hash
# 1 space : 7 hash
# 0 space : 9 hash
# 4 space : 1 hash
#Stephan's answer below
treeHeight = eval(input("How tall is the tree: "))
i = 0
hashCount = 1
print((treeHeight + 1) * ' ' + '#')
while i < treeHeight - 1:
initialNum = treeHeight - 1
space = initialNum - i
hashCount += 2
print((space * ' '), ('#' * hashCount))
i += 1
continue
print((treeHeight + 1) * ' ' + '#')
# Derek's Answer Below
# Get the number of rows for the tree
tree_height = input('How tall is the tree: ')
# convert into an integer
tree_height = int(tree_height)
# get the starting spaces for the top of the tree
spaces = tree_height - 1
# One hash to start that will be incremented
hashes = 1
# save stump spaces for later
stump_spaces = tree_height - 1
# make sure right number of rows are printed
while tree_height != 0:
# print spaces --> end=''
for i in range(spaces):
print(' ', end='')
# print the hashes
for i in range(hashes):
print('#', end='')
# new line after each row is printed
print()
# spaces decremented by 1 each time
spaces -= 1
# hashes incremented by 2 each time
hashes += 2
# decrement tree height each time to jump out of the loop
tree_height -= 1
# print stump
for i in range(stump_spaces):
print(' ', end='')
print('#')
|
bc69118506c2a5dfd3605fc845c04589e59509bf | dimDamyanov/Py-Fundamentals | /11. EXCERCISE - Functions/06.py | 516 | 4.03125 | 4 | password_input = input()
def is_valid(password: str):
valid = True
if not 6 <= len(password) <= 10:
print('Password must be between 6 and 10 characters')
valid = False
if not password.isalnum():
print('Password must consist only of letters and digits')
valid = False
if sum(c.isnumeric() for c in password) < 2:
print('Password must have at least 2 digits')
valid = False
return valid
if is_valid(password_input):
print('Password is valid') |
83870fd4b1ff04dbfd59924e710d3c45ccb1d10b | mumer29/100-days-code-challenge | /Union-of-two-arrays.py | 698 | 4.09375 | 4 | #User function Template for python3
class Solution:
#Function to return the count of number of elements in union of two arrays.
def doUnion(self,a,n,b,m):
final_list = list(set(a)|set(b))
return len(final_list)
#code here
#{
# Driver Code Starts
#Initial Template for Python 3
#contributed by RavinderSinghPB
if __name__=='__main__':
t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().strip().split()]
a=[int(x) for x in input().strip().split()]
b=[int(x) for x in input().strip().split()]
ob=Solution()
print(ob.doUnion(a,n,b,m))
# } Driver Code Ends
|
7c8235058bdaf9ee8300bcc89b705dfad9b30532 | LYC199124/_LeetCode_Study_ | /array/Leecode_intersect_function1_.py | 558 | 3.75 | 4 | #!/usr/bin/env python3.0
#!-*coding:utf-8 -*-
#!@Time :2018-5-22 11:07
#!@Author : LYC
#!@File : Leecode_intersect_function1_.PY
class Solution(object):
def intersect(self, nums1, nums2):
list_interset = []
for p in nums1:
for k in nums2:
if p == k:
list_interset.append(p)
nums2.remove(k)
break
return list_interset
if __name__ == '__main__':
ins1 = Solution()
nums1 =[1,2,2,1]
nums2 =[2,2]
print(ins1.intersect(nums1,nums2)) |
155752006c5732a69c421e3866dcd2d77c66e56f | IbrahimOladepo/Python-Projects | /Age_Calculator/age_opt.py | 2,524 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 5 09:55:04 2016
@author: IbrahimOladepo
"""
import time
import age_FUNCTION
import pandas as pd
# inputs
name = input("Enter your name: ")
# input year of birth and check validity
currentYear = int(time.strftime("%Y"))
birthYear = int(input("Enter birthYear: "))
age_FUNCTION.validyear(currentYear, birthYear)
# input month of birth and check validity
birthMonth = input("Enter birthMonth: ")
age_FUNCTION.validmonth(birthMonth)
# input day of birth and check validity
birthDay = int(input("Enter birthDay: "))
age_FUNCTION.validday(birthMonth, birthDay)
prevYearDays = age_FUNCTION.yearDays(currentYear - 1)
days = age_FUNCTION.bdayLocation(birthYear, birthMonth, birthDay)
currentDay = int(time.strftime("%j"))
# calculations
if (days < currentDay):
daysOld = currentDay - days
yearsOld = currentYear - birthYear
elif (days > currentDay):
daysOld = (prevYearDays - days) + currentDay
yearsOld = currentYear - birthYear - 1
else:
daysOld = 0
yearsOld = currentYear - birthYear
print ("\nYou are {} years old and {} days old".format(yearsOld, daysOld))
"""
# save data to file
keep = open('ageData.txt', 'a')
print(name, file = keep)
print("Runtime: " + time.strftime("%c"), file = keep)
print("age: {} years old and {} days old\n\n".format(yearsOld, daysOld), file = keep)
keep.close()
"""
# Saving data in .csv file with pandas
newdf = pd.DataFrame([(name, yearsOld, daysOld, time.strftime("%c"))],
columns = ['NAME', 'YEARS_OLD', 'DAYS_OLD', 'TIME'])
try:
if (yearsOld < 19 ):
olddf = pd.read_csv('agedata_18below.csv')
data = pd.concat([olddf, newdf], ignore_index=True)
data.to_csv('agedata_18below.csv', index = False)
elif (yearsOld < 41):
olddf = pd.read_csv('agedata_18to40.csv')
data = pd.concat([olddf, newdf], ignore_index=True)
data.to_csv('agedata_18to40.csv', index = False)
else:
olddf = pd.read_csv('agedata_40plus.csv')
data = pd.concat([olddf, newdf], ignore_index=True)
data.to_csv('agedata_40plus.csv', index = False)
except:
if (yearsOld < 19 ):
newdf.to_csv('agedata_18below.csv', index = False)
elif (yearsOld < 41):
newdf.to_csv('agedata_18to40.csv', index = False)
elif (yearsOld > 40):
newdf.to_csv('agedata_40plus.csv', index = False)
else:
print("Cannot be classified.") |
1ad74249d657b1a98c9aa4b55b0efd5569603c9f | friessm/math-puzzles | /p0010.py | 966 | 3.765625 | 4 | """
Solution to Project Euler problem 10
https://projecteuler.net/problem=10
"""
def sieve_of_eratosthenes(number):
"""
Sieve of Eratosthenes
Return the sum of all prime numbers from 2 to number.
Standard implementation of Sieve with some optimisations.
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
"""
# Create list from 0 to number
sieve_list = [True for x in range(0, number+1)]
# Remove multiples of 2
for i in range(4, number+1, 2):
sieve_list[i] = False
# Iterate over the odd numbers
for i in range(3, number+1, 2):
if sieve_list[i] == True:
# i is prime and odd. Use i+i to only iterate over odd
# multiples of i.
for j in range(i*i, number+1, i+i):
sieve_list[j] = False
return sum([i for i in range(2, number+1) if sieve_list[i] == True])
if __name__ == '__main__':
print(sieve_of_eratosthenes(2000000)) |
486c39e524365c89da367029856ce6c5d6b09e54 | LucasAraujoBR/Python-Language | /pythonProject/Python Basic/aula8.py | 807 | 4.5625 | 5 | """
Aula 8 - Desafio prático
"""
"""
*Criar variáveis para nome(str), idade(int)
*altura(float) e peso(float) de uma pessoa
*cria variável com o ano atual (int)
*obtem o ano de nascimento da pessoa (baseado na idade e no ano atual)
*obtem o IMC da pessoa com 2 casas decimais (peso e na altura da pessoa)
*Exibir um texto com todos os valores na tela usando F-strings (Com as chaves)
"""
name = 'José Falcão de Almeida'
age = 38
weight = 120.5
height = 1.95
currentYear = 2021
yearOfBirth = currentYear - age
imc = weight/height**2
print(f"The year of {name}'s birth is {yearOfBirth}")
print(f'{name} is {height} tall and has {weight} KG, generating {imc:.2f} IMC.')
print(f'Name: {name} \nAge: {age} \nWeight: {weight} \nHeight: {height} \nCurrent Year: {currentYear} \nYear of Birth: {yearOfBirth} \nIMC: {imc:.2f}') |
ce809b5dd2842cd8e73ce3992bafcfd20db8198a | aenima1983/Dual-Heap-Sorting-Algorithm | /dualheapsort.py | 1,794 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 15:32:31 2019
¡prototype dual-heap sorting algorithm!
slight downfall: user must enter each value individually, which could
be impractical for very large arrays.
in the future, consider file parsing--taking an array directly from a file
and inputting it into the algorithm.
to feed the algorithm random values, uncomment lines 32-33 and comment
lines 30-31.
@author: cosmicchasm1983
"""
import timeit
import random
import sys
print(""" WELCOME TO THE SORTING ALGORITHM
RULES: INPUT A SIZE VALUE LARGER THAN 2
NO FRACTIONAL VALUES ALLOWED
""")
size = int(input("enter size of list to be sorted: "))
if (size < 3):
print('execute the program again, and input a size value larger than 2.')
sys.exit()
values = [] #initializing integral algorithm components
maxvalues = []
sorted_list = []
for i in range(0,size): #appending initial values
values.append(int(input(f'enter list value no. {i+1}: ')))
#for i in range(0,size):
# values.append(random.randint(0,1000))
timerstart = timeit.default_timer()
for i in range(0,int((size/2))+1):
if len(sorted_list) < (len(values) - 1): #boundaries
maxvalues.append(max(values)) #removing max values
values.remove(max(values))
sorted_list.append(min(values))
values.remove(min(values))
#lines 36-37 are the backbone of the conventional heap algorithm
for element in list(reversed(maxvalues)):
sorted_list.append(element) #layering sorted max values onto sorted mins
timerend = timeit.default_timer()
elapsed = timerend - timerstart #rough method of deriving the amount of time taken
print(sorted_list) #et voila
print('successfully sorted.')
print(f'\nprocess took {elapsed} seconds.')
|
ea34893d80aa2e03b9821b43b7f4cc0dde0dd126 | Pollack72/2021-1-Algorithm-Study | /week3/Group9/boj4779_pollack72.py | 241 | 3.609375 | 4 | data = []
while True:
try:
data.append(int(input()))
except:
break
def Cantor(n):
if n == 0:
return '-'
else:
return Cantor(n-1)+' '*(3**(n-1))+Cantor(n-1)
for i in data:
print(Cantor(i)) |
f83a718a8e46f56888a98987c9a12ec75a3e1d6a | razmanika/My-Work-Python- | /Udemy/UdemyTest.py | 2,419 | 4.21875 | 4 | '''
### 43(lecture) ###
*args and **kwargs
'''
'''
print(issubclass(C, A))
print(issubclass(C, B)) ვამოწმებთ არის თუარა C a და b კლასების შვილობილი
'''
'''
### 49(lecture) ###
Map Filter Lambda
'''
## MAP Function 49(lecture) ##
# def square(mystring):
# if len(mystring) % 2 == 0:
# return 'EVEN'
# else:
# return mystring[0]
# name = ['Andy','Eve','Sally']
# print(list(map(square,name) ))
# def square(nums):
# return nums ** 2
# number = [1,2,3,4,5]
# for i in map(square,number):
# print(i)
# ##############################
# # filter Function ##
# def check_even(number):
# return number % 2 == 0
# my_nums = [1,2,3,4,5,6]
# # print(list(map(check_even,my_nums))) # or # for num in filete(check_even,my_nums):
# #print(n)
# square = lambda num: num ** 2 #gamoiyeneba martivi operaciebistvis
# print(square(3))
# print(list(map(lambda num:num**2,my_nums))) # rodesac gvinda cvladis ricxvebi davakavshirot
# print(list(filter(lambda number:number**2,my_nums))) # lambdashi gapiltvra cvladis ricxvebis
# print(list(map(lambda Fname:Fname[0],name)))
'''
#### 50 #####
NESTED and SCOPE
'''
# x = 25
# def printer():
# x = 50
# return x
# print(x)
# print(printer())
#lambda num:num**2:
#GLOBAL
# name = " THIS IS A GLOBAL STRING "
# def greet():
# #ENCLOSING
# #name = "Sammy"
# def Hello():
# #LOCAL
# #name = "IM A LOCAL"
# print("hello " + name)
# Hello()
# greet()
# x = 50
# def func(x):
# global x
# print(f"x IS {x}")
# #LOCAL REASSIGMENT!
# x = 200
# print(f"I JUST LOCALLY CHANGED X TO {x}")
# func(x)
# my_list = [1,2,3,4,5,6,7,9,10,11,12,13,14,15,16,17,18,19,20]
# d = {}
# list_key = []
# list_value = []
# for key in my_list:
# if key % 2 == 0:
# list_key.append(key)
# else:
# list_value.append(key)
# for i in list_key:
# d[i]
# for z in list_value:
# d = z
# print(d)
|
90cdf0e7902c1b7e34fe103b91a912699f9a3319 | tashakim/puzzles_python | /mruQueueDesign.py | 658 | 4.09375 | 4 | class MRUQueue:
"""
Purpose: Design a MRU (Most-Recently-Used) Queue.
Brute force
"""
def __init__(self, n: int):
"""
Purpose: Constructs the MRUQueue with n elements: [1, 2, ..., n]
"""
self.data = [x for x in range(1, n+1)]
def fetch(self, k: int) -> int:
"""
Purpose: Moves the k-th element (1-indexed) to the end of the queue,
and returns it.
"""
elm = self.data[k-1]
self.data.pop(k-1)
self.data.append(elm)
return elm
# Your MRUQueue object will be instantiated and called as such:
# obj = MRUQueue(n)
# param_1 = obj.fetch(k) |
4ba44d24bee72d561da282fc3c487772a0eb5b3a | motleytech/crackCoding | /linkedLists/palindrome.py | 966 | 4.09375 | 4 | '''
check if a list is a palindrome
'''
from llist import LinkedList
def isPalindrome(lst):
'''
return true if lst is a palindrome
'''
nodes = list(lst)
for x, y in zip(nodes, reversed(nodes)):
if x.data != y.data:
return False
return True
def isPalin2(lst, curr):
'''
return True, None if lst is a palindrome
'''
if curr.next is None:
return (curr.data == lst.data, lst.next)
res, node = isPalin2(lst, curr.next)
if not res:
return (False, None)
return (node.data == curr.data, node.next)
def test_isPalindrome():
'''
test for isPalindrome methods
'''
lst = LinkedList()
lst.add(1).add(2).add(3)
assert not isPalindrome(lst)
assert not isPalin2(lst.head, lst.head)[0]
lst.add(2).add(1)
assert isPalindrome(lst)
assert isPalin2(lst.head, lst.head)[0]
print 'Test Passed.'
if __name__ == '__main__':
test_isPalindrome()
|
c62c60779616e7cad892e205e92be1cc71cc5d1d | jacobgarrison4/Python | /p21_sqrt.py | 2,043 | 4.28125 | 4 | """
Square Root
CIS 210 F17 Project 2
Authors: Jacob Garrison
Credits: Python Programming in Context
Approximate sqrt of a given number with iterative function
"""
from math import *
def mysqrt(n, k):
"""(int, int) -> float
Returns an approximation of the square root
of a givven number after a given number
of iterations through a function.
>>> mysqrt(25, 5)
5.000023178253949
>>> mysqrt(25, 10)
5.0
>>> mysqrt(10000, 10)
100.00000025490743
"""
value = 1
for x in range( 1 , k + 1 ):
value = ( ( 1 / 2 ) * ( value + ( n / value ) ) )
return value
def sqrt_compare(num, iterations):
"""(int, int) -> int
Calls mysqrt function to find square root
through a function and compares it to
the math lib sqrt value and returns a
percdentage error.
>>> sqrt_compare(10000, 8)
For 10000 using 8 iterations:
mysqrt value is: 101.20218365353946
math lib sqrt value is: 100.0
This is a 1.2 percent error.
"""
MyValue = mysqrt(num, iterations)
CompValue = sqrt(num)
error = round( ( ( abs( CompValue - MyValue ) / CompValue) * 100 ), 2 )
print( "For ", num, "using ", iterations, "iterations:\nmysqrt value is: ",
MyValue, "\nmath lib sqrt value is: ", CompValue, "\nThis is a ",
error, "percent error.")
return None
def mysqrtp(n, precision):
"""(int, float) -> tuple
Takes a number to find the sqrt of and
a precision point. Returns the sqrt and the
number of iterations it takes to reach
the given precision.
>>> mysqrtp(125348, .01)
(354.04519491839494, 13)
"""
iterations = 1
MyValue = mysqrt(n, iterations)
p = ( ( abs( ( round( MyValue, 2 ) ** 2 ) - n ) ) / n ) * 100
while p > precision:
iterations += 1
MyValue = mysqrt(n, iterations)
p = ( ( abs( ( round( MyValue, 2 ) ** 2 ) - n ) ) / n ) * 100
return MyValue, iterations
|
5911669e869de0be34679f73c7d67874240ac5fb | cathyq/practice-code-a-day | /diagonal_difference.py | 378 | 3.6875 | 4 | #!/bin/python
# Given a square matrix NxN, calculate the absolute difference between the sums of its diagonals.
# This problem is from hackerrank.
import sys
n_row = 3
a = [[11,2,4], [4,5,6], [10,8,-12]]
primary = 0
secondary = 0
for i in range(n_row):
primary += a[i][i]
for j in range(n_row):
secondary += a[j][n_row-j-1]
print abs(primary - secondary) |
f2bd313a5e5eec61504dc02107744b3b7dc027ea | SoksanSerey/bootcamp | /sereysoksan16/week01/projects/01_dice.py | 843 | 4.28125 | 4 | import random
dice = [1, 2, 3, 4, 5, 6]
result = 0
print('Welcome to the dices game!')
while 1:
number_dices = input('Enter the number of dices you want to roll: ')
if number_dices.isdigit() and (1 <= int(number_dices) <= 8):
number_dices = int(number_dices)
if number_dices == 1:
dice_value = random.choice(dice)
print('RESULT: ' + str(dice_value))
elif number_dices > 1:
for i in range(0, number_dices):
dice_value = random.randrange(1, 7)
result = result + dice_value
print('Dice ' + str(i+1) + ': ' + str(dice_value))
print('==========')
print('RESULT: ' + str(result))
print('==========')
else:
print('USAGE: The number must be between 1 and 8')
continue
break
|
a499758ec1960d4b3762183e63925c5399238a9f | anax-code/Estudos | /Scripts/Python/URI/1010.py | 507 | 3.71875 | 4 | linha1 = input().split()
p1 = int(linha1[0])
n1 = int(linha1[1])
v1 = float(linha1[2])
linha2 = input().split()
p2 = int(linha2[0])
n2 = int(linha2[1])
v2 = float(linha2[2])
valor = (n1*v1)+(n2*v2)
print('VALOR A PAGAR: R$ {:.2f}'.format(valor))
#A função split() faz com que cada objeto digitado dentro da string seja separado pelo espaço
#ficando objetos indepedentes
#Em seguida foi colocado os valores das matrizes, de acordo com a posição que o objeto digitado se encontraria
#dentro da String |
a79806969e292cb7482e7d79083bcab5d4abca67 | ishankkm/pythonProgs | /progs/LengthLLArray.py | 353 | 3.5 | 4 | '''
Created on Nov 8, 2017
@author: ishank
'''
def solution(A):
if A[0] == -1: return 1
lenLL = 1
current = A[0]
for _ in xrange(1, len(A)):
if A[current] == -1: return lenLL + 1
else:
lenLL += 1
current = A[current]
return lenLL
A = [1,4,-1,2,3]
print solution(A) |
8e62a7a4c32952b62876e7eb0cb0a21e33396079 | rafaelperazzo/programacao-web | /moodledata/vpl_data/186/usersdata/269/108337/submittedfiles/volumeTV.py | 172 | 3.859375 | 4 | -*- coding: utf-8 -*-
v=int(input('digite: '))
t=int(input('digite: '))
for i in range(0,t,1):
ai=int(input('digite as trocas de volume: '))
v=v+(ai)
print(v) |
41c0fccd4f8fca878ff0ae0d6ea64dc039936173 | Nextc3/aulas-de-mainart | /Listas/Lista 7/q7.py | 548 | 3.546875 | 4 | '''
7.Dado um pais A, com 5.000.0000 de habitantes e uma taxa de natalidade de 3%
ao ano, e um pais B com 7.000.000 de habitantes e uma taxa de natalidade
de 2% ao ano. calcular e imprimir o tempo necessário para que a
população do pais A ultrapasse a população do pais B;
'''
paisA = 5000000
paisB = 7000000
ano = 0
while paisA < paisB:
paisB += (paisB * 0.02)
paisA += (paisA * 0.03)
print("Pais A")
print(paisA)
print("Pais B")
print(paisB)
ano += 1
print("O ano que o pais A alcançou o B foi: {}".format(ano)) |
f044d03a0dbcb53575b43cb35cf4787ba0ac65b9 | a-angeliev/Python-Fundamentals-SoftUni | /exame/05. Excursion Sale.py | 487 | 3.65625 | 4 | money = 0
sea_trips = int(input())
muntain_trips = int(input())
while (sea_trips !=0 or muntain_trips !=0):
a = input()
if a == 'sea' and sea_trips>0:
money = money + 680
sea_trips = sea_trips - 1
elif a == 'mountain' and muntain_trips>0:
money = money + 499
muntain_trips = muntain_trips -1
elif a =='Stop':
break
if sea_trips== 0 and muntain_trips ==0:
print(f"Good job! Everything is sold.")
print(f"Profit: {money} leva.")
|
181ebf7fc0f2ec161224addd5685fd4ff2f806f4 | kommisar5150/assembler | /InstructionForms.py | 2,605 | 3.609375 | 4 | #!/usr/bin/env python
"""
This file contains all potential states of an instruction. The parser gathers info about the instruction and arguments.
The arguments are identified as either registers, immediate values, flags, or width. These idenfitications are then
concatenated together as a "state" string. Because instructions may contain multiple forms, these states ensure that
each instruction code is unique for each form.
Ex: MOV $A $B is of the form Instruction - Register - Register. In this scheme, it would be "State 2".
MOV could also be Instruction - Immediate - Register, so within the STATE2 list, the MOV entry has the correct
binary value that we need for this line of code.
"""
# INS
STATE0 = [("RET", 0b11110000, 1), ("ACTI", 0b11110001, 1), ("DACTI", 0b11110010, 1), ("HIRET", 0b11110011, 1),
("NOP", 0b11111111, 1)]
# INSREG
STATE1 = [("CALL", 0b01110010, 2), ("INT", 0b10000011, 2), ("NOT", 0b01110000, 2), ("POP", 0b01110100, 2),
("PUSH", 0b01110011, 2), ("SIVR", 0b01110101, 2), ("SNT", 0b01110001, 2)]
# INSREGREG
STATE2 = [("ADD", 0b10010010, 2), ("AND", 0b10010111, 2), ("CMP", 0b10011010, 2), ("DIV", 0b10010101, 2),
("MOV", 0b10011011, 2), ("MUL", 0b10010100, 2), ("OR", 0b10011000, 2), ("SHL", 0b10010110, 2),
("SHR", 0b10011001, 2), ("SUB", 0b10010011, 2), ("XOR", 0b10010000, 2)]
# INSIMM
STATE3 = [("CALL", 0b10000010, 5), ("INT", 0b01110110, 5), ("PUSH", 0b10000001, 5), ("SNT", 0b10000000, 5)]
# INSIMMREG
STATE4 = [("ADD", 0b01100110, 6), ("AND", 0b01100001, 6), ("CMP", 0b01101000, 6), ("MOV", 0b01100000, 6),
("OR", 0b01100010, 6), ("SHL", 0b01100101, 6), ("SHR", 0b01100100, 6), ("SUB", 0b01100111, 6),
("XOR", 0b01100011, 6)]
# INSWIDTHIMMIMM
STATE5 = [("MEMW", 0b00110000, 10)]
# INSWIDTHIMMREG
STATE6 = [("MEMR", 0b00000001, 6), ("MEMW", 0b00000000, 6)]
# INSWIDTHREGIMM
STATE7 = [("MEMW", 0b00100000, 6)]
# INSWIDTHREGREG
STATE8 = [("MEMR", 0b00010000, 3), ("MEMW", 0b00010001, 3)]
# INSFLAGIMM
STATE9 = [("JMP", 0b01000001, 6), ("JMPR", 0b01000000, 6), ("SFSTOR", 0b01000010, 6)]
# INSFLAGREG
STATE10 = [("JMP", 0b01010001, 2), ("JMPR", 0b01010000, 2), ("SFSTOR", 0b01010010, 2)]
INSTRUCTION_LIST = ["ACTI", "ADD", "AND", "CALL", "CMP", "DACTI", "DIV", "HIRET",
"INT", "JMP", "JMPR", "MEMR", "MEMW", "MOV", "MUL", "NOP", "NOT", "NOP",
"OR", "POP", "PUSH", "RET", "SFSTOR", "SIVR", "SHL", "SHR", "SUB", "XOR"]
LABEL_INSTRUCTIONS = ["CALL", "JMP", "MOV", "PUSH"]
IDENTIFIER_LIST = [":", ".GLOBAL", ".DATAALPHA", ".DATANUMERIC", ".DATAMEMREF", ";"]
|
2e394c0a2e983a37bfca386c1d2fd78def4f523d | niksm7/March-LeetCoding-Challenge2021 | /Generate Random Point in a Circle.py | 1,354 | 4.40625 | 4 | '''
Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.
Implement the Solution class:
Solution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).
randPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].
Example 1:
Input
["Solution", "randPoint", "randPoint", "randPoint"]
[[1.0, 0.0, 0.0], [], [], []]
Output
[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]
'''
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
# Initializing the variables at class level
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
ang = random.uniform(0, 1) * 2 * math.pi
hyp = sqrt(random.uniform(0, 1)) * self.radius
adj = cos(ang) * hyp
opp = sin(ang) * hyp
return [self.x_center + adj, self.y_center + opp]
# Your Solution object will be instantiated and called as such:
# obj = Solution(radius, x_center, y_center)
# param_1 = obj.randPoint() |
c17fc4c50d3ab9135eea9c4cf63f99123d9d8e97 | ocewulf/scrapy | /lottery.py | 165 | 3.5 | 4 | from random import randint
balls = set()
while len(balls) < 7 :
red_ball = randint(1, 36)
balls.add(red_ball)
print(balls)
s = list(balls)
s.sort()
print(s) |
388417f6bcdd9c0fd97c21677ea5b522dc964d1f | yeulucay/python_algorithms | /sort_algorithms/selection_sort.py | 484 | 3.9375 | 4 | """
- O(n**2) worst case time complexity
- Find the smallest item in list and put it to the first sequence. Scan the rest in linear manner
- In place sort
"""
def selection_sort(list):
n = len(list)
for i in range(0, n-1):
min = i
for j in range(i+1, n):
if list[j] < list[min]:
min = j
list[i], list[min] = list[min], list[i]
return list
a = [14, 16, 11, 9, 34, 10 , 13, 14]
print(selection_sort(a))
|
2323f4b71d6ea608e702fd460410f12a9fb20b36 | llhbum/Problem-Solving_Python | /python-for-coding-test/팀 결성.py | 713 | 3.609375 | 4 | '''
INPUT
7 8
0 1 3
1 1 7
0 7 6
1 7 1
0 3 7
0 4 2
0 1 1
1 1 1
'''
def find_union(parent, x):
if parent[x] != x:
parent[x] = find_union(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
a = find_union(parent, a)
b = find_union(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
v, e = map(int, input().split())
parent = [0] * (v + 1)
for i in range(1, v+1):
parent[i] = i
for i in range(e):
bool ,a, b = map(int, input().split())
if bool == 0:
union_parent(parent, a, b)
elif bool == 1:
if find_union(parent, a) == find_union(parent, b):
print('YES')
else:
print('NO')
|
f1f0baed1a96dbdfefc49b071ed50e05d3669035 | thghu123/python-basic-example | /1109/ex1.py | 520 | 3.578125 | 4 | class myclass :
def __init__(self): #생성자
self.name ='' #초기화 : 오류 방지
def __del__(self): #소멸자 - 객체가 메모리 상에서 삭제될 때 호출
#할일 있을 때 쓰자.
self.name =''
def setName(self, n): #멤버 메서드 정의
self.name = n #self는 this, 초기화 부
#멤버 메서드 정의시 반도시 첫번째 인자는 현 객체의 레퍼런스인 self 넣어준다
def getName(self):
return self.name
|
5dd56def30c47f339c5cbd8ec88efc43393773b2 | folabi-masha/LicenseCountApp | /database.py | 3,381 | 3.75 | 4 | import sqlite3
class Database:
def __init__(self):
self.conn = sqlite3.connect("init.db")
self.cursor = self.conn.cursor()
def create_database(self):
return self.conn
def load(self):
products = """CREATE TABLE if not exists products (
product_id integer PRIMARY KEY AUTOINCREMENT,
product_name text NOT NULL UNIQUE,
allowance integer NOT NULL)"""
licenses = """CREATE TABLE if not exists active_licenses (
id integer PRIMARY KEY AUTOINCREMENT,
product_name text NOT NULL,
name text NOT NULL UNIQUE,
FOREIGN KEY (product_name) REFERENCES products(product_name))"""
self.cursor.execute(products)
self.cursor.execute(licenses)
# def default_selection(self):
# default_select = "INSERT OR IGNORE INTO products (product_name, allowance) VALUES ('Select Software', 0)"
#
# self.cursor.execute(default_select)
#
# self.conn.commit()
def add_software(self, software, allowance):
entry = (software, allowance)
add_product = "INSERT OR IGNORE INTO products (product_name, allowance) VALUES (?, ?)"
self.cursor.execute(add_product, entry)
self.conn.commit()
def add_user(self, software, user):
entry = (software, user)
add_product = "INSERT OR IGNORE INTO active_licenses (product_name, name) VALUES (?, ?)"
self.cursor.execute(add_product, entry)
self.conn.commit()
def show_licenses(self, software):
add_product = "SELECT * FROM products"
self.cursor.execute(add_product)
allowance = self.cursor.fetchall()
for sw in allowance:
if sw[1] == software:
default_allowance = sw[2]
return default_allowance
def show_software(self):
self.cursor.execute("SELECT product_name FROM products")
softwares = self.cursor.fetchall()
software_list = []
for sw in softwares:
software_list.append(sw[0])
return software_list
def show_users(self, software):
self.cursor.execute("SELECT * FROM active_licenses")
softwares = self.cursor.fetchall()
users = []
for sw in softwares:
if sw[1] == software:
users.append(sw[2])
return users
def remaining_licenses(self, software):
add_product = "SELECT product_name FROM active_licenses"
self.cursor.execute(add_product)
allowance = self.cursor.fetchall()
counter = 0
for sw in allowance:
if sw[0] == software:
counter += 1
return counter
def delete_user(self, name):
delete = (name,)
delete_user = "DELETE FROM active_licenses WHERE name = ?"
self.cursor.execute(delete_user, delete)
self.conn.commit()
def delete_software(self, software):
delete = (software,)
delete_user = "DELETE FROM active_licenses WHERE product_name = ?"
delete_software = "DELETE FROM products WHERE product_name = ?"
self.cursor.execute(delete_user, delete)
self.cursor.execute(delete_software, delete)
self.conn.commit()
|
c4c2206b9102fd3d7224828add43f8bc92ea7877 | vladi-dev/exercism | /python/word-count/wordcount.py | 224 | 3.90625 | 4 | # -*- coding: utf-8 -*-
import re
from collections import Counter
def word_count(str):
regexp = '\W|_'
return Counter(word for word in re.split(regexp, str.decode('utf-8').lower(), flags=re.UNICODE) if word != '')
|
76390c10b19dbb5e3c9c4163ff3663b99c27156f | sejin1996/pythonstudy | /ch03/function/03_function_return.py | 1,230 | 3.96875 | 4 | # 03_function_return
# 함수 정의 : 반환값이 있는 함수
# 반환값은 함수 호출 후 함수 내부 문장을 실행하고 실행된 결과를
# 함수를 호출한 지점으로 반환하는 값
# 함수정의
# 함수이름 : sum
# 함수 기능 : 사용자로부터 두개의 정수를 입력받아 / 더한결과/를 반환하는 함수
def sum():
num1 =int(input("정수 1 입력 :"))
num2 =int(input("정수 2 입력 :"))
return num1+num2 # 한개의 값을 반환
# 함수 호출 했을 때 결과가 반환되는 함수만 결과값이 호출 함수 이름 위치 반환되고
# 반환된 값을 변수에 저장해 출력해 볼 것
total = sum()
print("sum()함수를 호출해서 반환받은 값은 %d 입니다."%total)
print("sum()함수를 호출해서 반환받은 값을 바로 출력합니다. 그값은 %d 입니다." % sum())
# 반환 값이 없는 경우 변수에 저장하면?
def show():
print("안녕하세요") # return 문이 없는 함수
show()
result = show()
print(result) # none
print(show()) # None
# 반환값이 없는데 변수에 저장하거나 함수 호출 결과를 출력하라고 하면 => None 이 저장되거나 출력
|
f701d3dd552f4d8ed27b52872713aa9946509b1a | ananyaarv/Python-Projects | /InsertNumberonBoard/main.py | 516 | 3.84375 | 4 | # Name: Ananya Arvind
# Date: 3/12/2021
# Period: 8
# Activity: Lab 2.05
a=input("Select a spot on the board to change:")
print("Instead of the number you chose, there will be an X on the spot.")
b=['1', '2', '3']
c=['4', '5', '6']
d=['7', '8', '9']
a=int(a)
if (a==1):
b[0] = 'X'
elif (a==2):
b[1] = 'X'
elif (a==3):
b[2] = 'X'
elif (a==4):
c[0] = 'X'
elif (a==5):
c[1] = 'X'
elif (a==6):
c[2] = 'X'
elif (a==7):
d[0] = 'X'
elif (a==8):
d[1] = 'X'
elif (a==9):
d[2] = 'X'
print(b)
print(c)
print(d) |
48ce5011eff8b6a93965bcbbb16afcb0842ec01f | shashank-shark/numpy-experiments | /BasicPixels/DrawCrossOneNature.py | 527 | 3.65625 | 4 | from scipy import misc
import matplotlib.pyplot as plt
# read the image
imageHere = misc.imread ('nature.jpg')
# get the max ranges of pixels in x * y
xmax = imageHere.shape[0]
ymax = imageHere.shape[1]
print (xmax)
print (ymax)
# use the iterator object of numpy
imageHere [range(xmax), range(ymax)] = 0
imageHere [range(xmax - 1, -1, -1), range (ymax - 1, -1, -1)] = 0
# for let-top to right-bottom image
# for i in range(xmax):
# for j in range(ymax):
# imageHere[i,j] = 0
plt.imshow (imageHere)
plt.show() |
be83b6f5e9c2c4cdbc86ba5177e1dc129e22b337 | SHAZAM3107/FOSS-TASKS | /MEDIUM/cli.py | 1,129 | 3.828125 | 4 | from PIL import Image
availableitems=['asus zenfone','honor 7a','samsung galaxy s9','oppo f9','vivo v11']
price=['10000','11000','9000','50000','15000']
price=list(map(int,price))
print("the cost of each items are listed below respectively")
print(availableitems)
print(price)
n=int(input("how many products do you want to buy? "))
c=[]
while (len(c)!=n):
citems=input("enter product ")
c.append(citems)
s=0
for i in range(0,n):
if (c[i]==availableitems[0]):
s=s+price[0]
elif (c[i]==availableitems[1]):
s=s+price[1]
elif (c[i]==availableitems[2]):
s=s+price[2]
elif (c[i]==availableitems[3]):
s=s+price[3]
elif (c[i]==availableitems[4]):
s=s+price[4]
print("proceeding to checkout...")
print("the total amount payable is "+str(s))
x=input("do you have any coupon? ")
if x=="yes":
s=s-(s*0.04)
print("the total amount payable after discount is "+str(s))
else:
print("the total amount payable after discount is "+str(s))
print("Choose a payment option:\n1)credit card\n2)debit card\n3)net banking")
img=Image.open("1.jpg")
img.show()
img.close()
|
1d185ca9c81fb101d939d3dca26a423e85dffebe | ZASXCDFVA/LeetCodeAns | /letter-combinations-of-a-phone-number.py | 680 | 3.640625 | 4 | from typing import List
class Solution:
def __init__(self):
self._map_of = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def _append(self, result: List[str], prefix: str, current: str):
if current == "":
if prefix != "":
result.append(prefix)
return
for c in self._map_of[int(current[0]) - 2]:
self._append(result, prefix + c, current[1:])
def letterCombinations(self, digits: str) -> List[str]:
result: List[str] = []
self._append(result, "", digits)
return list(result)
if __name__ == '__main__':
print(Solution().letterCombinations("23"))
|
d3167dc953dcc731c9947fb5e838e495f3981dd3 | aklgupta/pythonPractice | /Q15 - countdown/countdown.py | 376 | 4.0625 | 4 | """Q 15 - Countdown
Input a integer N from user
Print numbers N to 0 in a single line, however, each number should be printed at an interval of 1 second.
eg.
Input: 5
Output: 5 4 3 2 1 0
(The output is generated over a time of 5 seconds, printing one number per second)
"""
import time
N = input("Enter a number: ")
for i in xrange(N, -1, -1):
print i,
time.sleep(1)
|
4c5b379b50a8e814e1e608140d1ae3bade9d4ce2 | Fragilegod/LinearRegression | /LinearRegression.py | 1,553 | 3.765625 | 4 | import matplotlib.pyplot as plt
learning_rate_ALPHA = float(0.0001)
initial_theta_0 = float(0)
initial_theta_1 = float(0)
nombre_iterations = 2000
X=[i for i in range(3000)]
Y=[2*i for i in range(3000)]
M=len(X)
def calc_derivatives(oldtheta_0, oldtheta_1):
derivtheta_0 = float(0)
derivtheta_1 = float(0)
for i in range(0, len(X)):
derivtheta_0 = float(((oldtheta_0 + (oldtheta_1 * X[i])) - float(Y[i])))
derivtheta_1 = (((oldtheta_0 + (oldtheta_1 * X[i]))) - float(Y[i])) * float(X[i])
derivtheta_0 = (1/M) * derivtheta_0
derivtheta_1 = (1/M) * derivtheta_1
return [derivtheta_0, derivtheta_1]
def calc_theta(oldtheta_0, oldtheta_1):
[derivtheta_0, derivtheta_1] = calc_derivatives(oldtheta_0,oldtheta_1)
newtheta_0 = oldtheta_0 - (learning_rate_ALPHA * derivtheta_0)
newtheta_1 = oldtheta_1 - (learning_rate_ALPHA * derivtheta_1)
return [newtheta_0,newtheta_1]
def gradient_descent():
theta_00 = initial_theta_0
theta_11 = initial_theta_1
for i in range(nombre_iterations):
[newtheta_0, newtheta_1] = calc_theta(theta_00, theta_11)
theta_00 = newtheta_0
theta_11 = newtheta_1
return [theta_00, theta_11]
[final_theta_0, final_theta_1] = gradient_descent()
print ("theta_0 = {0}, theta_1 = {1}".format(final_theta_0, final_theta_1))
Y1=[2*i for i in range(3000)]
for i in range(3000):
Y1[i]= final_theta_0 + final_theta_1 * X[i]
axes = plt.axes()
axes.grid()
plt.scatter(X,Y1, color = "m")
plt.plot(X, Y, color = "g")
plt.show()
|
460fc9175814d26f7d552ba0a46742a0a50892ff | Jonathan0137/Sokoban | /soundeffect.py | 1,045 | 3.5 | 4 | import json
import pygame
def soundEffect():
"""This is a function that plays the box moving sound when a box is pushed
"""
json_file = open("env.json", "r")
options_dict = json.load(json_file)
if(options_dict["sound_effects"] == "On"):
move_box_sound = pygame.mixer.Sound("box_moving.wav")
move_box_sound.play()
def soundVolumeCheck(sound_object):
"""This is a function that plays the button pressing sound when a button is pressed
Args:
sound_object (pygame.mixer): the sound
"""
json_file = open("env.json", "r")
options_dict = json.load(json_file)
if(options_dict["sound_effects"] == "Off"):
sound_object.set_volume(0)
else:
sound_object.set_volume(1)
def musicCheck():
"""Plays or stops music based on value stored in env.json
"""
json_file = open("env.json", "r")
options_dict = json.load(json_file)
if (options_dict["music"] == "Off"):
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1)
|
cd519634b477edc750ab62f974231c399e723152 | ycAngus2415/python_learning | /opp.py | 1,988 | 3.75 | 4 | class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s:%s' % (self.__name, self.__score))
def get_grade(self):
if self.__score >= 90:
return 'A'
elif self.__score >= 60:
return 'B'
else:
return 'C'
def get_name(self):
return self.__name
def get_score(self):
return self.__score
def set_score(self, score):
if 0 <= score <= score:
self.__score = score
else:
raise ValueError('bad score')
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
if 1915 <= value <= 2015:
self._birth = value
@property
def age(self):
return 2015 - self._birth
def __str__(self):
return 'Student object (name: %s)' % self.__name
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()
print(bart.get_grade())
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 running...')
dog = Dog()
dog.run()
cat = Cat()
cat.run()
print(type(dog))
import types
print(type(abs)==types.BuiltinFunctionType)
print(type(lambda x: x*x)==types.LambdaType)
print(x for x in range(10))
print(dir(dog))
def set_age(self, age):
self.age = age
from types import MethodType
#dog.set_age = MethodType(set_age, dog)#通过methodtype 给实例赋予方法
#dog.set_age(25)
#print(dog.age)
Animal.set_age = set_age
dog.set_age(22)
print(dog.age)
print(dir(Dog))
cat.set_age(19)
print(cat.age)#这东西能直接把方法传给类,然后各个实例都能用了。厉害
bart.birth = 2013
print(bart.birth)
print(bart.age)
print(bart)
|
8de30d1f17d5a3d05ca055b898160885d17fdd04 | deelaws/AlertWeb | /AlertWeb/threading_example.py | 437 | 3.5 | 4 | import threading
e = threading.Event()
threads = []
def runner():
tname = threading.current_thread().name
print('Thread waiting for event: %s' % tname)
e.wait()
print( 'Thread got event: %s' % tname)
for t in range(100):
t = threading.Thread(target=runner)
threads.append(t)
t.start()
input('Press enter to set and clear the event:')
e.set()
e.clear()
for t in threads:
t.join()
print( 'All done.') |
e05b0657015c2a1727df5104565a2cf210cc6142 | SeungHune/Programming-Basic | /과제 6/실습 6-3.py | 913 | 3.671875 | 4 | #행렬안에 중복된정수 여부(스도쿠)
def issudoku(mat):
matlist = []
size = len(mat)
for i in range(size):
for j in range(size):
matlist.append(mat[i][j])
matlist = sorted(matlist)
while (matlist != []):
if len(matlist) == 1:
break
if (matlist[0] == matlist[1]):
return False
else:
matlist = matlist[1:]
return True
matt = [[ 1, 2, 3, 4],
[ 8, 7, 6, 5],
[ 9, 10, 11, 12],
[16, 15, 14, 13]]
mat = [[1, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 1, 0, 1]]
ma = [[ 1, 9, 5, 11],
[ 9, 4, 7, 3],
[ 5, 7, -7, 8],
[11, 3, 8, 6]]
mattt = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]]
print(issudoku(matt))
print(issudoku(mat))
print(issudoku(ma))
print(issudoku(mattt))
|
98cae0ea82f3c50f23bcfd80ef82c5f1530103d2 | WYC15822755124/spiders | /re_test2.py | 336 | 3.640625 | 4 | #encoding: utf-8
import re
#r = raw =原生的
# text = "apple price is $299"
# ret = re.search("\$\d+",text)
# print(ret.group())
text = "\\n"
#= '\n'
#python : '\\n' = \n
#\\\\n-> \\n
#正则表达式中:\n=
#\\n->\n
# ret = re.match('\\\\n',text)
# print(ret.group())
text = "\\n"
ret = re.match(r'\\n',text)
print(ret.group()) |
d57bc13fd4d6755cc804d1171d7bce32a1eb3dfe | karasatishkumar/python-practice | /day3/loop.py | 324 | 3.546875 | 4 | datlst = [
"10-nov-2020",
"15-dec-2010",
"5-apr-1998",
"31-dec-1990"
]
for cursor in datlst:
print("%s - %s" %(cursor.split("-")[1], cursor.split("-")[1][0].upper()))
res = [cursor.split("-")[1] + " - " + cursor.split("-")[1][0].upper() for cursor in datlst]
print(res) |
d96d60079e6c15649f0075d3bf45919c98b86082 | ASzczesna/Python-1M | /script5.py | 214 | 3.5625 | 4 | napis = "wiek "+str(18)
print napis
print napis.replace('w','W')
print napis.lower()
print napis.upper()
nap = "ta liczba %f to %s" % (3.14, "licz")
print nap
print '{0}, {1}, {2}'.format('a','b','c') |
163d96671f43f0dea118ea6693473e20cba81157 | krusovaa/UdP_cviceni | /kd_tree.py | 1,030 | 3.71875 | 4 | from point_generator import random_square, circle
N_POINTS = 100
sq = random_square(N_POINTS)
def kd_tree(points, axis):
axis = 'x' or 'y'
# if len(points) = 1, only print point and return
if len(points) == 1:
print(points)
return
# sort points according to axis
if axis == 'x':
points.sort(key=lambda p: p[0]) # x axis, prvni clen ntice = x, pred dvojteckou je seznam parametru, za veci, ktery vraci
if axis == 'y':
points.sort(key=lambda p: p[1]) # y axis, druhy clen ntice = y
# def sort_x(point):
# return point[0]
# points.sort (key = sort.x)
# split points to two halves
# find and print coordinate of the middle point
# print each half
mid = len(points)//2
points_0 = points[:mid+1]
points_1 = points[mid+1:]
print(f"Axis: {axis}, before:{points_0}, after:{points_1}")
# recurse on each half
if axis == 'x':
kd_tree(points, 'y')
if axis == 'y':
kd_tree(points, 'x')
kd_tree(sq, 'x') |
ebae7cbaf9c2764e54dc5de60e7d38d8cdbaba7e | Dealead/Employee_Attrition | /Employee-Attrition.py | 4,259 | 4.0625 | 4 | """
An employee attrition data to predict the likelyhood of employee retention.
The following points should be noted:
(1) Since the data splits the employees into two: those who have left and existing employees,
It is necessary to first add an 'Attrition' column and then bring them together as one solid dataset.
This is done using the '.append()' method.
(2) There's need to visualize the data being described. Hence a chart is made and summary statistics.
(3) Categorical columns from the data are encoded
The Accuracy of the Trainng Model is about 99.8%
The confusion Matrix and Accuracy Score for the test data is about 99.2%
"""
####Importin the Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#### Adding the 'Attrition' Column Joining the datasets
d1 = pd.read_excel("C:/Users/mowab/Downloads/Hash-Analytic-Python-Analytics-Problem-case-study-1.xlsx",
sheet_name='Existing employees')
d1['Attrition'] = 'No'
print(d1)
d2 = pd.read_excel("C:/Users/mowab/Downloads/Hash-Analytic-Python-Analytics-Problem-case-study-1.xlsx",
sheet_name='Employees who have left')
d2['Attrition'] = 'Yes'
print(d2)
#### Joining the datasets Together
dataset = d1.append(d2)
print(dataset)
####Visualizing the Attrition data
sns.countplot(dataset['Attrition'])
plt.show()
# fig_dimensions = (120, 100)
# fig, ax = plt.subplot(figsize = fig_dimensions)
# sns.countplot(x = 'dept', hue = 'Attrition', data=dataset, palette='colorblind', ax=ax, edgecolor= sns.color_palette('dark', n_colors=1))
# plt.show()
##### Visualizing a summary of the columns
for column in dataset.columns:
if dataset[column].dtype == object:
print(str(column) + ' : ' + str(dataset[column].unique()))
print(dataset[column].value_counts())
print("\n ****************************************************** \n")
elif dataset[column].dtype == np.number:
print(dataset[column].value_counts())
print('\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
##### Dropping the 'Employee ID' column
dataset = dataset.drop('Emp ID', axis=1)
#### Visualizing the correlation between the columns
print("The Correlation between the columns are: \n")
print(dataset.corr())
##### Visualizing the Heatmap of the correlation
plt.figure(figsize=(9, 9))
sns.heatmap(dataset.corr(), annot=True, fmt='.0%')
plt.show()
#### Defining the dependent and Independent variables
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 9].values
print(y)
#### Importing preprocessing Libraries for encoding categorical data
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
col_tran = ColumnTransformer(transformers=[('one_hot_encoder', OneHotEncoder(categories='auto'), [7, 8])],
remainder='passthrough')
##### Encoding the independent variable and Dependent variabes
x = np.array(col_tran.fit_transform(x), dtype=np.float)
lab_en = LabelEncoder()
y = lab_en.fit_transform(y)
print(x)
print(y)
#### Spliting the data into training and Testing sets
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=5)
##### Fitting the training set with the Random Forest Classifier
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=10, criterion='entropy', random_state=0)
forest.fit(x_train, y_train)
#### Calculaing the Score
score = forest.score(x_train, y_train)
print(score)
"""
Showing the confusion matrix and accuracy for the model on the test data
Classification accuracy is the ratio of correct predictions to total predictions made.
"""
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, forest.predict(x_test))
aa = cm[0][0]
ab = cm[0][1]
ba = cm[1][0]
bb = cm[1][1]
cm1 = ((aa + bb) / (aa + ab + ba + bb)) * 100
print('\nThe Accuracy of the Model is : {}%!\n'.format(cm1))
from sklearn.metrics import accuracy_score
acc_score = accuracy_score(y_test, forest.predict(x_test))
print('\nThe Accuracy Score for the Model is : {}% '.format(acc_score * 100))
|
351843236f94624df661bd5480d6c5d789b78651 | qiubinbin/exercise | /@contextmanager.py | 465 | 3.734375 | 4 | """利用@contextlib.contextmanager和yield生成器实现上下文管理"""
import contextlib
@contextlib.contextmanager
def pp(m):
print('begin')
m += 1
yield m # 把传递给yield的值用作__enter__()方法的返回值
"""只有在with语句块执行未出现错误时才会执行下面的语句(可以使用finally代替)"""
print('end')
with pp(6) as temp:
try:
print(temp / 0)
except ZeroDivisionError:
pass
|
12b8f57b3dce0d8a3a369d4ae15ad128213d1b84 | Master-sum/pycharmfiles | /trim.py | 252 | 3.609375 | 4 | """
作者 :bjx
创建时间 :2020/8/24 11:04 下午
文件名称 :trim.PY
开发工具 :PyCharm
"""
def trim(s):
if s[:1] == ' ':
s = s[1:]
if s[-1:] == ' ':
s = s[:-1]
return len(s)
print(trim(" ncd "))
|
1c327c3fa8d8fda5e63e014715c5caf5e84cba29 | stimko68/daily-programmer | /challenge_anwers/159_intermediate.py | 5,119 | 4.25 | 4 | """
Rock Paper Scissors Lizard Spock - Part 2
The basic game as seen on The Big Bang Theory, plus a few
enhancements:
- Looping so the player can play more than once#
- Recording of win/tie/lose record of each player and the
number of games played#
- At the end of the game loop, display the stats from games
played and win/tie percentages#
- AI agent to make the game play harder for the player
- The AI agent will track each move the player makes and
then attempt to make a move that has a higher chance of
winning
"""
import operator, random
from collections import Counter
# Global variables
ai_counter_moves = {
'rock': ('spock', 'paper'),
'paper': ('scissors', 'lizard'),
'scissors': ('spock', 'rock'),
'lizard': ('rock', 'scissors'),
'spock': ('lizard', 'paper')
}
d = {
('paper', 'scissors'): 'cuts',
('spock', 'scissors'): 'smashes',
('paper', 'rock'): 'covers',
('rock', 'lizard'): 'crushes',
('lizard', 'spock'): 'poisons',
('lizard', 'paper'): 'eats',
('rock', 'scissors'): 'crushes',
('scissors', 'lizard'): 'decapitates',
('paper', 'spock'): 'disproves',
('spock', 'rock'): 'vaporizes'
}
play_again_choices = ['y', 'n']
result_tracking = {
'num_games': 0,
'user_wins': 0.0,
'comp_wins': 0.0,
'ties': 0.0
}
user_moves = []
valid_moves = ['scissors', 'paper', 'rock', 'lizard', 'spock']
def ai_guess():
"""
Given the global list of recorded user moves, this
function will find the most used move by the user
and return a valid counter move. For example, if the
user's most used move is 'rock', this function will
return either 'spock' or 'paper' since these are both
winning moves against 'rock.'
If the list is empty, then the function simply returns
a random choice from the list of valid moves.
"""
if len(user_moves) == 0:
return random.choice(valid_moves)
else:
u_moves = dict(Counter(user_moves))
u_max_move = max(u_moves.iteritems(), key=operator.itemgetter(1))[0]
return random.choice(ai_counter_moves[u_max_move])
def play_game():
"""
Calls the relevant functions that will ask the user
for their choice, store the choice in a list, grab
the computer's choice from the ai_guess() function,
and then call the show_results() function to display
the results of the game and determine the winner.
"""
user_choice = validate_input()
user_moves.append(user_choice)
comp_choice = ai_guess()
show_results(user_choice, comp_choice)
def show_results(user, comp):
"""
This function, given the move made by the user and
computer, will display the moves chosen by each
player and then determine which one wins based on
the combinations found in the global dict d.
"""
print("\n======= Results =======\n"
"User choice: {}\n"
"Computer choice: {}".format(user, comp))
if user == comp:
print("It's a tie!")
result_tracking['ties'] += 1
else:
try:
print "{} {} {}! User wins!".format(user.capitalize(), d[(user, comp)], comp)
result_tracking['user_wins'] += 1
except:
print "{} {} {}! Computer wins!".format(comp.capitalize(), d[(comp, user)], user)
result_tracking['comp_wins'] += 1
def show_summary():
"""
Calculates and prints summary information at the end of
gameplay, as chosen by the user. Stats returned include
the total number of games played, the user's and computer's
win percentages, and the tie percentage.
"""
user_w_per = float((result_tracking['user_wins'] / result_tracking['num_games']))
comp_w_per = float((result_tracking['comp_wins'] / result_tracking['num_games']))
tie_per = float((result_tracking['ties'] / result_tracking['num_games']))
print("\n======= Summary =======\n"
"Number of games played: {}\n"
"User win %: {:.0%}\n"
"Computer win %: {:.0%}\n"
"Tie %: {:.0%}".format(result_tracking['num_games'], user_w_per, comp_w_per, tie_per))
def validate_input():
"""
Asks the user for their move and validates whether or
not the input is one of the valid move choices. If not,
the user is asked again for their move until they enter
a valid choice.
"""
user_choice = raw_input('Choose a move: ').lower()
while user_choice not in valid_moves:
user_choice = raw_input('Invalid choice! Try again: ').lower()
return user_choice
if __name__ == "__main__":
game_over = False
print("Let's play Rock Paper Scissors Lizard Spock!")
play_game()
result_tracking['num_games'] += 1
while not game_over:
play_again = raw_input("\nWould you like to play again (y/n)? ")
while play_again not in play_again_choices:
play_again = raw_input("Invalid choice! Try again: ")
if play_again == 'y':
result_tracking['num_games'] += 1
play_game()
elif play_again == 'n':
show_summary()
game_over = True |
ec34bf799daa12ddc46d40e8d2edb308b018c53e | LucaCappelletti94/crr_labels | /crr_labels/utils/normalize_cell_lines.py | 500 | 3.75 | 4 | from typing import List
def normalize_cell_lines(cell_lines: List[str]) -> List[str]:
"""Return normalized cell lines.
Currently, the only normalization procedure is to convert the cell lines
to uppercase.
Parameters
----------------------
cell_lines: List[str],
The list of the cell lines.
Returns
----------------------
List of the normalized cell line names.
"""
return [
cell_line.upper()
for cell_line in cell_lines
]
|
a7bbd057d47cd7e2d3c7f54b6395ecec0e6eb2d7 | surjitchoudhary/hellogit | /second.py | 768 | 4.28125 | 4 | var1='hello'
var2=10
var3=12.4
#check the type of variables in python3 'str'=string,int=integer, float=decimal value
print(type(var1))
print(type(var2))
print(type(var3))
#we are here to check what kind of type does input BYDEFAULT TAKE
a=input('Bydefault str')
b=int(input('Enter integer value'))
c=float(input('Enter float value'))
d=str(input('Enter string '))
print(type(a))
print(type(b))
print(type(c))
print(type(d))
#multiplying a string to an interger will print number of integer times the string.
"""Point to note here is float can't we multiplied by string it will give error if you want to try."""
print(a*b)
#Now we try string multiply by string
print(a*d)
#above equation will produce error Typeerror:can't multiply sequence by non-int of type 'str'.
|
e07c374a627647f939853f2dbc9dc2dd4176c0d0 | pruthvipatnala/CalendarApp | /calendar_app.py | 2,265 | 3.65625 | 4 | """
Calendar
"""
import calendar
import datetime as dt
import sys
import re
import subprocess
def display_calendar(month_offset=0):
"""
Function to display calendar with current date highlighted
"""
if month_offset > 12 or month_offset < -12:
print("The application does not handle offsets greater than 12 or less than -12")
return None
# Todays's Date
today = dt.datetime.today()
final_month = today.month + month_offset
final_year = today.year
if final_month < 1:
final_month = 12 + final_month
final_year = final_year - 1
elif final_month > 12:
final_month = final_month - 12
final_year = final_year + 1
# create HTML Calendar month
cal = calendar.HTMLCalendar()
html_string = cal.formatmonth(final_year, final_month)
css = "<style> table {\
width: 100%;\
height: 100%;\
}</style>"
# ss = s.replace('>%i<'%t.day, ' bgcolor="#66ff66"><b><u>%i</u></b><'%t.day)
pat = re.findall(r">\d+", html_string)
for i in pat:
number = i[1:]
html_string = html_string.replace(i, ' style="text-align:center">'+number)
html_string = html_string.replace('>%i<'%today.day, 'bgcolor="#34C420"><b>%i</b><'%today.day)
final_html = "<html>"+css+"<body>"+html_string+"</body>"+"</html>"
# Creating HTML file used by GUI
with open('calendarApp.html', 'w') as html_file:
html_file.write(final_html)
# Opening the GUI in background
subprocess.Popen(["pythonw", "calendar_gui.py"])
return None
if __name__ == '__main__':
# Initialize parser
HELP_MESSAGE = "Project developed by -- \n\
Name: Prudhvi Raj Patnala\n\
Email: [email protected]\n\
**************************\n\
Usage Info -- \n\
Command - python calendarApp.py <int:month_offset>"
try:
if sys.argv[1] == '-h' or sys.argv[1] == '--help':
print(HELP_MESSAGE)
elif int(sys.argv[1]) or int(sys.argv[1]) == 0:
display_calendar(int(sys.argv[1]))
except IndexError:
print(HELP_MESSAGE)
display_calendar()
except ValueError:
print("Use a number between -12 to +12 as month_offset")
|
229e31e98acff077faf521f789f23a9796f19d46 | BRIANHG89/Python-Exercises- | /condicionalcompuesta/validatresdigitos.py | 366 | 3.90625 | 4 |
#ingrese un valor de hasta tres digitos positivos
num=int(input("Ingrese un valor de hasta tres digitos positivos"))
if num<10:
print("Tiene un digito")
else:
if num<100:
print("Tiene dos digitos:")
else:
if num<1000:
print("Tiene tres digitos")
else:
print("Error en la entrada de datos.")
|
ac00eff9f1fe52b8ce22168dd2b48b52e6ce4ec5 | kavi707/pythod_examples | /calculator.py | 1,049 | 4 | 4 | def add(a, b):
return a+b
def substract(a, b):
return b-a
def multiply(a, b):
return a*b
def divide(a, b):
if b == 0:
return "Syntax Error"
else:
return a/b
def getInputs():
print " "
print " "
print "Welcome to calculator from python"
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
return input ("Choose your option: ")
loop = 1
choice = 0
r = 0
while loop == 1:
choice = getInputs()
if choice == 1:
r = add(input("Add this: "), input("to this: "))
print "Added Result:", r
elif choice == 2:
r = substract(input("Substract this: "), input("from this: "))
print "Substract Result:",r
elif choice == 3:
r = multiply(input("Multiply this: "), input("from this: "))
print "Multiplied Result:",r
elif choice == 4:
r = divide(input("Divide this: "), input("from this: "))
print "Divided Result:",r
elif choice == 5:
loop = 0
else:
print "Error input"
|
7381fdadafc61c72fdeedac352958550de715060 | linminhtoo/Pentago | /game.py | 5,174 | 3.90625 | 4 | import numpy as np
from typing import List, Optional
class Game:
def __init__(self, num_humans: int, game_size: int, win_length: int,
first_player: str, sec_player: str,
level: Optional[int]=None):
self.num_humans = num_humans
self.game_size = game_size
self.win_length = win_length
self.first_player = first_player
self.sec_player = sec_player
self.level = level # will be 1 or 2 only if computer is playing, otherwise None
self.game_board = np.zeros((self.game_size, self.game_size))
self.turn = 1 # counter for turn, see self.increment_turn()
self.turn_to_name = {
1 : first_player,
2 : sec_player
} # keep track of player name and order of player, see self.increment_turn()
self.state = 0 # 0 = game is running, 1 = player 1 wins, 2 = player 2 wins, 3 = tie, 4 = quit
self.state_full = 'Game is running!'
def update_state(self, new_state: int):
''' Also see: self.check_victory()
'''
self.state = new_state
if self.state == 1:
self.state_full = f'{first_player} has won!'
elif self.state == 2:
self.state_full = f'{sec_player} has won!'
elif self.state == 3:
self.state_full = "It's a tie!"
else:
raise ValueError('Error! self.state is not 1, 2, or 3, and yet the game is still running... Please debug!')
def increment_turn(self):
''' Alternates value of self.turn between 1 and 2 every time this is run.
Run once at the end of every turn, from main().
'''
self.turn %= 2
self.turn += 1
print(f"It's {self.turn_to_name[self.turn]}'s turn'")
def apply_move(self, row: int, col: int, rot: int):
''' To implement!!!
This function's role is to apply a player’s move to the game_board. The parameters are:
game_board: the current game board
turn: 1: player 1’s turn to play; 2: player 2’s turn to play
row: the row index to place marble
col: the col index to place marble
rot:
1: rotate the first quadrant clockwise at 90 degree
2: rotate the first quadrant anticlockwise at 90 degree
3: rotate the second quadrant clockwise at 90 degree
4: rotate the second quadrant anticlockwise at 90 degree
5: rotate the third quadrant clockwise at 90 degree
6: rotate the third quadrant anticlockwise at 90 degree
7: rotate the fourth quadrant clockwise at 90 degree
8: rotate the fourth quadrant anticlockwise at 90 degree
It will return the updated game_board after applying player’s move.
'''
pass
def check_victory(self):
''' To implement!!!
This function’s role is to check the current situation of the game after one of the players has made a move
to place marble and rotate quadrant.
The meaning of the parameters to this function are:
game_board: the current game board
turn: 1: player 1’s turn to play; 2: player 2’s turn to play
in other word, when it is called, game_board, turn, and rot are passed in. It will return an integer:
0: no winning/draw situation
1: player 1 wins
2: player 2 wins
3: game draw
Also see: self.update_state()
'''
# new_state is the output of this class function (0, 1, 2, or 3)
self.update_state(new_state)
pass
def check_move(self, row: int, col: int):
''' To implement!!!
This function's role is to check if a certain move is valid. The parameters are:
game_board: the current game board
row: the row index to place marble
col: the col index to place marble
If a place defined by row and col is occupied, the move is invalid, otherwise, it is valid.
This function will return True for a valid move and False for an invalid move.
'''
pass
def computer_move(self):
''' To implement!!!
This function is to generate computer move. The parameters are:
game_board: the current game board
turn: 1 or 2 depending on whether computer to play first or secondly.
level: the strategy of computer player
1. computer play in a random placing style
2. computer can search possible positions and analyse the game_board to find a good move to win (Option!)
The function returns three values: row, col, and rot.
'''
# check level 1 or 2, then carry out the appropriate move
# better idea is to set this to random or recursive search at self.__init__()
# i.e. define self.computer_random() & self.computer_recursive()
def display_board(self):
print('\n') # new line, for cleaner printing
print(self.game_board) |
161e1ababdf6db57f495b821aaad1681c2f81a47 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/dsxriy002/question3.py | 1,323 | 4.09375 | 4 | #Riya Desai
#Assignment 9 - Question 3
#15 May 2014
sudokugame = [ ]
check = True
#keep adding numbers to the grid
for i in range(9):
sudokugame.append(input())
grid = [ ]
for i in range(9):
grid.append(sudokugame[i][0:3])
for i in range(9):
grid.append(sudokugame[i][3:6])
for i in range(9):
grid.append(sudokugame[i][6:9])
#set i = 0
i=0
while(i<len(grid)):
grid[i]=grid[i]+grid[i+1]+grid[i+2]
grid.remove(grid[i+1])
grid.remove(grid[i+1])
i=i+1
#create the colums of the sudokugame
columns = [[],[],[],[],[],[],[],[],[]]
#add numbers to the grid (max 9)
for i in range(9):
for j in range(9):
columns[i].append(sudokugame[j][i])
#find all conditions where grid is NOT valid
for i in range(9):
for j in range(9):
if(grid[i].index(grid[i][j])!=j):
check= False
for i in range(9):
for j in range(9):
if(columns[i].index(columns[i][j])!=j):
check=False
for i in range(9):
for j in range(9):
if(sudokugame[i].index(sudokugame[i][j])!=j):
check=False
#print statements relating to the "check" to see whether grid was valid or not
if(check):
print("Sudoku grid is valid")
else:
print("Sudoku grid is not valid") |
a6eeafe205707290647075bb74754cf78a550554 | PrithviSathish/School-Projects | /ListSort.py | 1,008 | 3.671875 | 4 | # Maximum and Minimum
n = int(input("Enter the value: "))
L = []
for i in range(n):
print('Enter L[',i,']: ')
L += [int(input())]
print("Original List: ", str(L))
L2, L3 = list(L), list(L)
ch = 0
while ch != 5:
print("\n1. Maximum Value\n2. Minimum Value\n3. Ascending Order\n4. Descending Order\n5. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
max = L[0]
for i in range(1, n):
if max < L[i]:
print(i)
max = L[i]
print("Maximum Value: ", str(max))
elif ch == 2:
min = L[0]
for i in range(1, n):
if min > L[i]:
min = L[i]
print("Minimum Value: ", str(min))
elif ch == 3:
for i in range(n):
t = i
for j in range(i + 1, n):
if L2[t] > L2[j]:
t = j
L2[i], L2[t] = L2[t], L2[i]
print("Ascending order: ", str(L2))
elif ch == 4:
for i in range(n):
for j in range(0, n - 1):
if L2[j] < L2[j + 1]:
L2[j], L2[j + 1] = L2[j + 1], L2[j]
print("Descending Order: ", str(L2))
elif ch == 5:
print("Thank you!")
break
|
83b8b4ee1611505600a4f425eacdca7ab4beec68 | VolodymyrKM/alfred_pennyworth | /Classes/lecture_2/slots.py | 1,120 | 3.75 | 4 | # Slots
# https://stackoverflow.com/a/28059785/5841818
# ******************
# What problem solve
# ******************
# __slots__ allows to predefine set of attributes class instance will have. (avoid dynamically created attributes)
# Reason to use:
# 1. Faster attribute access
# 2. Space savings in memory
# ******************
# When not to use
# ******************
# does not work for classes derived from some built-in types such as int, bytes and tuple.
# better not to use in case of multiple inheritance - brings extra complexity.
# definitely should not be used if dynamical attribute assignment should be performed.
# ******************
# Syntax/example
# ******************
# ** but if slots attribute is set, __dict__ dictionary will be created - memory optimization
#
class SlotsClass:
__slots__ = ('foo', 'bar')
obj = SlotsClass()
obj.foo = 5
obj.__slots__
# ('foo', 'bar')
# if slots attribute is set, __dict__ dictionary will not be created
obj.__dict__
# Traceback (most recent call last):
# File "python", line 8, in <module>
# AttributeError: 'SlotsClass' object has no attribute '__dict__'
|
4a7bd524c42a6493b5ce0791cacf0a76dd68e10d | junhaalee/Algorithm | /solved/LeetCode/course_schedule/course_schedule.py | 1,770 | 3.515625 | 4 | numCourses = 2
prerequisites = [[0,1],[0,2],[1,2]]
# visited 없을 때
from collections import defaultdict
class Solution:
def canFinish(self, numCourses, prerequisites):
graph = defaultdict(list)
for a,b in prerequisites:
graph[a].append(b)
visit = set()
def dfs(num):
if num in visit:
return False
visit.add(num)
print('구역1')
print(visit)
for k in graph[num]:
if not dfs(k):
return False
print('구역2')
print(visit)
visit.remove(num)
print('구역3')
print(visit)
return True
for num in list(graph):
if not dfs(num):
return False
return True
# visited 있을 때
from collections import defaultdict
class Solution:
def canFinish(self, numCourses, prerequisites):
graph = defaultdict(list)
for a,b in prerequisites:
graph[a].append(b)
visit = set()
visited = set()
def dfs(num):
if num in visit:
return False
if num in visited:
return True
visit.add(num)
for k in graph[num]:
if not dfs(k):
return False
visit.remove(num)
visited.add(num)
print(visited)
return True
for x in list(graph):
if not dfs(x):
return False
return True
sol = Solution()
sol.canFinish(numCourses,prerequisites)
|
c5a545412d8bec68565f01493babc87e7c47ae64 | Andong501/LeetCode-with-Python | /496-Next-Greater-Element-I.py | 1,594 | 3.71875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# LeetCode with Python
# You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
#
# The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
#
# Example:
# Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
# Output: [-1,3,-1]
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
res = []
dic = {}
for idx in range(len(nums)):
dic[str(nums[idx])] = idx
for num in findNums:
idx = dic[str(num)]
get = 0
for i in nums[idx+1:]:
if i > num:
res.append(i)
get = 1
break
if get == 0:
res.append(-1)
return res
def nextGreaterElement2(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
stack = []
dic = {}
for num in nums:
while stack and stack[-1]<num:
dic[stack.pop()] = num
stack.append(num)
return [dic.get(num, -1) for num in findNums]
if __name__ = '__main__':
print Solution().nextGreaterElement([4, 1, 2], [1, 3, 4, 2]) |
f8a985159ea3501b21d251f68c24f8902f65adf4 | Jay28497/Problem-solution-for-Python | /Python HackerRank Problem Solution/Collections/companyLogo.py | 725 | 3.5625 | 4 | from collections import Counter, OrderedDict
import math
import os
import random
import re
import sys
if __name__ == '__main__':
s = input()
chars = Counter(s).items()
for char, n in sorted(chars, key=lambda c: (-c[1], c[0]))[:3]:
print(char, n)
##########
# OR
##########
chars = Counter(input()).items()
for char, n in sorted(chars, key=lambda c: (-c[1], c[0]))[:3]:
print(char, n)
##########
# OR
##########
string = sorted(Counter(input()).items(), key=lambda x: (-x[1], x[0]))[:3]
print("\n".join(x[0] + " " + str(x[1]) for x in string))
##########
# OR
##########
class OrderedCounter(Counter, OrderedDict):
pass
[print(*c) for c in OrderedCounter(sorted(input())).most_common(3)]
|
42f04d0f35a2f5c7b0516e6902be7a099bc5c246 | bcaldwell/devops | /setup.py | 3,163 | 3.546875 | 4 | import subprocess
import sys
import yaml
import json
import os
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
print "This script will set up a new server\n"
HOST = raw_input("Enter host: ")
# PORT = raw_input("Enter shh port: ") or 22
host_file = open("ansible/playbooks/hosts.temp", "w")
host_file.write("[server]\n%s" % HOST)
host_file.close()
print "Using root user to set up with setup-server ansible playbook\n"
status = subprocess.call("cd ansible/playbooks && ansible-playbook setup-server.yml -i hosts.temp -u root --ask-pass -v", shell=True)
dotfiles = query_yes_no("Would you like to setup dotfiles? ")
if dotfiles:
status = subprocess.call("cd ansible/playbooks && ansible-playbook dotfiles.yml -i hosts.temp -u admin --ask-become-pass -v", shell=True)
docker = query_yes_no("Would you like to install docker? ")
if docker:
status = subprocess.call("cd ansible && ansible-playbook run_role.yml -e 'hosts=server roles=docker' -i playbooks/hosts.temp -u admin --ask-become-pass -v", shell=True)
upgrade = query_yes_no("Would you like to upgrade server? ")
if upgrade:
status = subprocess.call("cd ansible && ansible-playbook run_role.yml -e 'hosts=server roles=upgrade' -i playbooks/hosts.temp -u admin --ask-become-pass -v", shell=True)
config = query_yes_no("Would you like add this server to the config? ")
if config:
with open("server-config.yaml", "r") as yml:
try:
data = yaml.load(yml)
yml.close()
NAME = raw_input("Enter hostname: ")
TAGS = raw_input("Enter tags: ")
TAGS = TAGS.split(",")
data.append({
"host":NAME,
"hostname": HOST,
"tags": TAGS,
# "port": int (PORT),
"user": "admin"
})
with open("server-config.yaml", "w") as outfile:
yaml.dump(data, outfile, default_flow_style=False)
except yaml.YAMLError as exc:
print(exc)
execfile("sshconfig.py")
os.remove("ansible/playbooks/hosts.temp") |
c68f9a17146e12de3e24a85322ceede3c0978c6d | chenxu0602/LeetCode | /1198.find-smallest-common-element-in-all-rows.py | 1,241 | 3.71875 | 4 | #
# @lc app=leetcode id=1198 lang=python3
#
# [1198] Find Smallest Common Element in All Rows
#
# https://leetcode.com/problems/find-smallest-common-element-in-all-rows/description/
#
# algorithms
# Medium (74.17%)
# Likes: 71
# Dislikes: 7
# Total Accepted: 6.1K
# Total Submissions: 8.2K
# Testcase Example: '[[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]'
#
# Given a matrix mat where every row is sorted in increasing order, return the
# smallest common element in all rows.
#
# If there is no common element, return -1.
#
#
#
# Example 1:
# Input: mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
# Output: 5
#
#
# Constraints:
#
#
# 1 <= mat.length, mat[i].length <= 500
# 1 <= mat[i][j] <= 10^4
# mat[i] is sorted in increasing order.
#
#
#
# @lc code=start
from collections import Counter
from functools import reduce
class Solution:
def smallestCommonElement(self, mat: List[List[int]]) -> int:
# c = Counter()
# for row in mat:
# for a in row:
# c[a] += 1
# if c[a] == len(mat):
# return a
# return -1
return min(reduce(lambda x, y: set(x) & set(y), mat), default=-1)
# @lc code=end
|
7261e6a13f693bd6088a2b1488212ea1de748486 | Uche-Clare/python-challenge-solutions | /Darlington/phase1/python Basic 2/day 22 solution/qtn9.py | 426 | 3.9375 | 4 | #program that compute the area of the polygon . The vertices have the names vertex 1, vertex 2, vertex 3, ...
# vertex n according to the order of edge connections.
def poly_area(c):
add = []
for i in range(0, (len(c) - 2), 2):
add.append(c[i] * c[i + 3] - c[i + 1] * c[i + 2])
add.append(c[len(c) - 2] * c[1] - c[len(c) - 1] * c[0])
return abs(sum(add) / 2)
print(poly_area([1, 0, 0, 0, 1, 1, 2, 0, -1, 1])) |
9f2edfec886b2a005ab8315a024e93eec1aeac57 | Otumian-empire/tkinter-basic-gui | /bgrid.py | 633 | 3.828125 | 4 | from tkinter import Tk, Label, mainloop
from random import choice
root = Tk()
b = Label(text="I am using a grid here for the B label", width=70, height=10)
b.grid(row=3,column=3,padx=5, pady=5)
colors = ['black', 'white', 'green', 'red', 'yellow']
for i in range(4):
for x in range(4):
bgc = choice(colors)
fgc = choice(colors)
print(bgc, fgc, '**')
if (bgc == fgc):
bgc, fgc = choice(colors), choice(colors)
a = Label(text="I am using a grid here for the A label", fg=fgc, bg=bgc)
a.grid(row=i,column=x,padx=i, pady=x)
print(bgc, fgc)
mainloop() |
17f5462a59712e18ff94cc0fdadb039baed080db | GuileStr/proyectos-py | /testInterSection.py | 242 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 27 15:52:06 2020
@author: palar
"""
a=[-19,-17,-15,-5,13,18]
b=[-14,-13,-11,1,6,7,14,16,18]
print("a",a)
print("b",b)
c=[]
for i in a:
if i in a and i in b:
c.append(i)
print("c",c) |
eacc425b5cd8e839fb33ef5c64be110cc6cedceb | jpbat/advent-of-code | /2018/day_06/part2/script.py | 2,203 | 3.5625 | 4 | from collections import namedtuple
Place = namedtuple('Place', ['x', 'y'])
FRINGE_SIZE = 10000
fringe = {}
def read_input():
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
return lines
def fill_grid(place):
for fringe_key, fringe_item in fringe.items():
if fringe[fringe_key]['distance'] >= FRINGE_SIZE:
continue
fringe[fringe_key]['distance'] += abs(fringe_item['x'] - place.x) + abs(fringe_item['y'] - place.y)
def main():
lines = read_input()
places = []
for i in range(len(lines)):
places.append(
Place(
x = int(lines[i].split(',')[0]),
y = int(lines[i].split(' ')[1]),
)
)
center = places[0]
for i in range(400):
for j in range(400):
if i + j >= FRINGE_SIZE:
continue
key = '{}.{}'.format(center.x + i, center.y + j)
fringe[key] = {
'distance': abs(center.x + i - center.x) + abs(center.y + j - center.y),
'x': center.x + i,
'y': center.y + j
}
key = '{}.{}'.format(center.x + i, center.y - j)
fringe[key] = {
'distance': abs(center.x + i - center.x) + abs(center.y - j - center.y),
'x': center.x + i,
'y': center.y - j
}
key = '{}.{}'.format(center.x - i, center.y + j)
fringe[key] = {
'distance': abs(center.x - i - center.x) + abs(center.y + j - center.y),
'x': center.x - i,
'y': center.y + j
}
key = '{}.{}'.format(center.x - i, center.y - j)
fringe[key] = {
'distance': abs(center.x - i - center.x) + abs(center.y - j - center.y),
'x': center.x - i,
'y': center.y - j
}
for place in places[1:]:
fill_grid(place)
counter = 0
for k, v in fringe.items():
if v['distance'] < FRINGE_SIZE:
counter += 1
print (counter)
if __name__ == '__main__':
main()
|
d9b45aad4a507741df807d9904814eae78d97d0d | rizniyarasheed/python | /oops/multilevelinheritance.py | 249 | 3.625 | 4 | class Parent:
def m1(self):
print("inside parent")
class Child(Parent):
def m2(self):
print("inside child")
class SubChild(Child):
def m3(self):
print("inside subchild")
obj=SubChild()
obj.m3()
obj.m2()
obj.m1() |
23655568cfb786d81e034d4b6ed80fb69c189308 | Ytr00m/Listas | /Lista2 AED/Questao3.py | 116 | 3.984375 | 4 | pi = 3.14
raio = int(input("Digite o raio do circulo:"))
area = pi * raio ** 2
print("A area do circulo é",area) |
e9f08082e3f535c92c002cc4af58686019005954 | sethgerou/PlantingLog | /backend.py | 1,535 | 3.6875 | 4 | import sqlite3
class Database:
def __init__(self, db):
self.conn=sqlite3.connect(db)
self.cur=self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS plants (id INTEGER PRIMARY KEY, crop text, quantity int, plant_date datetime, outcome text, notes text)")
self.conn.commit()
def insert(self, crop, quantity, plant_date, outcome, notes):
self.cur.execute("INSERT INTO plants VALUES (NULL,?,?,?,?,?)",(crop, quantity, plant_date, outcome, notes))
self.conn.commit()
def view(self):
self.cur.execute("SELECT * FROM plants")
rows=self.cur.fetchall()
return rows
def search(self, crop="", quantity="", plant_date="", outcome=""):
self.cur.execute("SELECT * FROM plants WHERE crop=? or quantity=? or plant_date=? or outcome=?",(crop,quantity,plant_date,outcome))
rows=self.cur.fetchall()
return rows
def delete(self, id):
self.cur.execute("DELETE FROM plants WHERE id=?",(id,))
self.conn.commit()
def update(self, id,crop="", quantity="", plant_date="", outcome="", notes=""):
self.cur.execute("UPDATE plants SET crop=?, quantity=?, plant_date=?, outcome=?, notes=? WHERE id=?" ,(crop,quantity,plant_date,outcome,notes,id))
self.conn.commit()
def __del__(self):
self.conn.close()
# insert("Potato",12,"March15,2017","Epic Fail!","We thought we were planting tomatoes.")
# update(3,"Broccoli",5,"April2,2017","meh","small crowns but predation was acceptible")
|
e6fa6e47e776ec2dc5abade3bdbe16d3577e1f7d | SantiagoJSG/Trabajo_Final_30_Abril | /Ejercicio20.py | 1,012 | 3.546875 | 4 | # Ejercicio 20
valor = 0
cien = 0
cincuenta = 0
veinte = 0
diez = 0
cinco = 0
mil = 0
valor = int(input("Ingresa la cantidad de dínero (Mínimo 1.000): "))
if valor >= 1000:
cien = int(valor / 100000)
reserva = valor % 100000
cincuenta = int(reserva / 50000)
reserva = reserva % 50000
veinte = int(reserva / 20000)
reserva = reserva % 20000
diez = int(reserva / 10000)
reserva = reserva % 10000
cinco = int(reserva / 5000)
reserva = reserva % 5000
dosmil = int(reserva / 2000)
reserva = reserva % 2000
mil = int(reserva / 1000)
reserva = reserva % 1000
print("La cantidad mínima de cada billete son: ")
print(str(cien) + " de 100.000" + "\n" + str(cincuenta) + " de 50.000" + "\n" + str(veinte) + " de 20.000" + "\n" + str(diez) + " de 10.000" + "\n" + str(cinco) + " de 5.000" + "\n" + str(dosmil) + " de 2.000" + "\n" + str(mil) + " de 1.000")
else:
print("Digitó un número fuera del rango")
|
06140dcee702faa6edc417e75b2f4b5487567aae | p4r4n0rm4l/random-scripts | /copycontent.py | 565 | 3.609375 | 4 | from sys import argv
script, fromFile, toFile = argv
def copy(fromFile, toFile):
# Open file 'fromFile' for reading as binary
sourceFile = open(fromFile, "rb")
data = sourceFile.read()
sourceFile.close()
# Open (or create if does not exists) file 'toFile' for writing as binary
destFile = open(toFile, "wb")
destFile.write(data)
destFile.close()
print("Done!")
# Ask for file names
#src = input("Type the source file name:\n")
#dst = input("Type the destination file name:\n")
# Call copy function
copy(fromFile, toFile) |
f601d308f6f6816f510220a19cd1a43dc8321461 | PanyushkinOOP/OOPb | /datasql.py | 2,080 | 3.609375 | 4 | import os
import sqlite3 as db
emptydb = """
PRAGMA foreign_keys = ON;
create table materials
(code integer primary key,
name text,
priceForGramm integer);
create table product
(code integer primary key,
name text,
type1 text,
weight integer,
price integer,
material integer);
create table sell
(code integer primary key,
date text,
surname text,
name text,
secname text,
product integer references product(code) on update cascade on delete set null);
"""
class datasql:
def read(self,inp,sto):
conn = db.connect(inp)
curs = conn.cursor()
curs.execute("select code,name,priceForGramm from materials")
data=curs.fetchall()
for r in data:sto.newMaterial(r[0],r[1],r[2])
curs.execute("select code,name,type1,material,weight,price from product")
data=curs.fetchall()
for r in data:
sto.newProduct(r[0],r[1],r[2],sto.findMaterialByCode(int(r[3])),r[4],r[5])
curs.execute("select code,product,date,surname,name,secname from sell")
data=curs.fetchall()
for r in data:sto.newSell(r[0],sto.findProductByCode(int(r[1])),r[2],r[3],r[4],r[5])
def write(self,out,sto):
conn = db.connect(out)
curs = conn.cursor()
curs.executescript(emptydb)
for c in sto.getMaterialCodes():
curs.execute("insert into materials(code,name,priceForGramm) values('%s','%s','%s')"%(
str(c),
sto.getMaterialName(c),
int(sto.getMaterialPriceForGramm(c))))
for c in sto.getProductCodes():
curs.execute("insert into product(code,name,type1,material,weight,price) values('%s','%s','%s','%s','%s','%s')"%(
str(c),
sto.getProductName(c),
sto.getProductTypel(c),
int(sto.getProductMaterialCode(c)),
int(sto.getProductPrice(c)),
int(sto.getProductWeight(c))))
for c in sto.getSellCodes():
curs.execute("insert into sell(code,product,date,surname,name,secname) values('%s','%s','%s','%s','%s','%s')"%(
str(c),
int(sto.getSellProductCode(c)),
sto.getSellDate(c),
sto.getSellSurname(c),
sto.getSellName(c),
sto.getSellSecname(c)))
conn.commit()
conn.close()
|
e9140cf46ea883c3f86c2de63735e964e9e2889b | sherinfazer/python | /python38.py | 273 | 3.921875 | 4 | s = float(input(" Please Enter the First Value s: "))
j = float(input(" Please Enter the Second Value j: "))
print("Before Swapping two Number: s = {0} and j = {1}".format(s, j))
temp = s
s = j
j= temp
print("After Swapping two Number: s = {0} and j = {1}".format(, j))
|
b72f0c91b7339e2fa6ef8909221f0e893926221a | Nikkuniku/AtcoderProgramming | /ABC/ABC200~ABC299/ABC234/a.py | 86 | 3.828125 | 4 | def f(x):
return x**2 + 2*x +3
t=int(input())
ans=f(f(f(t)+t)+f(f(t)))
print(ans) |
86f0d70ea94461b03df823bf130d1e1998259ca3 | Kirankumar422/HelloWorld | /programFlowControl.py | 573 | 3.9375 | 4 | # for i in range(1, 12):
# print("No {} squared is {} and cubed is {:4}".format(i, i**2, i**4))
# print("Calculation completed")
# print("Try again")
print("Please guess a number between 1 and 10: ")
guess = int(input())
if guess != 5:
if guess <5:
print("Please guess higher")
else: #guess must be greater than 5
print("Please guess lower")
guess = int(input())
if guess == 5:
print("Well done, you guessed it")
else:
print("Sorry, you have not guessed correctly")
else:
print("You got it first time") |
43377decd1e70ff4d35070db41d2149703ec2bfe | mkdika/learn-python | /basic/substring.py | 109 | 3.640625 | 4 |
str = 'maikel'
print(str[-1])
x = len(str)/2
print(int(x))
strx = str[1:len(str)-1]
print(f">>> {strx}")
|
da72f53cb5a87be57964cbeeaef6fd1e28712473 | sbsdevlec/PythonEx | /Hello/Lecture/Day04/listType/list04.py | 923 | 4.3125 | 4 | # 리스트에 추가하기
list = []
print(list)
list.append(9)
list.append(8)
list.append(7)
print(list)
list.append([6,5,4]);
print(list)
print("*"*30)
# 리스트 수정하기
list[0] = 88
print(list)
list[1:2] = [77,66,55,44]
print(list)
#list[1:5] = 33 # TypeError: can only assign an iterable
list[1:5] = [33]
print(list)
print("*"*30)
# 리스트 삭제하기
del list[0]
print(list)
del list[0:1]
print(list)
list[1][:2]=[]
print(list)
list[1]=[]
print(list)
list[1]=[1,2,3]
print(list)
del list[1]
print(list)
print("*"*30)
# 리스트에 삽입하기
list.insert(0,6)
list.insert(0,7)
print(list)
list.insert(1,[2,2,2])
print(list)
print("*"*30)
# 리스트 확장
list[0:]=[1,2,3,4,5]
print(list)
list.append(11)
list.append(12)
list.append(13)
print(list)
list.extend([21,22,23])
print(list)
append = [33,44,55,66,77]
list.extend(append)
print(list)
|
4a6432a888a944690081ca22fe7596aa5182107f | tgkei/Algorithm_study | /by_python/programmers/42861.py | 875 | 3.65625 | 4 | from queue import PriorityQueue
from math import inf
def solution(n, costs):
answer = 0
linked = [[inf for _ in range(n)] for _ in range(n)]
q = PriorityQueue()
visited = set()
for p1, p2, cost in costs:
linked[p1][p2] = cost
linked[p2][p1] = cost
idx = 0
visited.add(idx)
for p2, cost in enumerate(linked[idx]):
if cost == inf:
continue
q.put([cost, p2])
while not q.empty():
cost, idx = q.get()
if idx in visited:
continue
visited.add(idx)
answer += cost
for p2, cost in enumerate(linked[idx]):
if cost == inf:
continue
q.put([cost, p2])
return answer
if __name__ == "__main__":
n = 4
costs = [[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 1], [2, 3, 8]]
print(solution(n, costs))
|
99235b43190897d41f69c810954b46e1e8f438b9 | jwyx3/practices | /leetcode/dynamic-programing/largest-sum-of-averages.py | 1,072 | 3.546875 | 4 | # https://leetcode.com/problems/largest-sum-of-averages/
# https://leetcode.com/problems/largest-sum-of-averages/solution/
# Time: O(N*N*K)
# Space: O(N)
class Solution(object):
def largestSumOfAverages(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: float
"""
# dp[i]: the largest score of A[i:] partitioning into at most K
# k=1..K
# dp[i] = max(average(i, N), max{average(i, j) + dp[j], j > i}))
# average(i, j) = float(P[j] - P[i]) / (j - i)
# initial: dp[i] = average(i, N)
# answer: dp[0]
N = len(A)
P = [0]
for num in A:
P.append(P[-1] + num)
def average(i, j):
return float(P[j] - P[i]) / (j - i)
dp = [0] * N
for i in xrange(N):
dp[i] = average(i, N)
for k in xrange(K - 1):
for i in xrange(N):
for j in xrange(i + 1, N):
dp[i] = max(dp[i], average(i, j) + dp[j])
return dp[0]
|
1cb649073f435cd622c0e1ad95be884a1a224906 | bekbusinova/-1 | /arr.py | 338 | 4.125 | 4 | def arr_min(arr):
min = arr[0]
for elem in arr:
if elem < min:
min = elem
return min
def arr_avg(arr):
count = len(arr)
summ = sum(elem for elem in arr)
return summ / count
arr = [1, 2, 4, 6, 0]
print("minimum")
print(arr_min(arr))
print("average")
print(arr_avg(arr)) |
07a8fc2ad5f6981d39cc3506d5ab7fe4203f6d84 | Fondamenti18/fondamenti-di-programmazione | /students/1797637/homework01/program02.py | 5,743 | 3.671875 | 4 | def conv(n):
'''Viene composta la stringa formata dalle cifre del numero in input in forma letterale. Esse vengono
costruite attraverso la chiamata di funzioni secondarie (unita, centinaia, migliaia, ecc)'''
numero=str(n)
numero='0'*(12-len(numero))+numero
num_lett=""
num_lett=unita(numero[0],'!uno')+centinaia(numero[0],numero[1])+decina(numero[1],numero[2])
num_lett+=unita(numero[2],'!uno',numero[1])+miliardo(numero[2],numero[1],num_lett)+unita(numero[3],'!uno')+centinaia(numero[3],numero[4])+decina(numero[4],numero[5])
num_lett+=unita(numero[5],'!uno',numero[4])+milione(numero[5],numero[4],numero[3],num_lett)+unita(numero[6],'!uno')+centinaia(numero[6],numero[7])+decina(numero[7],numero[8])
num_lett+=unita(numero[8],'!uno',numero[7])+migliaia(numero[8],numero[7],numero[6],num_lett)+unita(numero[9],'!uno')+centinaia(numero[9],numero[10])+decina(numero[10],numero[11])
num_lett+=unita(numero[11],'',numero[10])
return num_lett
def unita(cifra, eccezione='',cifra_prec=''):
risultato=''
if int(cifra)>1: risultato= unita_1(cifra)
elif cifra == '1' and eccezione == '!uno': risultato=''
elif cifra == '1': risultato='uno'
if cifra_prec=='1':risultato=''
return risultato
def unita_1(cifra):
risultato=''
if int(cifra)>4: risultato= unita_2(cifra)
elif cifra == '2': risultato='due'
elif cifra == '3': risultato='tre'
elif cifra == '4': risultato='quattro'
return risultato
def unita_2(cifra):
risultato=''
if cifra == '5': risultato='cinque'
elif cifra == '6': risultato='sei'
elif cifra == '7': risultato='sette'
elif cifra == '8': risultato='otto'
elif cifra == '9': risultato='nove'
return risultato
def decina(cifra,cifra_succ):
risultato=''
if cifra == '1' and cifra_succ != '0': risultato=mag_dieci(cifra_succ)
elif cifra == '1': risultato='dieci'
elif int(cifra) > 1:risultato=decina_1(cifra)
if int(cifra)>1 and (cifra_succ == '1' or cifra_succ == '8'): risultato = risultato[:-1]
return risultato
def decina_1(cifra):
risultato=''
if int(cifra)>4:risultato=decina_2(cifra)
elif cifra == '2': risultato='venti'
elif cifra == '3': risultato='trenta'
elif cifra == '4': risultato='quaranta'
return risultato
def decina_2(cifra):
risultato=''
if cifra == '5': risultato='cinquanta'
elif cifra == '6': risultato='sessanta'
elif cifra == '7': risultato='settanta'
elif cifra == '8': risultato='ottanta'
elif cifra == '9': risultato='novanta'
return risultato
def mag_dieci(cifra_succ):
risultato=''
if int(cifra_succ)>4:risultato=mag_dieci_1(cifra_succ)
elif cifra_succ == '1': risultato='undici'
elif cifra_succ == '2': risultato='dodici'
elif cifra_succ == '3': risultato='tredici'
elif cifra_succ == '4': risultato='quattordici'
return risultato
def mag_dieci_1(cifra_succ):
risultato=''
if cifra_succ == '5': risultato='quindici'
elif cifra_succ == '6': risultato='sedici'
elif cifra_succ == '7': risultato='diciassette'
elif cifra_succ == '8': risultato='diciotto'
elif cifra_succ == '9': risultato='diciannove'
return risultato
def centinaia(cifra,cifra_succ):
risultato=''
if not cifra == '0': risultato = 'cento'
if not cifra =='0' and cifra_succ== '8': risultato = 'cent'
return risultato
def migliaia(cifra,cifra_prec,sec_cifra_prec,parte_prec):
risultato=''
if cifra == '0' and not parte_prec=='':risultato=migliaia_0(cifra_prec,sec_cifra_prec)
elif cifra == '1':risultato=migliaia_1(cifra_prec,sec_cifra_prec,parte_prec)
elif cifra_prec=='1':risultato='mila'
elif not cifra == '0': risultato='mila'
return risultato
def migliaia_0(cifra_prec,sec_cifra_prec):
risultato=''
if cifra_prec == '0' and sec_cifra_prec =='0': risultato=''
else: risultato='mila'
return risultato
def migliaia_1(cifra_prec,sec_cifra_prec,parte_prec):
risultato=''
if parte_prec == '': risultato='mille'
elif not parte_prec == '' and cifra_prec == '0' and sec_cifra_prec =='0': risultato='mille'
elif not parte_prec == '' and cifra_prec=='1': risultato='mila'
elif not parte_prec == '': risultato='unomila'
return risultato
def milione(cifra,cifra_prec,sec_cifra_prec,parte_prec):
risultato=''
if cifra == '0' and not parte_prec == '':risultato=milione_0(cifra_prec,sec_cifra_prec)
elif cifra == '1':risultato=milione_1(cifra_prec,sec_cifra_prec,parte_prec)
elif cifra_prec=='1':risultato='milioni'
elif not cifra == '0': risultato='milioni'
return risultato
def milione_0(cifra_prec,sec_cifra_prec):
risultato=''
if cifra_prec == '0' and sec_cifra_prec =='0': risultato=''
else: risultato='milioni'
return risultato
def milione_1(cifra_prec,sec_cifra_prec,parte_prec):
risultato=''
if parte_prec == '': risultato='unmilione'
elif not parte_prec == '' and cifra_prec == '0' and sec_cifra_prec =='0': risultato='unmilione'
elif not parte_prec == '' and cifra_prec=='1': risultato='milioni'
elif not parte_prec == '': risultato='unomilioni'
return risultato
def miliardo(cifra,cifra_prec,parte_prec):
risultato=''
if cifra == '1': risultato= miliardo_1(cifra_prec,parte_prec)
elif cifra_prec=='1':risultato='miliardi'
elif cifra == '0' and not parte_prec == '': risultato='miliardi'
elif not cifra == '0': risultato='miliardi'
return risultato
def miliardo_1(cifra_prec,parte_prec):
risultato=''
if parte_prec == '': risultato='unmiliardo'
elif not parte_prec == '' and cifra_prec=='1': risultato='miliardi'
elif not parte_prec == '': risultato='unomiliardi'
return risultato |
004bdc7a78db6a8fb131de6978e7d0f2248a7d88 | kashyapa/interview-prep | /revise-daily/educative.io/medium-dp/longest-common-subsequence/1_longest_common_substring.py | 885 | 3.546875 | 4 | def find_LCS_length(s1, s2):
return find_lcs_rec(s1, s2, 0, 0, 0)
def find_lcs_rec(s1, s2, i1, i2, count):
if i1 == len(s1) or i2 == len(s2):
return count
if s1[i1] == s2[i2]:
count = find_lcs_rec(s1, s2, i1+1, i2+1, count+1)
c2 = find_lcs_rec(s1, s2, i1, i2+1, 0)
c3 = find_lcs_rec(s1, s2, i1+1, i2, 0)
return max(count, max(c2, c3))
def find_lcs_dp(s1, s2):
n1 = len(s1)
n2 = len(s2)
dp = [[0 for _ in range(n2+1)] for _ in range(n1+1)]
max_length = 0
for i in range(1, n1+1):
for j in range(1, n2+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
max_length = max(max_length, dp[i][j])
return max_length
def main():
print(find_LCS_length("abdca", "cbda"))
print(find_LCS_length("passport", "ppsspt"))
if __name__ == "__main__":
main()
|
24d7edfa905a5ca42695463a74ff1ea611fe4b50 | Klinsmann-Agyei/Python-Syntax-Medical-Insurance-Project | /python Syntax Medical Insurance Project.py | 1,232 | 4.1875 | 4 |
# create the initial variables below
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# Add insurance estimate formula below
insurance_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
print("This person's insurance cost is "+ str(insurance_cost) + " dollars")
# Age Factor
age += 4
new_insurance_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
change_in_insurance = new_insurance_cost - insurance_cost
print("The change in cost of insurance after increasing the age by 4 years is "+str(change_in_insurance)+" dollars.")
# BMI Factor
age = 28
bmi += 3.1
new_insurance_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
change_in_insurance = new_insurance_cost - insurance_cost
print("The change in estimated insurance cost after increasing BMI by 3.1 is "+ str(change_in_insurance)+ "dollars.")
# Male vs. Female Factor
sex = 1
bmi = 26.2
sex = 1
new_insurance_cost = 250*age - 128*sex + 370*bmi + 425*num_of_children + 24000*smoker - 12500
change_in_insurance = new_insurance_cost - insurance_cost
print("The change in estimated cost for being male instead of female is "+str(change_in_insurance)+ "dollars.")
# Extra Practice |
2f875989cc2ff026c53e6f3ed8384b7948a4547b | attoPascal/risk-simulator | /risk.py | 1,710 | 3.6875 | 4 | from sys import argv
from random import randrange
def roll_dice():
return randrange(1,7)
def attack(units):
if units >= 3:
cast = [roll_dice(), roll_dice(), roll_dice()]
elif units == 2:
cast = [roll_dice(), roll_dice()]
else:
cast = [roll_dice()]
return sorted(cast, reverse=True)
def defend(units):
if units >= 2:
cast = [roll_dice(), roll_dice()]
else:
cast = [roll_dice()]
return sorted(cast, reverse=True)
def play(attackers, defenders, verbose=False):
if verbose:
print("Attacker has", attackers, "units")
print("Defender has", defenders, "units")
print()
while attackers > 0 and defenders > 0:
the_attack = attack(attackers)
the_defense = defend(defenders)
if verbose:
print(the_attack, "vs.", the_defense)
while len(the_attack) > 0 and len(the_defense) > 0:
if the_attack.pop(0) > the_defense.pop(0):
defenders -= 1
if verbose:
print("Defender unit dies ({} left)".format(defenders))
else:
attackers -= 1
if verbose:
print("Attacker unit dies ({} left)".format(attackers))
if verbose:
print()
if attackers > 0:
if verbose:
print("Attacker wins with", attackers, "units left")
return attackers
else:
if verbose:
print("Defender wins with", defenders, "units left")
return -defenders
def main():
attackers = int(argv[1])
defenders = int(argv[2])
play(attackers, defenders, True)
if __name__ == '__main__':
main()
|
fcddddd5aab587312d7aa04aa44e27426922242b | jonahliu0426/leetcode | /algo/easy/706.design-hashmap.py | 1,968 | 3.5 | 4 | class ListNode:
def __init__(self, key, value, node):
self.val = [key, value]
self.next = node
class LList:
def __init__(self, key, value, nxt=None):
self.head = ListNode(key, value, nxt)
def get(self, key):
temp = self.head
if not temp:
return -1
while temp:
if temp.val[0] == key:
return temp.val[1]
temp = temp.next
return -1
def remove(self, key):
temp = self.head
if not temp:
return None
while temp:
if temp.val[0] == key:
temp.val[1] = -1
temp = temp.next
return None
def put(self, key, value):
temp = self.head
to_insert = ListNode(key, value, None)
if not temp:
temp = to_insert
return None
while temp.next:
if temp.val[0] == key:
temp.val[1] = value
return None
temp = temp.next
if temp.val[0] == key:
temp.val[1] = value
return None
else:
temp.next = to_insert
return None
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = [LList(i,-1, None) for i in range(1000)]
def put(self, key, value):
x = key % 1000
node = self.d[x]
node.put(key, value)
return None
def get(self, key) :
x = key % 1000
to_find = self.d[x]
res = to_find.get(key)
return res
def remove(self, key):
x = key % 1000
to_remove = self.d[x]
to_remove.remove(key)
return None
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key) |
f81f65e8711b3bc4e773cb596fadf3303405f5a7 | elhanan18/hello | /RPN_2.py | 3,207 | 3.53125 | 4 | import sys
'''
Run: python RPN_2.py "a b +"
Variables input: a 2 b 3
'''
class Calculator:
def __init__(self):
self._expression = []
self._variables = {}
self._op_dict = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
}
def run(self):
self._expression = self._handle_expression()
stop = False
while not stop:
try:
print("Expression: {}\nInsert variables:".format(self._expression))
variables_str = input().strip()
self._parse_variables_input(variables_str)
res = self._calc_result()
print("= {}".format(res))
except EOFError:
stop = True
print("Good Bye")
def _handle_expression(self):
assert (len(sys.argv) == 2)
expression_str = sys.argv[1].strip().split()
expression = []
# simplify expression
print("\nExpression: {}".format(expression_str))
for item in expression_str:
if self._is_operand(item):
if self._is_digit(item):
item = int(item)
expression.append(item)
else: # operator
assert (len(expression) >= 2)
operator = item
operand_2, operand_1 = expression.pop(), expression.pop()
if type(operand_1) == int and type(operand_2) == int:
tmp_res = self._op_dict[operator](operand_1, operand_2)
expression.append(tmp_res)
else:
expression.append(operand_1)
expression.append(operand_2)
expression.append(operator)
return expression
def _parse_variables_input(self, variables_str):
if not variables_str:
return
variables_arr = variables_str.split(' ')
assert (len(variables_arr) % 2 == 0)
for i in range(0, len(variables_arr), 2):
self._variables[variables_arr[i]] = int(variables_arr[i+1])
def _calc_result(self):
stack = []
for item in self._expression:
if self._is_operand(item):
stack.append(item)
else: # operator
assert (len(stack) >= 2)
operand_2, operand_1 = stack.pop(), stack.pop()
tmp_res = self._calc_tmp_exp(operand_1, operand_2, item)
stack.append(tmp_res)
assert (len(stack) == 1)
return stack.pop()
def _calc_tmp_exp(self, operand_1, operand_2, operator):
if operand_1 in self._variables:
operand_1 = self._variables[operand_1]
if operand_2 in self._variables:
operand_2 = self._variables[operand_2]
return self._op_dict[operator](operand_1, operand_2)
@staticmethod
def _is_digit(item):
return item.isdigit() or (item[0] == '-' and item[1:].isdigit())
@staticmethod
def _is_operand(item):
return item not in ['+', '-', '*', '/']
if __name__ == '__main__':
Calculator().run() |
ed17f29e704ec4d60b190e0aa4c564a08c9e6877 | HotHunter/PYTHON-__-begin-to-learn | /Python2Test/d9-6(1.py | 289 | 3.5625 | 4 | __author__ = 'Administrator'
l = [0, 10, 20, 30, 40, 50]
cnt = len(l)
n = int(raw_input('print a number:'))
l.append(n)
for i in range(cnt):
if n<l[i]:
for j in range(cnt, i, -1):
l[j] = l[j-1]
l[i] = n
break
print 'The new sorted list is:', l |
1e9daae6e541ec6bbd6e51b47fcd6863e832a244 | Charles-Paley/calculator | /main.py | 1,585 | 3.96875 | 4 | from math import *
import math
question = input("Enter Sine, Cosine, Tangent, Square Root, Type 1 for 4 operations: ")
if question == "sine":
sine_num = input("put the number you want to sine here: ")
sine_num = float(int(sine_num))
result_sine = (math.sin(float(int(sine_num))))
print(result_sine)
if question == "cosine":
cosine_num = input("put the number you want to cosine here: ")
cosine_num = float(int(cosine_num))
result_cosine = (math.cos(float(int(cosine_num))))
print(result_cosine)
if question == "tangent":
tangent_num = input("put the number you want to Tangent here: ")
tangent_num = float(int(tangent_num))
result_tangent = (math.tan(float(int(tangent_num))))
print(result_tangent)
if question == "Square Root":
squareroot_num = input("put the number you want to get the Square Root of here: ")
squareroot_num = float(int(squareroot_num))
result_squareroot = (math.sqrt(float(int(squareroot_num))))
print(result_squareroot)
toehead = input("Your First Number Here: ")
operation = input("Put the operation here: ")
toehead2 = input("Put Your Second Number Here: ")
if operation == "+":
answer_1 = float(toehead) + float(toehead2)
print(answer_1)
if operation == "-":
answer_2 = float(toehead) - float(toehead2)
print(answer_2)
if operation == "*":
answer_3 = float(toehead) * float(toehead2)
print(answer_3)
if operation == "/":
answer_4 = float(toehead) / float(toehead2)
print(answer_4)
|
f131f370b4d835d5d27ff2ce130a998416a8618d | rafaelperazzo/programacao-web | /moodledata/vpl_data/5/usersdata/64/1997/submittedfiles/atm.py | 642 | 3.875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
#ENTRADA
v = int(input('Digite a quantidade a ser sacada: '))
d20 = 0
d10 = 0
d5 = 0
d2 = 0
d1 = 0
#PROCESSAMENTO]
while v >=20:
d20 = d20 + 1
v = v - 20
while v >= 10 < 20:
d10 = d10 + 1
v = v - 10
while v >= 5 < 10:
d5 = d5 + 1
v = v - 5
while v >= 2 < 5:
d2 = d2 + 1
v = v -2
while v >=1 <2:
d1 = d1 + 1
v = v - 1
#SAÍDA
print str(d20)
print str(d10)
print str(d5)
print str(d2)
print str(d1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.