blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c5b282c0e2dd1cc489376c4112cb3ae28d839b76 | jzuver/QueryParser | /main.py | 2,046 | 3.734375 | 4 |
from parserFunctions import *
import data
import os.path as path
def main():
print("enter: help \n or load data and begin query")
keepRunning = True
# loop to allow for as many queries as desired, will run until user types quit
while keepRunning:
# get user input
userInput = input(">")
# check if user wants to quit, print help, or create/overwrite the database
if userInput.lower() == "quit":
keepRunning = False
elif userInput.lower() == "help":
printHelp()
elif userInput.lower() == "load data":
data.initDb()
print("Database created (or overwritten).")
# split user input string into individual components
userInputList = inputToList(userInput)
# if the query is valid, and the database exists, establish connection, do query, and print query results
if validateInput(userInputList) and path.exists("data.db"):
cur = data.sqliteConnect()
if len(userInputList) == 4:
# case for join statement, allows for the user to type in the join statement as outlined for
# our query language
if userInputList[0].lower() == "tweet" and userInputList[1].lower() == "insults" and userInputList[2].lower() == "losers":
print(data.fetch(cur, userInputList[3]))
# case for non-join statement queries
else:
print(data.fetch(cur, userInputList[3], userInputList[1], userInputList[0], userInputList[2]))
# if database hasn't been created, display error message to user
elif not path.exists("data.db"):
print("The database has not been created yet. Please use the load data command to create the database.")
# case for if database exists, but user entered an invalid query
elif userInput.lower() != "help" and userInput.lower() != "quit":
print("Invalid query, type help for list of commands.")
main()
|
5e5e9906b5d17791a55540d08255dabfe2e8d1d0 | Meghana86/CodeInPlace | /Assignment2/Assignment2/nimm.py | 1,681 | 4.125 | 4 | """
File: nimm.py
-------------------------
Add your comments here.
"""
"""
def main():
NO_OF_STONES=20
player_no=1
while NO_OF_STONES>0:
print("There are "+ str(NO_OF_STONES) + " stones left")
remove=int(input("Player "+ str(player_no)+" would you like to remove 1 or 2 stones? "))
# print("Player "+ str(player_no)+" would you like to remove 1 or 2 stones? ")
# remove=int(input("\n"))
if remove == 1 or remove == 2:
NO_OF_STONES = NO_OF_STONES - remove
else:
remove=int(input("Please enter 1 or 2: "))
NO_OF_STONES = NO_OF_STONES - remove
if player_no == 1:
player_no=2
else:
player_no=1
print("")
print("Player "+str(player_no)+" wins!")
if __name__ == '__main__':
main()
"""
def main():
NO_OF_STONES=20
player_no=1
while NO_OF_STONES>0:
print("There are "+ str(NO_OF_STONES) + " stones left")
remove=int(input("Player "+ str(player_no)+" would you like to remove 1 or 2 stones? "))
# print("Player "+ str(player_no)+" would you like to remove 1 or 2 stones? ")
# remove=int(input("\n"))
if remove == 1 or remove == 2:
NO_OF_STONES = NO_OF_STONES - remove
else:
remove=int(input("Please enter 1 or 2: "))
NO_OF_STONES = NO_OF_STONES - remove
if player_no == 1:
player_no=2
else:
player_no=1
print("")
print("Player "+str(player_no)+" wins!")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
|
806412b31ef178089ec348de67c75a6a1b2a6ea0 | larissalages/code-selection | /numbers.py | 349 | 3.90625 | 4 | def print_numbers():
str_result = ""
for i in range(100):
if (i % 3 == 0 and i % 5 == 0):
print "ThreeFive"
str_result += "ThreeFive\n"
elif (i % 3 == 0):
print "Three"
str_result += "Three\n"
elif (i % 5 == 0):
print "Five"
str_result += "Five\n"
else:
print str(i)
str_result += str(i)+"\n"
return str_result
|
15a2e353efb571af76e5652543a50937243167f2 | Hedgehuug/python_30 | /day2/exercise.py | 1,047 | 4.4375 | 4 | """
Generate a sequence using the function range that
returns the following.
[-100, -90, -80, -70, -60, -50, -40, -30, -20, -10, 0,
10, 20, 30, 40, 50, 60, 70, 80, 90]
"""
sequence_one = list(range(-100,91,10))
print(sequence_one)
"""
Generate the previous sequence but in this case in
the opposite way.
"""
sequence_reverse = list(range(90,-101,-10))
print(sequence_reverse)
"""
This challenge can be a bit difficult, try to create a
function that returns a sequence of decimal numbers between
2 numbers, incremental only.
Here's a hint, use the while statement
"""
#Hoof this was really hard cause of the rounding, but it's something I've had problems with in the past
#But the solution should adjust the rounding to the number of decimal points in Step
def float_sequence(start,stop,step):
progress = start
output = [start]
round_num = len(str(step).split('.')[1])
while progress < stop:
output.append(progress)
progress = round(progress + step,round_num)
print(output)
float_sequence(2,15,0.08)
|
195429afd6dc06f0d0844708380beaff9bc318e7 | codud0954/megait_python_20201116 | /02_condition/quiz03/quiz03_3.py | 169 | 3.84375 | 4 | bmi = int(input("bmi 수치를 입력하세요: "))
if bmi <= 10:
print("정상")
elif bmi <= 20:
print("과체중")
elif bmi > 20:
print("비만")
|
cc99de424e99d00b7b5d7a4633f08226bd556053 | RahulGusai/data-structures | /python/problem-solving/rotateMatrix.py | 1,911 | 4 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the matrixRotation function below.
def matrixRotation(matrix, r):
rows = len(matrix)
columns = len(matrix[0])
ret = False
count = 0
n = 0
while( n<rows):
if( ret==False):
rotations = (columns - n*2)*2 + (rows - 2 - 2*n)*2
rotations = (r%rotations)
while( count<rotations ):
ret = rotateMatrix(n,rows,columns)
count = count + 1
count = 0
n = n + 1
else:
break
printMatrix()
def printMatrix():
rows = len(matrix)
columns = len(matrix[0])
for i in range(0,rows):
string = ""
for j in range(0,columns):
string = string + "{0:d} ".format( (matrix[i])[j] )
print(string)
def rotateMatrix(n,rows,columns):
i = n
j = n
temp = (matrix[i])[j]
flag = False
while (i+1)<rows-n:
i = i + 1
if (i==n+1) and (j==n+1):
flag = True
swap = (matrix[i])[j]
(matrix[i])[j] = temp
temp = swap
while (j+1)<columns-n:
j = j + 1
if (i==n+1) and (j==n+1):
flag = True
swap = (matrix[i])[j]
(matrix[i])[j] = temp
temp = swap
while (i-1)>=n:
i = i - 1
if (i==n+1) and (j==n+1):
flag = True
swap = (matrix[i])[j]
(matrix[i])[j] = temp
temp = swap
while (j-1)>=n:
j = j - 1
if (i==n+1) and (j==n+1):
flag = True
swap = (matrix[i])[j]
(matrix[i])[j] = temp
temp = swap
return flag
if __name__ == '__main__':
matrix = [ [1, 2, 3, 4],[7, 8, 9, 10],[13, 14, 15, 16],[19, 20, 21, 22],[25, 26, 27, 28] ]
r = 1
matrixRotation(matrix, r)
print(matrix) |
a87bb2695dccd8706d6076eb64afa3b4af478ec5 | Vagacoder/Codesignal | /python/InterviewPractice/Array01FirstDuplicate.py | 1,796 | 3.578125 | 4 | #
# * Interview Practice, Arrays 01, First Duplicate
# * Easy
# * Given an array a that contains only numbers in the range from 1 to a.length,
# * find the first duplicate number for which the second occurrence has the minimal
# * index. In other words, if there are more than 1 duplicated numbers, return
# * the number for which the second occurrence has a smaller index than the second
# * occurrence of the other number does. If there are no such elements, return -1.
# * Example
# For a = [2, 1, 3, 5, 3, 2], the output should be firstDuplicate(a) = 3.
# There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a
# smaller index than the second occurrence of 2 does, so the answer is 3.
# For a = [2, 2], the output should be firstDuplicate(a) = 2;
# For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1.
# * Input/Output
# [execution time limit] 3 seconds (java)
# [input] array.integer a
# Guaranteed constraints:
# 1 ≤ a.length ≤ 105,
# 1 ≤ a[i] ≤ a.length.
# [output] integer
# The element in a that occurs in the array more than once and has the minimal
# index for its second occurrence. If there are no such elements, return -1.
#%%
# * Solution 1
def firstDuplicate1(a: list)-> int:
n = len(a)
for i in range(n):
for j in range(i):
if a[j] == a[i]:
return a[i]
return -1
# * Solution 2
# ! trade space for speed
def firstDuplicate2(a: list)-> int:
mySet = set()
for i in a:
if i in mySet:
return i;
else:
mySet.add(i)
return -1
a1 = [2, 1, 3, 5, 3, 2]
e1 = 3
r1 = firstDuplicate2(a1)
print('For {}, expected: {}, result:{}'.format(a1, e1, r1))
# %%
|
7fcdc1d0d73870adcb0c932c5dd3603eb0603629 | grahamrichard/COMP-123-fall-16 | /PycharmProjects/Sept26/inclass.py | 2,785 | 3.625 | 4 | # Part 1
x = 25
y = 30
s = 'boolean'
print(x <= y) #True
print(x + 5 > y) #False
print(x % 2 == 0) #False
print(s > 'bodwaddle') #True
print(len(s) ==7) #True
print('e' in s) #True
print('c' in s) #False
print('boo' in s) #True
print(True == False) #False
print(False == False) #True
print(7 != 7) #False
# ======================================
print()
# ======================================
# Part 2
def isSmall(x):
return x <= 10
print(isSmall(8))
# ======================================
print()
# ======================================
# Part 3
def isEven(x):
return x % 2 == 0
print(isEven(100))
# ======================================
print()
# ======================================
# Part 4
print((x % 5 == 0) and (y % 5 == 0)) # True
print((s[0] == 'b') or (len(s) >= 10)) # True
print('l' not in s) # False
print(not (s[1] == 'a')) # True
nums = [15, 20, 25, 30]
print((x in nums) and not (y in nums)) # False
print((x >= 15) and (x <= 50)) # True
# ======================================
print()
# ======================================
# Part 5
def bigEven(x):
return isEven(x) and not isSmall(x)
print(bigEven(20))
# ======================================
print()
# ======================================
# Part 6
x = 7
y = 7
if x > y:
print(x, y)
elif y > x:
print(y, x)
else:
print(x)
# prints the greater of the two numbers followed by the lesser, or the value of both if they're equal
# ======================================
print()
# ======================================
# Part 7
def evaluate(x):
if bigEven(x):
print("wow I love this number. It's so big!")
elif not isSmall(x):
print("It's pretty big, but it's not the best")
else:
print("it's a pretty small number")
evaluate(9)
# ======================================
print()
# ======================================
# Part 8
def min3(x, y, z):
if x <= y and x <=z:
print(x)
elif y <= x and y <=z:
print(y)
else:
print(z)
min3(70, 54, 200)
# ======================================
print()
# ======================================
# Part 9
import turtle
def doMove(teleT, move):
if move == "f":
teleT.fd(15)
elif move == "b":
teleT.bk(15)
elif move == "r":
teleT.rt(90)
elif move == "l":
teleT.lt(90)
else:
print("invalid input")
def teleTurtle(n):
win = turtle.Screen()
teleT = turtle.Turtle()
for i in range(n):
move = input("Enter next move: ")
doMove(teleT, move)
win.exitonclick()
teleTurtle(5)
|
2b3fa8f41d16606779e3aaa843392c764d24abbd | JUNE001/offer-python | /KMP.py | 417 | 3.546875 | 4 | # coding=utf-8
#通过计算,返回子串T的next数组
def get_next(T):
i = 1#后缀
j = 0#前缀
a = []
a.append(0)
while i < len(T):#T[0]表示T的长度
print(i)
if j == 0 or T[i-1] == T[j-1]:
i += 1
j += 1
a.append(j)
else:
j = a[j-1]
return a
T = 'ababaaaba'
next1 = get_next(T)
print(next1)
|
955ca7dd7b1b52cf158b31ee88d1a21104074d94 | linshizuowei/LeetCode | /paralle_link.py | 974 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
cur = head
cnt = 0
while cur:
cnt += 1
cur = cur.next
cur = head
net = head.next
for i in range(1, cnt // 2):
tmp = net.next
net.next = cur
cur = net
net = tmp
if cnt % 2 != 0:
net = net.next
while net:
if net.val != cur.val:
return False
net = net.next
cur = cur.next
return True
if __name__ == '__main__':
head = ListNode(1)
net = ListNode(2)
head.next = net
so = Solution()
so.isPalindrome(head) |
eec9b1554a50bfc6f4d90f716b08219e17476e70 | vijayroykargwal/Infy-FP | /DSA/Day5/src/Excer21.py | 1,281 | 4.125 | 4 | #DSA-Exer-21
'''
Created on Mar 19, 2019
@author: vijay.pal01
'''
def merge_sort(num_list):
# Remove pass and write the logic here to return the sorted list
low = 0
high = len(num_list)-1
if(low==high):
return num_list
else:
mid = len(num_list)//2
l_list = merge_sort(num_list[:mid])
r_list= merge_sort(num_list[mid:])
sorted_list = merge(l_list,r_list)
return sorted_list
def merge(left_list,right_list):
# Remove pass and write the logic to merge
#the elements in the left_list and right_list
# and return the sorted list
i = 0
j = 0
sorted_list = []
while(i<(len(left_list)) and j<(len(right_list))):
if(left_list[i]<=right_list[j]):
sorted_list.append(left_list[i])
i+=1
else:
sorted_list.append(right_list[j])
j+=1
for x in left_list:
if x not in sorted_list:
sorted_list.append(x)
for y in right_list:
if y not in sorted_list:
sorted_list.append(y)
return sorted_list
num_list=[34, 67, 8, 19, 2, 23, 1, 91]
print("Before sorting:",num_list)
sorted_list = merge_sort(num_list)
print("After sorting:",sorted_list)
|
a4f0554cef3427981f1bd8257d1bda7b3830718a | vitorczz1/Curso-Python-MIT | /Parte 2/p1_1.py | 255 | 3.671875 | 4 | interest_rate = 1 #100%
out = 2 #tempo
if (interest_rate != 0):
aux = 0
while (out <= 2):
out = out * (1 + interest_rate)
aux = aux + 1
out = aux
print(out)
if (interest_rate == 0):
out = ("NEVER")
print(out) |
014f45e0e6c70dd98473bf7f18f137bca360eb4e | s87217647/PyCharm_Projects | /ShangAn/FindKthLargest.py | 792 | 3.640625 | 4 | from typing import List
class FindKthLargest:
def findKthLargest(self, nums: List[int], k: int) -> int:
return self.quickSelect(nums, 0, len(nums) - 1, k)
def quickSelect(self, nums, lo, hi, k):
if lo >= hi:
return
mid = self.partition(nums, lo, hi, k)
if mid == len(nums) - k - 1:
return mid
self.partition(nums,lo, mid - 1, k)
self.partition(nums,mid + 1, hi, k)
def partition(self, nums, lo, hi, k):
pivot = nums[lo]
while lo < hi:
while lo < hi and nums[hi] >= pivot:
hi -= 1
nums[lo] = nums[hi]
while lo < hi and nums[lo] <= pivot:
lo += 0
nums[hi] = nums[lo]
nums[lo] = pivot
return lo |
30a47bf110dcc34794a0e12c4345760ec22637c1 | ApostolosZezos/Year9DesignCS-PythonAZ | /TakingInputInt.py | 329 | 4.09375 | 4 | #Input
#Assignment Statement
r = input("What is the radius: ")
r = int(r)
#Casting is the process of changing type
#Strings - collections of characters
#int - integers
#float - numbers with decimals
h = input("What is the height: ")
h = int(h)
#Process
sa = (2 * (3.14) * r * h) + (2 * (3.14) * (r * r))
#Output
print(sa)
|
4009867376493414193a52c15975866f6d903a60 | haruyasu/improve_python | /divisor_prime.py | 925 | 3.96875 | 4 | # coding: utf-8
# divisor 約数列挙
def make_divisor_list(num):
if num < 1:
return []
elif num == 1:
return [1]
else:
divisor_list = []
divisor_list.append(1)
for i in range(2, num // 2 + 1):
if num % i == 0:
divisor_list.append(i)
divisor_list.append(num)
return divisor_list
print(make_divisor_list(28))
# prime 素数列挙
import math
def is_prime(num):
if num < 2:
return False
else:
num_sqrt = int(math.floor(math.sqrt(num)))
for prime in range(2, num_sqrt + 1):
if num % prime == 0:
return False
return True
def make_prime_list(num):
if num < 2:
return []
prime_list = []
for prime in range(2, num + 1):
if is_prime(prime):
prime_list.append(prime)
return prime_list
print(make_prime_list(28))
|
5f8f0fa483539e3a36cc5c98ba79dac23a4bcd21 | JonSolo1417/Python | /fundamentals/fundamentals/basic_functions_2.py | 877 | 3.734375 | 4 | def countdown(num):
arr=[]
for x in range(num,-1,-1):
arr.append(x)
return arr
print(countdown(5))
def printAndReturn(num1,num2):
print (num1)
return num2
x =printAndReturn(5,10)
print("This is x: " + str(x))
def firstPlusLength(arr):
return arr[0] + len(arr)
sum = firstPlusLength([1,2,3,4,5])
print(sum)
def ValuesGreaterThanSecond(arr):
newList=[]
count=0
if len(arr) < 2:
return False
for x in range (0,len(arr)):
if arr[x] > arr[1]:
count+=1
newList.append(arr[x])
print (count)
return newList
newList=ValuesGreaterThanSecond([1,2,6,1,4,6,8])
print(newList)
smallList = []
print(ValuesGreaterThanSecond([]))
def lengthVal(num1,num2):
newList=[]
for x in range (0,num1):
newList.append(num2)
return newList
print(lengthVal(6,2))
print(lengthVal(4,7)) |
1e69e23061cc17cbdc47fcf6a1c203260bcd2d4a | Saipraneeth1001/webcrawler | /mark6/general.py | 1,426 | 3.625 | 4 | # what this file basically consists of is functions to add the obtained data into the file
# functions to delete the files
# function to create the project directory
import os
def create_project(directory):
if not os.path.exists(directory):
print("creating directory" + directory)
os.makedirs(directory)
def create_files(project_name, base_url):
queue = os.path.join(project_name, 'queue.txt')
crawled = os.path.join(project_name, 'crawled.txt')
if not os.path.isfile(queue):
write_file(queue, base_url)
if not os.path.isfile(crawled):
write_file(crawled, '')
# to write the links inside the files
def write_file(path, data):
with open(path, 'w') as f:
f.write(data)
# just to delete the contents of the file not the file itself
def delete_file_contents(path):
open(path, 'w').close()
# to append the data to the existing file ,
def append_to_file(path, data):
with open(path, 'w') as file:
file.write(data + '\n')
# to convert the files to a set for faster operations
def file_to_set(file_name):
results = set()
with open(file_name, 'rt') as file:
for line in file:
results.add(line.replace('\n', ''))
return results
# to convert a set into a file later...
def set_to_file(links, file_name):
with open(file_name, 'w') as f:
for link in sorted(links):
f.write(link + "\n")
|
d93401a8edaf55d6c1993cf0f057f7d0ed606abc | xuyinhao/test_study | /4dict/4dict_test.py | 893 | 3.84375 | 4 | #字典 dict 映射mapping
#1.创建字典
# dstr={'a':'1','b':'2','c':'3'}
# print(dstr['b'])
#
# dstr1=[('name','gab'),('age',24)]
# ndstr1=dict(dstr1)
# print(ndstr1)
#
# dstr2=dict(name='gg',age=23)
# print(dstr2)
#2.基本字典操作
# print(len(dstr2)) #len(d) 键值对个数
# print(dstr2['name']) #特定键 对应的value
# dstr2['sex']='man'
# print(dstr2)
# dstr2['name']='ggnew' #键 赋值,或者新添加
# print(dstr2)
# del dstr2['sex'] #删除某个键
# print(dstr2)
# print('name' in dstr2) # 判断某个键是否存在
#3.字典格式化字符串
#可以在 %(key)s 来打印 value值
# dt={'a':'1','b':'2','c':'3'}
# print('c\'s value is %(c)s ' %dt)
# tmp='''
# title
# %(title)s
# digital
# %(digital)d
# '''
# print(tmp)
# data={'title':'python','digital':22222222222}
# print(tmp%data)
#4 字典的方法
|
cb768ad889997bbbe64f2a40605d12ced6b4dd52 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#253 Sum without highest and lowest number.py | 646 | 3.53125 | 4 | # Task
# Sum all the numbers of a given array ( cq. list ), except the highest and the
# lowest element ( by value, not by index! ).
#
# The highest or lowest element respectively is a single element at each edge,
# even if there are more than one with the same value.
#
# Mind the input validation.
#
# Example
# { 6, 2, 1, 8, 10 } => 16
# { 1, 1, 11, 2, 3 } => 6
# Input validation
# If an empty value ( null, None, Nothing etc. ) is given instead of an array,
# or the given array is an empty list or a list with only 1 element, return 0.
def sum_array(arr):
return sum(sorted(arr)[1:-1]) if isinstance(arr, list) and len(arr) > 2 else 0
|
7c655519c6ae9eef41c00977e057cf577c24d028 | Dzhano/Python-projects | /nested_loops/cinema_tickets.py | 905 | 3.796875 | 4 | all_seats = 0
student_seats = 0
standard_seats = 0
kid_seats = 0
movie_name = input()
while movie_name != "Finish":
taken_seats = 0
counter = 0
seats = int(input())
type_seat = input()
while type_seat != "End":
counter += 1
all_seats += 1
taken_seats += 1
if type_seat == "student":
student_seats += 1
elif type_seat == "standard":
standard_seats += 1
elif type_seat == "kid":
kid_seats += 1
if counter == seats:
break
type_seat = input()
print(f"{movie_name} - {((counter * 100) / seats):.2f}% full.")
movie_name = input()
print(f"Total tickets: {all_seats}")
print(f"{((student_seats * 100) / all_seats):.2f}% student tickets.")
print(f"{((standard_seats * 100) / all_seats):.2f}% standard tickets.")
print(f"{((kid_seats * 100) / all_seats):.2f}% kids tickets.") |
ecabf9541e40a6b20b598e5c8b45cca26d24cb14 | Code360In/oracle-july20 | /day_02/labs/lab_01_participant_solutions.py | 3,407 | 3.703125 | 4 | From Suvarchala Alamur to Everyone: 11:43 AM
Hi Purushotam
N=(1,2,3,4,5,6,7,8,9,10)
for i in N:
print(5, "X", i, "=", 5*i)
o/p for the above code came as
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
From Saumya Tripathi to Me: (Privately) 11:45 AM
#Input
c = input('Enter a number:')
#Process
int_c = int(c)
range_list = list(range(10))
#Output
for i in range_list:
print(c,' X ', i+1,' = ', int_c*(i+1))
From mukeskuk to Everyone: 11:47 AM
#input
num = int(input("Enter number for table:"))
i = 0
#process
while i < 10:
i=i+1
print(num,"* " ,i, "=", num*i)
From Deeptiman Rath to Everyone: 11:47 AM
>>> x=range(1,11)
>>> y=5
>>>for N in x:
print(y ,'*',N,'=',N*y)
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
From Anjani Verma to Everyone: 11:48 AM
x = int(input('Enter the number for Table: '))
for i in range(1,11,1):
print(x, ' X ',i, ' = ' ,x*i)
output:
From Munirathna G to Me: (Privately) 11:48 AM
num = (int(input("Please enter number ")))
N=10
for i in range(1, N+1):
print(num, "X", i ,"=", (num*i) )
From Anjani Verma to Everyone: 11:48 AM
Enter the number for Table: 5
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
From Biswanath Mahapatra to Everyone: 11:49 AM
N=5
for i in range(1,11):
print(N,"X",i,"=",N*i)
From Ritesh Srivastava to Me: (Privately) 11:51 AM
N = int(input('Enter the number for Table: '))
x = 1
while x < 11:
multi = N * x
print(N, 'X', x, '=', multi)
x += 1
From Arpita Sengupta to Me: (Privately) 11:53 AM
N=int(input("Enter user number: "))
for i in range(1,11):
print(N,"X",i,'=', N*i)
From Munirathna G to Me: (Privately) 11:56 AM
Hi Purushotham, I have a doubt
When I print this
x = range(1, 10)
print(type(x))
Output is <class 'range’>
So when we say
for i in range(1, 10):
print(i)
In the above code,
for loop is accepting data which is of type range,
which means we can datatype of iterator can be range
just like list or string
Is my understanding right
or is for loop converting this "range(1, 10)” to a list internally
From Anjani Verma to Everyone: 11:59 AM
code for diamond
line =3
k = 2 * line - 2
for i in range(0, line):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = line - 2
for i in range(line, -1, -1):
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
for j in range(0, i + 1):
print("* ", end="")
print("")
From Ritesh Srivastava to Me: (Privately) 12:02 PM
With for loop:
N = int(input('Enter the number for Table: '))
x = 11
for x in range(1, x):
multi = N * x
print(N, 'X', x, '=', multi)
x += 1
From Kaushik Rout to Everyone: 12:03 PM
# Program to display the multiplication table
# Output Sample
'''
5 x 1 = 5
5 x 2 = 10
.
.
.
5 x 10 = 50
'''
# Input
N = int(input('Enter the number : '))
# Process
for i in range(1, 10+1):
product = N*i
#print (N + 'x '+ i + '= ' + product)
print (N, 'x', i, '=', product)
# Output
|
f09e0df6ab73916b90887a566dc1bab89a824f1a | indraastra/nn-ocr | /archive/cjk_utils.py | 718 | 3.609375 | 4 | import random
CJK_START = 0x4E00
CJK_END = 0x9FD5
numbers = '零一二三四五六七八九'
def random_glyph():
'''Returns a character in the unified CJK range.'''
return chr(random.randrange(CJK_START, CJK_END))
def random_decimal_glyph():
'''Returns a single-digit number.'''
return random.choice(numbers)
def glyphs_by_range(start=CJK_START, end=CJK_END, limit=None):
if limit:
end = start + limit
for i in range(start, end):
yield chr(i)
if (__name__ == '__main__'):
print("Random CJK Character: ", random_glyph())
print("Random CJK Number: ", random_decimal_glyph())
print("CJK range, first 10 characters: ",
list(glyphs_by_range(limit=10)))
|
ebcec35b39afe7d90de1fdb240dc2513c7c79f0f | AvengerDima/Python_Homeworks | /Homework_1(1-6).py | 2,419 | 4.125 | 4 | import math
#Задача №1
print("Задача №1 \n Задание: Найти результат выражения для произвольных значений a,b,c: a + b * ( c / 2 ) \n Решение:")
a = 2
b = 4
c = 6
decision = a + b * (c / 2)
print(" a = %d; b = %d; c = %d; \n a + b * (c / 2) = %d \n" % (a, b, c, decision))
#----------------------------------------------------
#Задача №2
print("Задача №2 \n Задание: Найти результат выражения для произвольных значений a,b: (a**2 + b**2) % 2 \n Решение:")
a = 2
b = 4
remainder = (a**2 + b**2) % 2
print(" a = %d; b = %d; \n (a**2 + b**2) остаток от деления 2 = %d \n" % (a, b, remainder))
#----------------------------------------------------
#Задача №3
print("Задача №3 \n Найти результат выражения для произвольных значений a,b,c: ( a + b ) / 12 * c % 4 + b \n Решение:")
a = 2
b = 4
c = 6
result = (a + b) / 12 * c % 4 + b
print(" a = %d; b = %d; c = %d; \n (a + b) / 12 * c остаток от деления 4 + b = %d\n" % (a, b, c, result))
#----------------------------------------------------
#Задача №4
print("Задача №4 \n Найти результат выражения для произвольных значений a,b,c: (a - b * c ) / ( a + b ) % c")
a = 2
b = 4
c = 6
answer = (a - b * c) / (a + b) % c
print(" a = %d; b = %d; c = %d; \n (a - b * c) / (a + b) остаток от деления c = %d \n" % (a, b, c, answer))
#----------------------------------------------------
#Задача №5
print("Задача №5 \n Найти результат выражения для произвольных значений a,b,c: |a - b| / (a + b)**3 - cos(c)")
a = 2
b = 4
c = 6
otvet = abs(a - b) / (a + b)**3 - math.cos(c)
print(" a = %d; b = %d; c = %d; Ответ: %.2f" % (a, b, c, otvet))
print("\n")
#----------------------------------------------------
#Задача №6
print("Задача №6 \n Найти результат выражения для произвольных значений a,b,c: (ln(1 + c) / -b)**4 + |a|")
a = 2
b = 4
c = 6
expression = (math.log (1 + c) / -b)**4 + abs(a)
print(" a = %d; b = %d; c = %d; Ответ: = %.2f" % (a, b, c, expression))
#---------------------------------------------------- |
7537ac2ffd73eed82b7d30e07ff3370098575a5e | wiput1999/PrePro60-Python | /Onsite/Week1/percent_f.py | 233 | 3.78125 | 4 | """ %d """
def main():
""" Display string """
text = float(input())
print("|%.2f|" %(text))
print("|+%.2f|" %(text))
print("|%10.2f|" %(text))
print("|%-10.2f|" %(text))
print("|%010.2f|" %(text))
main()
|
b9bdbd13dbf7d3ab93e1447b550ea321dbffaf40 | cooldld/learning_python_4th | /ch25_class_tree2.py | 614 | 4.0625 | 4 | class C2: pass
class C3: pass
class C1(C2, C3):
def setname(self, who):
self.name = who #对特殊参数self做赋值操作,可以把属性添加到实例中
print('I1 = C1()')
I1 = C1()
'''
error!!!
AttributeError: 'C1' object has no attribute 'name'
print('I1.name =', I1.name)
'''
print("I1.setname('bob')")
I1.setname('bob')
print('I1.name =', I1.name)
print()
print('I2 = C1()')
I2 = C1()
'''
error!!!
AttributeError: 'C1' object has no attribute 'name'
print('I2.name =', I2.name)
'''
print("I2.setname('tom')")
I2.setname('tom')
print('I2.name =', I2.name)
print('I1.name =', I1.name)
|
cbd4017e7a093e11d5ee99d82429ef42ad450fae | zzq5271137/learn_python | /18-装饰器/07-wraps.py | 1,798 | 4.125 | 4 | """
wraps装饰器
"""
from functools import wraps
def greet(func):
def wrapper(*args, **kwargs):
print('func start execute')
func(*args, **kwargs)
print('func end execute')
return wrapper
"""
下面的代码, 在add()函数上加上@greet装饰器, 等价于以下这种写法:
def add(x, y):
print('%d + %d = %d' % (x, y, x + y))
add = greet(add)
而greet()函数返回一个wrapper()函数, 即add实际指向的是greet()返回的wrapper()函数,
所以打印add.__name__的值为wrapper
"""
@greet
def add(x, y):
print('%d + %d = %d' % (x, y, x + y))
def minus(x, y):
print('%d - %d = %d' % (x, y, x - y))
# 在Python中, 所有东西都是对象, 函数也不例外
# 函数有一个__name__属性, 这个属性记录了该函数的名字;
# 观察不加@greet装饰器和加上@greet装饰器后, __name__值的不同
print(add.__name__)
print(minus.__name__)
print("#############################################################")
"""
以上的现象, 其实会造成一些问题, 因为有时候我们可能需要获取某函数的名字, 但如果加上装饰器该函数的名字就会改变的话,
就会造成问题; 所以需要使用wraps装饰器, 使得即使函数使用装饰器, 但是它的__name__属性的值依然保持原来的那个值;
"""
def greet2(func):
@wraps(func) # @wraps装饰器的使用, 把它加包裹住func()真正运行的位置的函数的顶部(以后要养成习惯, 自定义装饰器的时候一定要加@wraps装饰器)
def wrapper(*args, **kwargs):
print('func start execute')
func(*args, **kwargs)
print('func end execute')
return wrapper
@greet2
def multiple(x, y):
print('%d * %d = %d' % (x, y, x * y))
print(multiple.__name__)
|
8c966bb63a0fd3c19e92806e89c4d9c25948948c | Darshonik/saturday_python | /ideone_hUGooX.py | 233 | 3.71875 | 4 | for i in range(1,4):
for j in range(2,i-1,-1):
print(" "),
for k in range(0,(2*i-1),+1):
print("*"),
print
for i in range(2,0,-1):
for j in range(2,i-1,-1):
print(" "),
for k in range(0,(2*i-1),+1):
print("*"),
print |
7a5f54322d24fccdac558d61be0ace5ad8b2c513 | ChandrashekharIyer/MovieRec-2.0 | /rate.py | 3,491 | 3.546875 | 4 | from Tkinter import *
import csv
import time
import tkMessageBox
import operator
import recom
'''rating'''
def csv_to_list(csv_file, delimiter=','):
"""
Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table.
"""
with open(csv_file, 'r') as csv_con:
reader = csv.reader(csv_con, delimiter=delimiter)
return list(reader)
def rate():
'''
gui that enables user to rate movies
'''
top = Tk()
top.geometry("400x400" )
top.resizable(0,0)
title = Label(top, text = "\t\t\tRate Movies")
title.pack(side = LEFT)
title.place(x = "20", y = "20")
movieName = Label(top, text = "Movie")
movieName.pack(side = LEFT)
movieName.place(x = "20", y = "80")
m = Entry(top, bd =5)
m.pack(side = LEFT)
m.place(x = "80", y = "80")
def select():
'''
reads movie-name, rating.
writes user-id, movie-id, rating and timestamp into rate.csv
'''
flag = 0
movie = m.get()
timestamp = time.time()
rating = var.get()
fl = open("currentUserID.txt", "r")
userID = int(fl.read())
fl.close()
print rating
with open('movies.csv' , 'rb') as csvfile:
dataReader = csv.reader(csvfile, delimiter = ',')
for row in dataReader:
if row[1] == movie:
movieID = row[0]
flag = 1
if flag == 0:
tkMessageBox.showinfo('Not Found', 'Movie not found. Please try again.')
with open('ratings.csv', 'ab') as csvfile:
dataWriter = csv.writer(csvfile, delimiter=',')
dataWriter.writerow([userID] + [movieID] + [rating] + [timestamp])
tkMessageBox.showinfo("Success!", "Your rating has been saved!")
rate = csv_to_list("ratings.csv")
for j in range (0,1000210) :
rate[j] = map(int, rate[j])
rate = sorted (rate, key= operator.itemgetter(0))
with open("ratings.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(rate)
var = IntVar()
R1 = Radiobutton(top, text="1", variable=var, value=1)
R1.pack( anchor = W )
R1.place(x = "20", y = "120")
R2 = Radiobutton(top, text="2", variable=var, value=2)
R2.pack( anchor = W )
R2.place(x = "80", y = "120")
R3 = Radiobutton(top, text="3", variable=var, value=3)
R3.pack( anchor = W)
R3.place(x = "140", y = "120")
R4 = Radiobutton(top, text="4", variable=var, value=4)
R4.pack( anchor = W )
R4.place(x = "200", y = "120")
R5 = Radiobutton(top, text="5", variable=var, value=5)
R5.pack( anchor = W )
R5.place(x = "260", y = "120")
save = Button(top, text = "Save", command = select)
save.pack(side = BOTTOM)
save.place(x = "90", y = "200")
def rateAgain():
top.destroy()
rate()
rateAgain = Button(top, text = "Rate Again", command = rateAgain)
rateAgain.pack(side = RIGHT)
rateAgain.place(x = "140", y = "200")
recommend = Button(top, text = "Recommend", command = recom.recom)
recommend.pack(side = RIGHT)
recommend.place(x = "230", y = "200")
top.mainloop()
rate()
|
790fdcc6b026f61abdd7145c4b18ff94211114c9 | alixoallen/todos.py | /dissecando numero.py | 286 | 3.96875 | 4 | numero=int(input('qual o numero vai digitar ?'))
u=numero//1%10
d=numero//10%10
c=numero//100%10
m=numero//1000%10
print('sua unidade é de {}'.format(u))
print('sua dezena é de {:.0f}'.format(d))
print('sua centena é de {:.0f}'.format(c))
print('seu milhar é de {:.0f}'.format(m))
|
c0e3411d9f998d99eff349aaf124106506997f42 | peterashwell/python-dpath | /dpath.py | 2,008 | 3.9375 | 4 | def dpath(dikt):
"""Helper to create a DPath that is nice to read e.g. dpath(my_dict)['a', 'b']
:param dikt: Dictionary to wrap in DPath
:return: A DPath object
"""
return DPath(dikt)
class DPath:
"""dpath is a tool for navigating multidimensional map structures easily
>>> from pprint import pprint # for consistency of dict assert
>>> my_dict = {'eggs': {'ham': 4, 'bacon': {23: 3}}, ('cheese',): 666, 'cheese': 42}
>>> x = dpath(my_dict)
>>> x['foo']
>>> x['eggs', 'bacon', 23, 'bar']
>>> x[('ham',)]
>>> x[('cheese',)]
666
>>> x['cheese']
42
>>> x['eggs', 'ham']
4
>>> x['eggs', 'bacon', 23]
3
>>> pprint(x['eggs', 'bacon'])
{23: 3}
>>> pprint(x['eggs'])
{'bacon': {23: 3}, 'ham': 4}
>>> pprint(x.unwrap())
{'cheese': 42, 'eggs': {'bacon': {23: 3}, 'ham': 4}, ('cheese',): 666}
"""
def __init__(self, dikt):
if not isinstance(dikt, dict):
raise ValueError('Wrong type: {0}, need dict'.format(type(dikt)))
self.dikt = dikt
def unwrap(self):
return self.dikt
def __getitem__(self, *args):
# Make args consistently iterable if 1 or many passed
# Also handle weird case when single key is used that is a single element tuple
# e.g. dpath({'eggs': 2, ('eggs',): 3})['eggs'] -> 2 or 3?
if isinstance(args[0], tuple) and len(args[0]) > 1:
path = args[0]
else:
path = args
# Try to follow path until we can't
node = self.dikt
for path_elem in path:
# Can't continue because trying to follow path into non-dict
if type(node) is not dict:
return None
# Can't continue because no key matching path elem
if path_elem not in node:
return None
node = node[path_elem]
return node
def __setitem__(self, *path):
raise NotImplementedError('Coming soon...')
|
800fb7229f9882a24f22e6ad53b3327075d504ca | ksilberbauer/coderdojo-python | /exercises/ex3.py | 600 | 4.3125 | 4 | secret_word = input("Enter a secret word:")
guess = ""
guessed_letters = ""
correct_letters = ""
emergency_break = 0 # you'll thank me later ;)
# TODO: the goal is to ask the user to guess each letter in the secret_word, one at a time
for letter in secret_word:
while guess is not letter and emergency_break < 100:
# TODO: keep track of all the incorrect guesses, and print them for the user as they guess
emergency_break += 1
# TODO: keep track of the correct guesses, and print the (partial) word each time the user guesses a new letter correctly
print "You got it!" |
fd75c7d25279ae736c29af155608b17c4f9294cb | alextickle/zelle-exercises | /ch9/vball.py | 2,825 | 3.921875 | 4 | # vball.py
import random
import math
def main():
printIntro()
n, probA, probB = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printIntro():
print "This program simulates a game of volleyball between two players A and B"
print "with given serve win probabilities."
def getInputs():
n = input("Please enter the number of matches to simulate: ")
probA = input("Please the probability that A scores on his/her serve (0-1): ")
probB = input("Please the probability that B scores on his/her serve (0-1): ")
return n, probA, probB
def simNGames(n, probA, probB):
winsA = winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA = winsA + 1
else:
winsB = winsB + 1
return winsA, winsB
def simOneGame(probA, probB):
scoreA = scoreB = 0
serving = "A"
while gameOver != True:
if serving == "A":
if random.random() < probA:
scoreA = scoreA + 1
else:
serving = "B"
else:
if random.random() < probB:
scoreB = scoreB + 1
else:
serving = "A"
return scoreA, scoreB
return scoreA, scoreB
def gameOver(scoreA, scoreB):
if abs(scoreA - scoreB) >= 2 and (scoreA > 15 or scoreB > 15):
return True
else:
return False
def printSummary(winsA, winsB):
print "Wins for A: %d (%0.1f%%)" % (winsA, float(winsA)/n * 100)
print "Wins for B: %d (%0.1f%%)" % (winsB, float(winsB)/n * 100)
def vballmain():
printIntrov()
n, probA, probB = getInputsv()
winsA, winsB = simNGamesv(n, probA, probB)
printSummaryv(winsA, winsB)
def printIntrov():
print "This program simulates a game of volleyball between two players A and B"
print "with given serve win probabilities."
def getInputsv():
n = input("Please enter the number of matches to simulate: ")
probA = input("Please the probability that A scores on his/her serve (0-1): ")
probB = input("Please the probability that B scores on his/her serve (0-1): ")
return n, probA, probB
def simNGamesv(n, probA, probB):
winsA = winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA = winsA + 1
else:
winsB = winsB + 1
return winsA, winsB
def simOneGamev(probA, probB):
scoreA = scoreB = 0
serving = "A"
while gameOverv != True:
if serving == "A":
if random.random() < probA:
scoreA = scoreA + 1
else:
serving = "B"
else:
if random.random() < probB:
scoreB = scoreB + 1
else:
serving = "A"
return scoreA, scoreB
return scoreA, scoreB
def gameOverv(scoreA, scoreB):
if abs(scoreA - scoreB) >= 2 and (scoreA > 15 or scoreB > 15):
return True
else:
return False
def printSummaryv(winsA, winsB):
print "Wins for A: %d (%0.1f%%)" % (winsA, float(winsA)/n * 100)
print "Wins for B: %d (%0.1f%%)" % (winsB, float(winsB)/n * 100)
main()
|
13bc33f51ed822bb7e5b4af8dac6cf7d00eda048 | 26XINXIN/leetcode | /212_word_search_2.py | 2,038 | 3.640625 | 4 | class Solution:
def __init__(self):
pass
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
self.n = len(board)
if not self.n:
return []
self.m = len(board[0])
words = set(words)
result = list()
for word in words:
if self.containsWord(word, board):
result.append(word)
return result
def containsWord(self, word, board):
if len(word) == 0:
return True
for i in range(self.n):
for j in range(self.m):
if board[i][j] == word[0]:
if self.findPath(word[1:], board, {(i, j)}, (i, j)):
return True
return False
def findPath(self, word, board, path, current_position):
print(path)
if not word:
return True
valid_steps = self.findValidStep(board, path, current_position)
for i, j in valid_steps:
if board[i][j] == word[0]:
new_path = set(path)
new_path.add((i, j))
if self.findPath(word[1:], board, new_path, (i, j)):
return True
return False
def findValidStep(self, board, path, current_position):
i, j = current_position
valid_steps = [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]
valid_steps = [s for s in valid_steps if s not in path]
valid_steps = filter(lambda pos: (0 <= pos[0] < self.n and 0 <= pos[1] < self.m), valid_steps)
return valid_steps
board = [
["b","a","a","b","a","b"],
["a","b","a","a","a","a"],
["a","b","a","a","a","b"],
["a","b","a","b","b","a"],
["a","a","b","b","a","b"],
["a","a","b","b","b","a"],
["a","a","b","a","a","b"]]
words = ["aabbbbabbaababaaaabababbaaba"]
#,"abaabbbaaaaababbbaaaaabbbaab","ababaababaaabbabbaabbaabbaba"]
print(Solution().findWords(board, words))
|
010805bbbd7131ffa996d4111f0e0cdc0781a281 | SrikanthreddyR/BasicPythonPrograms | /computing paradox.py | 462 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 12:52:23 2019
@author: Admin
"""
n=int(input())
songs_list=input();
songs_list=list(map(int,songs_list.split()))
fav_song_pos=int(input())
fav_song=songs_list[fav_song_pos-1]
#print(fav_song,"fav song")
sorted_list=songs_list.copy()
#print(sorted_list,"cpopied");
sorted_list.sort()
#print(sorted_list, "sorted");
for i in range(n):
if fav_song==sorted_list[i]:
print(i+1)
break; |
80e59af89ade57971e7838b66333c0b7858596e4 | nullscc/pythoncode | /print.py | 149 | 3.59375 | 4 | #!/usr/bin/python
A = input("input A:")
B = input("input B:")
print(A)
print(B)
sum = A+B
print(sum)
print('A+B =', A+B)
print('你好,python')
|
872ab905861ad57b2a2e1a55a5126066e2517b43 | BlairBejan/DojoAssignments | /Python/printnames.py | 1,280 | 3.96875 | 4 | def printnames(x):
for i in range(len(x)):
name = ""
for val in x[i].itervalues():
name += val + " "
print name
# printnames([
# {'first_name': 'Michael', 'last_name' : 'Jordan'},
# {'first_name' : 'John', 'last_name' : 'Rosales'},
# {'first_name' : 'Mark', 'last_name' : 'Guillen'},
# {'first_name' : 'KB', 'last_name' : 'Tonel'}
# ])
def printusers(x):
for key in x.iterkeys(): #looping through keys in dict gives students, instructers
print key
for i in range(len(x[key])): # looping through each array in students and instructers
name = ""
for val in x[key][i].itervalues(): #looping through array indexes
name += val + " "
name = name[:-1].upper()
print "{} - {} - {}".format(i, name, len(name)-1)
# printusers({
# 'Students': [
# {'first_name': 'Michael', 'last_name' : 'Jordan'},
# {'first_name' : 'John', 'last_name' : 'Rosales'},
# {'first_name' : 'Mark', 'last_name' : 'Guillen'},
# {'first_name' : 'KB', 'last_name' : 'Tonel'}
# ],
# 'Instructors': [
# {'first_name' : 'Michael', 'last_name' : 'Choi'},
# {'first_name' : 'Martin', 'last_name' : 'Puryear'}
# ]
# }) |
183fb9ae59b0e84ca73aa33a8005c75f41d2ef7d | zpinto/learn-git-with-hack | /problems/problem1/tester1.py | 474 | 3.78125 | 4 | from answer1 import Solution
reverse = Solution().reverse
testcases = [(123, 321), (-123, -321), (120, 21)]
print("Running Unit Tests for Problem 1:\n")
correct_count = 0
for case in testcases:
result = reverse(case[0])
print("Input: " + str(case[0]))
print("Output: " + str(result))
print("Expected Output: " + str(case[1]) + "\n")
if result == case[1]:
correct_count += 1
print("Score: " + str(correct_count) + "/" + str(len(testcases)))
|
311e1318e18feeab6083303d0651ef9482382c2c | dunitian/BaseCode | /python/1.POP/1.base/03.3.elif.py | 422 | 3.6875 | 4 | input_int = int(input("请输入(1-7)"))
# if后面的:,tab格式,else if 现在是elif
if input_int == 1:
print("星期一")
elif input_int == 2:
print("星期二")
elif input_int == 3:
print("星期三")
elif input_int == 4:
print("星期四")
elif input_int == 5:
print("星期五")
elif input_int == 6:
print("星期六")
elif input_int == 7:
print("星期日")
else:
print("别闹") |
0495d51899205b08c72438547135b25804c31dd9 | s10th24b/DNN_study | /practice/16_StackedRNNWithSoftMaxLayer.py | 5,274 | 3.5 | 4 | # 이전 15강 LongLong에서는 RNN이 하나밖에 없었다. 그래서 정확도가 낮았음
# 이제는 RNN을 쌓아서.
# Cell을 추가. MultiRNNCell
import tensorflow as tf
import numpy as np
import pdb
import sys
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# 하지만, 만약에 엄~청나게 긴 문자열이라면?
sentence = ("if you want to build a ship, don't drum up people together to collect wood and don't assign them tasks and work, but rather teach them\
to long for the endless immensity of the sea")
# 여러개의 배치를 준다.
# dataset
# 0 if you wan -> f you want
# 1 f you want -> you want
# 2 you want -> you want t
# 3 you want t -> ou want to
# ...
# 168 of the se -> of the sea
# 169 of the sea -> f the sea.
char_set = list(set(sentence))
char_dic = {w: i for i, w in enumerate(char_set)}
idx2char = list(set(sentence)) # index -> char
print("idx2char:", idx2char)
char2idx = {c: i for i, c in enumerate(idx2char)} # chat -> idx
print("char2idx:", char2idx)
data_dim = len(char_set)
hidden_size = len(char_set)
num_classes = len(char_set)
seq_length = len(char_set)-1
print("char_set:", char_set)
print("char_dic:", char_dic)
dataX = []
dataY = []
for i in range(0, len(sentence) - seq_length):
x_str = sentence[i:i+seq_length]
y_str = sentence[i+1:i+seq_length+1]
print(i, x_str, '->', y_str)
x = [char_dic[c] for c in x_str] # x str to index
y = [char_dic[c] for c in y_str] # y str to index
dataX.append(x)
dataY.append(y)
batch_size = len(dataX)
X = tf.placeholder(tf.int32,[None,seq_length])
Y = tf.placeholder(tf.int32,[None,seq_length])
X_one_hot = tf.one_hot(X,num_classes)
cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size,state_is_tuple=True)
######################
cell = tf.contrib.rnn.MultiRNNCell([cell] * 3, state_is_tuple=True) # 깊게 팔수있으.
# 그리고 RNN에서도 CNN에서처럼 소프트맥스를 마지막에 붙여주자
# softmax에 넣으려면 크기에 맞게 reshape
# X_for_softmax = tf.reshape(outputs,[-1, hidden_size])
# 어려워보이나, 그냥 기계적으로 이렇게 한다고만 알면 됨.
# 이렇게 하면 output들마다 크기가 hidden_size로 되고 Stack처럼 쌓여
# softmax(??... softmax취하지도 않는데 왜 softmax layer라고 이름붙인거지 여기선..?)의 입력으로 들어간다.
# 그냥 fully-connected-layer라고 하는게 좋을듯.
# 그럼 이제 softmax의 output이 나온다. 그걸 어떻게 펼쳐줘야하나?
# outputs = tf.reshape(outputs,[batch_size,seq_length,num_classes])
######################
initial_state = cell.zero_state(batch_size,tf.float32)
outputs, _states = tf.nn.dynamic_rnn(cell,X_one_hot,initial_state=initial_state,dtype=tf.float32)
X_for_softmax = tf.reshape(outputs,[-1, hidden_size])
softmax_w = tf.get_variable("softmax_w",[hidden_size,num_classes])
softmax_b = tf.get_variable("softmax_b",[num_classes])
outputs = tf.matmul(X_for_softmax,softmax_w) + softmax_b # (= softmax output)
outputs = tf.reshape(outputs,[batch_size,seq_length,num_classes]) # softmax output을 펼쳐준다
weights = tf.ones([batch_size,seq_length])
seq_loss = tf.contrib.seq2seq.sequence_loss(logits=outputs,targets=Y,weights=weights)
# 사실, 저 logit에는 activation 함수를 거치지 않은 값을 넣어야한다. 그래야 좋은성능.
# RNN에서 output된 값은 이미 activation을 거친 값이기에 logit으로 넣는데에 불안정하다
# 그래서 그 값을 reshape해주고 WX+b의 형태인 affine sum으로 다시 정리를 해준후
# logit으로 주어야 학습이 잘된다
mean_loss = tf.reduce_mean(seq_loss)
optimizer = tf.train.AdamOptimizer(learning_rate=0.1).minimize(mean_loss)
prediction = tf.argmax(outputs,axis=-1)
from os import system
system('clear')
res= []
# 이제 학습해야지.
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(2000):
l, _, result = sess.run([mean_loss, optimizer,outputs], feed_dict={X:dataX, Y:dataY})
# print("loss:", l)
result, outputs_res = sess.run([prediction, outputs], feed_dict={X: dataX})
# print("outputs_res:", outputs_res)
# print("outputs_res.shape:", outputs_res.shape)
# print("output_res -> result:", result)
# print("result.shape:", result.shape)
# print("np.squeeze(result):", np.squeeze(result))
# print("np.squeeze(result).shape:", np.squeeze(result).shape)
result = result[0]
# print("result:", result)
# print("np.squeeze(result):", np.squeeze(result))
# print("np.squeeze(result).shape:", np.squeeze(result).shape)
# for c in np.squeeze(result):
# print(c)
# print("np.squeeze(result).shape:", np.squeeze(result).shape)
result_str = [idx2char[c] for c in np.squeeze(result)]
origin_str = [idx2char[c] for c in np.squeeze(dataY[0])]
# sys.stdout.flush()
sys.stdout.write("origin_str:{0} \n\rresult_str:{1}\r".format(origin_str,result_str))
# print("origin_str:",origin_str)
# print("result_str:",result_str)
res = result_str
print("final result:",res)
# 잘 안된다... 왜? -> 1. logits에서 매끄럽지가 않다. NN이 깊지가 않다.
|
52fe7ccdea8a83ad99880d8f7f4c3e2901fa5154 | Uttam1982/PythonTutorial | /14-Python-Advance/06-python-regex/04-Match-Object/01-Match-Methods/01-Match-Object.py | 660 | 4.15625 | 4 | # Match Object Methods and Attributes
#--------------------------------------------------------------------------------------------
# As you’ve seen, most functions and methods in the re module return a match object
# when there’s a successful match. Because a match object is truthy, you can use it
# in a conditional:
import re
m = re.search('bar','foo.bar.baz')
# Output : <re.Match object; span=(4, 7), match='bar'>
print(m)
# Output : True
print(bool(m))
if re.search('bar','foo.bar.baz'):
print('Found a match')
else:
print('No match found')
#--------------------------------------------------------------------------------------------
|
1c4a158e8eb1b5b46874bd978c995d794fd25b47 | liquse14/MIT-python | /python교육/Code05-11.py | 594 | 3.828125 | 4 | select,answer,numStr,num1,num2=0,0,"",0,0
select= int(input("1.입력한 수식 계산 2.두 수 사이의 합계:"))
if select ==1:
numStr=input("***수식을 입력하세요:")
answer=eval(numStr)
print("%s결과는 %5.1f입니다."%(numStr,answer))
elif select==2:
num1=int(input("***첫번째 숫자를 입력하세요:"))
num2=int(input("***두번째 숫자를 입력하세요:"))
for i in range(num1,num2+1):
answer=answer+i
print("%d+...+%d는 %d입니다."%(num1,num2,answer))
else:
print("1또는 2만 입력해야합니다.")
|
a9a86c29f19171d12fe281254da5ed7a1ec90366 | Kharya3/algo | /merge.py | 814 | 3.578125 | 4 | def merge(a, b, c):
m = len(b)
l = len(c)
cnt = 0
i = j = k = 0
while i < m and j < l:
if b[i] <= c[j]:
a[k] = b[i]
i+=1
else:
a[k] = c[j]
j+=1
cnt+=m-i
k+=1
while j < l:
a[k] = c[j]
j+=1
k+=1
while i < m:
a[k] = b[i]
i+=1
k+=1
return cnt
def merge_sort(a):
cnt = 0
if len(a)>1:
mid = len(a)//2
b = a[:mid]
c = a[mid:]
cnt += merge_sort(b)
cnt += merge_sort(c)
cnt += merge(a, b, c)
b.clear()
c.clear()
return cnt
f = open("file.txt", 'r')
arr = []
for line in f:
a = line
a.rstrip()
arr.append(int(a))
n1 = len(arr)
count = merge_sort(arr)
print(count, arr)
|
443041bcbb1ef4e90adf2017114a6279944f5832 | mgokani/RH | /print_pairs.py | 1,140 | 4.1875 | 4 | """@author: Mirav Gokani
Program that prints pairs of numbers that sum up to n
for example: Given list of numbers 4, 1, 3, 5, 2, 6, 8, 7
Print pairs of numbers whose sum equals 8
>>> pairs([4, 1, 3, 5, 2, 6, 8, 7], 8)
array([[1, 7],
[2, 6],
[3, 5]])
"""
import numpy as np
def pairs(arr1, num):
"""Returns 2D array with pairs of numbers that sum up to num,
else raises Exception
"""
arr2 = []
count = 0
left = 0
right = len(arr1) - 1
arr1 = sorted(arr1)
while left < right:
if arr1[left] + arr1[right] > num:
right -= 1
elif arr1[left] + arr1[right] < num:
left += 1
elif arr1[left] + arr1[right] == num:
arr2.append(arr1[left])
arr2.append(arr1[right])
right -= 1
left += 1
count += 1
if count == 0:
raise Exception("no pair found")
else:
arr2 = np.reshape(arr2, (-1, 2)) # Convert 1D to 2D array
return arr2
if __name__ == "__main__":
import doctest
doctest.testmod()
a = [20, 10, 30, 40, 50]
result = pairs(a, 70)
print(result)
|
a2ead2b560d0f1dddae844a9662b019b99daf0a2 | GermanSumus/Algorithms | /largest_prime_factor.py | 708 | 3.890625 | 4 | '''
# 3
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
def largest_prime(n):
def factors(n):
result = set()
for i in range(1, int(n ** 0.5) + 1):
div, mod = divmod(n, i)
if mod == 0:
result |= {i, div}
return result
primes = []
all_factors = factors(n)
for factor in all_factors:
prime_check = factors(factor)
if len(prime_check) == 2:
primes.append(factor)
print(max(primes))
# Tests
largest_prime(13195)
largest_prime(600851475143)
'''
>>> # 5, 7, 13 ,29 are factors of 13195. 29 is the largest prime
>>> [29]
>>> [5]
'''
|
f0919c93196cc36c4f2c90b59baf518cb9b11b89 | bennyfungc/PROJECT-LRN2L337 | /MergeInterval/mergepairs.py | 706 | 3.71875 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
def start(interval):
return interval.start
result = []
ls = sorted(intervals, key=start)
for interval in ls:
if result and interval.start <= result[-1].end:
result[-1].end = max(interval.end, result[-1].end)
else:
result.append(interval)
return result |
28d6aa1032cefd362da7b2091bddc35714c34e46 | sikorskaewelina/Programowanie_w_data_science_podstawy | /zad12.py | 574 | 4.0625 | 4 | """
12. Utworzyć skrypt z interfejsem tekstowym obliczający n-ty element ciągu Fibonacciego
- wykonać zadanie iteracyjnie i rekurencyjnie
"""
def fib_iteracyjny(x):
pwyrazy = (0, 1)
a, b = pwyrazy
while x > 1:
a, b = b, a + b
x -= 1
return x
x = int(input('Podaj, który element ciągu chcesz policzyć: '))
print(fib_iteracyjny(x))
def fib_rekurencyjny(y):
a, b = 0, 1
for i in range(y-1):
a, b = b, a+b
return a
y = int(input('Podaj, który element ciągu chcesz policzyć: '))
print(fib_rekurencyjny(y)) |
9d32dc93779baf8f337c064f27fdce4b2e8cfbaf | ACENDER/LeetCode | /A01/830.较大分组的位置.py | 637 | 3.71875 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : 830. 较大分组的位置.py @Time : PyCharm -lqj- 2021-1-5 0005
from typing import List
class Solution:
def largeGroupPositions(self, s: str) -> List[List[int]]:
l = list(s)
res = []
n, num = len(l), 1
for i in range(n):
if i == n - 1 or l[i] != l[i + 1]:
if num >= 3:
res.append([i - num + 1, i])
num = 1
else:
num += 1
return res
if __name__ == '__main__':
solution = Solution()
print(solution.largeGroupPositions("xxxxabc"))
|
9103912693778aa9f55b56f1584831b4127a072b | romanvoiers/Python | /Lists.py | 521 | 4.3125 | 4 | # can be used as an inventory system
friends = ["Mike", "John", "Don", "Roman", "Maria"]
print(friends[1]) # Shows a specific element by index. Goes by 0,1,2....
print("I hate " + friends[2])
print(friends[-1]) # Negatives pick from the back of the list
print(friends[3:5]) # Takes a range. First number inclusive second exclusive
friends[0] = "Lola"
print(friends[0])
items = ["potion", "Sword", "Armor"]
print(items)
print(" You dropped the potion")
del(items[0]) # Deletes an item out of the list
print(items)
|
133df5cf96f8bb3dd7128757702f2e2a62d62584 | smanjil/PigLatinTranslator | /pig_latin.py | 2,580 | 3.984375 | 4 | __author__ = 'ano'
class PigLatin:
def __init__(self):
self.choice = raw_input("Enter \n(1) to translate a single word \n(2) to translate a sentence \n(3) to translate word containing hyphens: ")
if self.choice == '1':
self.plainText = raw_input("\nEnter plaintext word : ")
#print self.plaintext
print self.translate_single_word(self.plainText)
elif self.choice == '2':
self.plainText = raw_input("\nEnter a sentence of plaintexts : ")
#print self.plainText
print self.translate_sentence(self.plainText)
elif self.choice == '3':
self.plainText = raw_input("\nEnter a sentence of plaintexts containing hyphens : ")
#print self.plainText
self.translate_sentence_with_hyphens(self.plainText)
else:
print "Wrong Choice!!!!"
def translate_single_word(self , plainText):
vowels = 'aeiou'
vowelsup = vowels.upper()
consonants = 'bcdfghjklmnpqrstvwxyz'
consonantsup = consonants.upper()
if len(plainText) > 0:
if (plainText[0] in vowels or plainText[0] in vowelsup) and (plainText[len(plainText) - 1] in consonants or plainText[len(plainText) - 1] in consonantsup) and plainText[len(plainText) - 1] not in ['y' , 'Y']:
#print plainText[0] , plainText[len(plainText) - 1]
return plainText + 'ay'
elif (plainText[0] in vowels or plainText[0] in vowelsup) and (plainText[len(plainText) - 1] in vowels or plainText[len(plainText) - 1] in vowelsup) and plainText[len(plainText) - 1] not in ['y' , 'Y']:
#print plainText[0] , plainText[len(plainText) - 1]
return plainText + 'yay'
elif (plainText[0] in vowels or plainText[0] in vowelsup) and plainText[len(plainText) - 1] in ['y' , 'Y']:
return plainText + 'nay'
else:
const_char = ""
for char in plainText:
if char in consonants or char in consonantsup:
const_char += char.lower()
else:
break
if plainText[0].isupper():
return plainText[len(const_char):].capitalize() + const_char + 'ay'
else:
return plainText[len(const_char):] + const_char + 'ay'
else:
return "Nil"
def translate_sentence(self , plainText):
strli = plainText.split()
#print strli
newli = []
for i in range(len(strli)):
a = strli.pop()
a = self.translate_single_word(a)
newli.insert(i , a)
newli.reverse()
return ' '.join(newli)
def translate_sentence_with_hyphens(self , plainText):
strli = plainText.split('-')
#print strli
newli = []
for i in range(len(strli)):
a = strli.pop()
a = self.translate_sentence(a)
newli.insert(i , a)
newli.reverse()
print '-'.join(newli)
p = PigLatin()
|
9b0c8380485399bd8bb2e9ad41b9c23bd748d226 | geoffreynyaga/leetcode-challenges-python | /6 move zeros.py | 1,079 | 3.796875 | 4 | """Given an array nums, wriall 0's to tte a function to move he end of it
while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations."""
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# for num in nums:
# if num == 0:
# nums.remove(num)
# nums.append(0)
# return nums
# i = 0
# for j in range(len(nums)):
# if nums[j] != 0:
# nums[i], nums[j] = nums[j], nums[i]
# i = i + 1
# Fastest Solution
j = 0 # position of 1st 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
sol_instance = Solution()
x = sol_instance.moveZeroes([0,1,0,3,12])
print(x, "x")
|
c61e0bcb51dd2fa13fcc80123a913b2cce1e4bd4 | esix/competitive-programming | /e-olymp/~contest-9716/D/main.py | 82 | 3.65625 | 4 | #!/usr/bin/env python3
import re
s = input()
print(len(re.findall(r"\w+", s))) |
09892465db18059bbaf2d1b41f9bbc13786130d8 | LichAmnesia/LeetCode | /python/203.py | 937 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# @Author: Lich_Amnesia
# @Email: alwaysxiaop@gmail.com
# @Date: 2016-09-18 23:12:39
# @Last Modified time: 2016-09-18 23:19:24
# @FileName: 203.py
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
pre, node = None, head
while node:
if node.val == val:
if node.next:
node.val, node.next = node.next.val, node.next.next
else:
if pre and pre.next:
pre.next = None
node = None
else:
return pre
else:
pre, node = node, node.next
return head |
964b829c5cae2b5c3dcb192667e05f37350a2940 | JeanDenisD/Projects | /Shark Project/Shark Project final.py | 8,013 | 3.578125 | 4 | # Problem Definition:
## Deduce TOP-10 Manufacturers by Fuel Efficiency for given year
"""import pandas as pd
year=int(input('Enter the year: '))
def acquisition():
df=pd.read_csv('/Users/jidekickpush/Documents/GitHub/0323_2020DATAPAR/Labs/vehicles/vehicles.csv')
return df
def wrangle(df):
global year
filtered=df[df.Year==year]
return filtered
def analyze(df):
grouped=df.groupby('Make')['Combined MPG'].agg('mean').reset_index()
final=grouped.sort_values('Combined MPG', ascending=False).head(10)
return final
def viz(df):
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
global year
fig,ax=plt.subplots(figsize=(15,8))
barchart=sns.barplot(data=df, x='Make',y='Combined MPG')
plt.title("Top 10 Manufacturers by Fuel Efficiency in", year)
return barchart
def save_viz(plot):
fig=plot.get_figure()
global year
fig.savefig("Top 10 Manufacturers by Fuel Efficiency in",year,".png")
if __name__=='__main__':
data=acquisition()
filtered=wrangle(data)
results=analyze(filtered)
barchart=viz(results)
save_viz(barchart)"""
import pandas as pd
import numpy as np
import re
year=2016
def acquisition():
df=pd.read_csv('/Users/jidekickpush/Documents/GitHub/0323_2020DATAPAR/Labs/module_1/Pipelines-Project/Data/GSAF5.csv', encoding ='cp1252')
return df
def data_cleaning(df):
#From the table overview, we can see the following statements:
#* columns 'unnamed: 22' and 'unnamed: 23' are not referenced in the description of the dataset and doesn't contain any (relevant) information.
#* columns 'Case Number.1' and 'Case Number.2'are duplicates of 'Case Number'
#* columns 'date' cannot be nomalised cause of the differents syntaxes but the information can be extract from column 'Case Number'
#=> Proceed to drop those columns
null_cols = df.isnull().sum()
null_cols
null_cols[null_cols > 0]
df=df.drop(['Unnamed: 22','Unnamed: 23','Case Number.1','Case Number.2','Date'], axis=1)
# Some names of the columns aren't clean or clear enough. Below the list of columns renamed
#* Sex: remove a blank space at the end.
df.rename(columns={'Sex ':'Sex', 'Country':'Place'}, inplace = True)
#Among the total 5900 events registered, only 137 happened before 1700.
#To evaluate only statistically relevant data, events registered before 1700 will not be considered
df=df[df['Year']>1700]
#Let's fix 'Sex' column: Typo found on 2 entrances.
#For 'Place': We've reduced the list of countries from the original set of 196 categories, to 174.
#=>For that purpose we have used both regular expressions and manual replacement.
df.replace({'Sex':{'M ':'M'}}, inplace=True)
#remove end ?
#remove start/end blank spaces
#remove 2nd country after /
#df.columnname.str.replace('word','newword')
df.replace(regex={
r'\?':'',
r'\s\/\s[A-Z\s]+': '',
r'\s$':'', r'^\s':''
}, inplace=True)
#On 'Place' column, manually fixed some duplicates
df.replace({'Place': { 'UNITED ARAB EMIRATES (UAE)':'UNITED ARAB EMIRATES',
'Fiji':'FIJI', 'ST. MAARTIN':'ST. MARTIN',
'Seychelles':'SEYCHELLES',
'Sierra Leone':'SIERRA LEONE',
'St Helena': 'ST HELENA',
'ENGLAND': 'UNITED KINGDOM',
'SCOTLAND': 'UNITED KINGDOM'}
}, inplace=True)
#Normalizing column Activity
#Reduce from the original 1418 unique values on Activity to 5: 'Surfing', 'Swimming', 'Fishing', 'Diving' & 'Others'.
df.rename(columns={'Activity':'unActivity'}, inplace=True)
df_activity = df['unActivity']
activity = []
for a in df_activity:
if re.search(r'Surf[\w\s\,]+|surf[\w\s\,]+|[\w\s\,]+surf[\w\s\,]+', str(a)):
a = 'Surfing'
elif re.search(r'Fish[\w\s\,]+|fish[\w\s\,]+|[\w\s\,]+fish[\w\s\,]+', str(a)):
a = 'Fishing'
elif re.search(r'Spear[\w\s\,]+|spear[\w\s\,]+|[\w\s\,]+spear[\w\s\,]+', str(a)):
a = 'Fishing'
elif re.search(r'Swim[\w\s\,]+|swim[\w\s\,]+|[\w\s\,]+swim[\w\s\,]+', str(a)):
a = 'Swimming'
elif re.search(r'Div[\w\s\,]+|div[\w\s\,]+|[\w\s\,]+div[\w\s\,]+', str(a)):
a = 'Diving'
else: a = 'Others'
activity.append(a)
df['Activity'] = activity
df = df.drop(['unActivity'], axis=1)
#Create a new column for dates, getting the information from the column 'Case Number'
df['Date']=df['Case Number']
df['Date'].replace(regex = {r'.[A-Za-z]$':''}, inplace = True)
#Create a new column for the month, extracting it from the 'Case Number' column
#* check if percentage of unrelevant dates : month missing in the data
#=> drop the rows without specified month
df['Month']=[m[5:7] for m in df['Case Number']]
#Percentage of month not specified in the df is less than 10%, we decided to do not keep them:
# Get 'Months' of indexes for which column month has value 00
indexNames = df[ df['Month'] == '00' ].index
# Delete these row indexes from dataFrame
df.drop(indexNames , inplace=True)
#Normalizing the hour, keeping only the values that correspond to a 24h value
#df['Time'] = df['Time'].replace(regex = {r'\s[\w\-\d\/\()]+|\-[\w\-\d\/]+|j$|^\>|^\<':'', r'h':':'})
#hour = []
#time = df['Time']
#for h in time:
# if re.search(r'\d{2}\:\d{2}', str(h)) == None:
# h = 'Unknown'
# hour.append(h)
#df['Hour'] = hour
#Change column types
#Change the column Fatal (Y/N) to a boolean, normalizing all the entries to True or False.
#The few unknown values have been trated as non fatal.
df.rename(columns={ 'Fatal (Y/N)' : 'Fatal'}, inplace=True)
df = df.replace({'Fatal': { 'N' : '0', 'Y' : '1', 'n' : '0', 'y' : '1', 'UNKNOWN' : '0', 'F' : '0', '#VALUE!' : '0'}})
df['Fatal'].astype(bool)
return df
def filter_by_year(df):
global year
filtered=df[df.Year==year]
return filtered
def display_seasonality_attacks(df):
#Binning the data by season on a new column
season_labels=['Winter','Spring','Summer','Fall']
cutoffs= ['01','04','07','10','12']
bins = pd.cut(df['Month'], cutoffs, labels = season_labels)
df['Season']=bins
#Ratio of attacks per person
seasonality = df.pivot_table(index=['Season'], values=['Date'], aggfunc= len,fill_value=0)
seasonality = seasonality.rename(columns= {'Date':'Count'})
seasonality['Ratio'] = seasonality['Count'] * 100 / seasonality['Count'].sum()
seasonality = seasonality.round({'Ratio':2})
#display(seasonality)
return seasonality
def activity_season(df):
activity_season = df.pivot_table(index=['Activity', 'Season'], values=['Date'], aggfunc= len, fill_value=0)
activity_season = activity_season.rename(columns= {'Date' : 'Count'})
activity_season['Ratio'] = activity_season['Count'] * 100 / activity_season['Count'].sum()
activity_season = activity_season.round({'Ratio' : 2})
activity_season.sort_values(by=['Activity','Ratio'], ascending=False, inplace=True)
print(activity_season)
return activity_season
#def viz(df):
#import matplotlib.pyplot as plt
#import seaborn as sns
#sns.set()
#global year
# fig,ax=plt.subplots(figsize=(15,8))
#barchart=sns.barplot(data=df, x='Activity',y='Count')
#plt.title("Attack per season during the year")
#return barchart
if __name__=='__main__':
data_raw=acquisition()
data_cleaned=data_cleaning(data_raw)
data_filtered=filter_by_year(data_cleaned)
#final_table = data_filtered[['Date', 'Year', 'Month', 'Place', 'Area','Location', 'Activity', 'Sex', 'Fatal']]
#display(final_table.head(10))
data_seasonality = display_seasonality_attacks(data_filtered)
display(data_seasonality)
data_activity_season = activity_season(data_filtered)
#data_viz = viz(data_activity_season)
|
84d8a425d38392d5382503e38699dba396d9dc52 | humachine/AlgoLearning | /leetcode/Done/474_OnesAndZeros.py | 1,961 | 3.578125 | 4 | #https://leetcode.com/problems/ones-and-zeroes/
'''Given an array of binary strings and m, n - where m & represent the number of
zeros and 1s you have respectively, what is the maximum number of strings you
can build from the array.
Inp: ["10", "0001", "111001", "1", "0"], m = 5, n = 3
Out: 4 (With 5 zeros and 3 ones, we can pick out 10, 0001, 1, 0)
Inp: ["10", "0", "1"], m = 1, n = 1
Out: 2 (We can pick out 0 and 1 using just one one and one zero)
'''
class Solution(object):
def findMaxForm(self, strs, m, n):
# counts is a tuple containing the counts of 0s and 1s in the string
counts = [(x.count('0'), x.count('1')) for x in strs]
# results[i][j] = #strings that we can pick using i 0s and j 1s using
# the first k strings
# We finally return results[m][n] after processing all strings
results = [[0]*(n+1) for i in xrange(m+1)]
for zeros, ones in counts:
for i in xrange(m, -1, -1):
for j in xrange(n, -1, -1):
# DP Recursion:
# results[i][j][k] = max(results[i][j][k-1], 1+results[i-zeros][j-ones][k]
# To reduce space used, we drop the 3rd dimension (which represents number of strings processed thus far)
# This is just an example of 0-1 knapsack problem
if i>=zeros and j>=ones:
results[i][j] = max(results[i][j],
1+results[i-zeros][j-ones])
return results[m][n]
s = Solution()
print s.findMaxForm(["10", "0001", "111001", "1", "0"], 5, 3)
print s.findMaxForm(["10", "0", "1"], m = 1, n = 1)
print s.findMaxForm(["0","11","1000","01","0","101","1","1","1","0","0","0","0","1","0","0110101","0","11","01","00","01111","0011","1","1000","0","11101","1","0","10","0111"], 9, 10)
print s.findMaxForm(["0110101","0","11","01","00","01111","0011","1","1000","0","11101","1","0","10","0111"], 9, 20)
|
fe83d42057da0a9517d187e5b7767860538b0e72 | zuhaalfaraj/Introduction-to-Algorithms | /3. Heap/heapSort.py | 877 | 3.515625 | 4 | import numpy as np
def max_heapify(arr,n,i):
node = i
left = 2*i+1
right = 2*i+2
larg= node
if left<n and arr[left]> arr[node]:
larg= left
if right<n and arr[right]> arr[larg]:
larg = right
if larg != i:
arr[i], arr[larg] = arr[larg], arr[i]
max_heapify(arr, n, larg)
def max_heap(arr):
n = len(arr)
half= int(np.floor(n/2))
while half>=0:
max_heapify(arr, n, half)
half-=1
for i in range(n-1,0,-1):
arr[i], arr[0]= arr[0], arr[i]
max_heapify(arr, i, 0)
return arr
if __name__=='__main__':
import time
arr= [4,1,3,2,16,9,10,14,8,7]
lst = [4, 2, 1, 5, 3, 10, 2, 33, 100, 23, 3, 44, 3, 2323, 12, 45, 23, 55, 234]
lst = np.random.rand(700)
lst= list(lst)
t1= time.time()
c= max_heap(lst)
t2 = time.time()
print(t2-t1)
|
f260c93a83b5d8f790a7c7ad690aab8414728027 | Spinnerka/Python-Coursera-Assignments | /Ex10_DistributionByHour.py | 1,019 | 4.0625 | 4 | # 10.2 Write a program to read through the mbox-short.txt and figure out the
# distribution by hour of the day for each of the messages. You can pull the
# hour out from the 'From ' line by finding the time and then splitting the
# string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts,
# sorted by hour as shown below.
name = input("Enter file:")
handle = open(name)
counts = dict()
#find 'from' lines in the txt file and get email address
for line in handle:
line = line.rstrip()
if not line.startswith('From '):
continue
words = line.split()
words = words[5]
words = words.split(':')
words = words[0]
counts[words] = counts.get(words, 0) + 1 #puts the email address in dictionary and counts it
lst = list()
for key, val in counts.items():
lst.append((key,val))
lst = sorted(lst)
for key, val in lst:
print(key,val)
#
|
d2bba48c2511f61e020915b9b61c7b34b60a0713 | Sauvikk/practice_questions | /Level8/Black Shapes.py | 1,390 | 3.78125 | 4 | # Given N * M field of O's and X's, where O=white, X=black
# Return the number of black shapes. A black shape consists of one or more adjacent X's (diagonals not included)
#
# Example:
#
# OOOXOOO
# OOXXOXO
# OXOOOXO
#
# answer is 3 shapes are :
# (i) X
# X X
# (ii)
# X
# (iii)
# X
# X
# Note that we are looking for connected shapes here.
#
# For example,
#
# XXX
# XXX
# XXX
# is just one single connected black shape.
class Solution:
def dfs(self, arr, i, j, visit, r, c):
if i < 0 or i > r - 1:
return
if j < 0 or j > c - 1:
return
if arr[i][j] == 'O' or visit[i][j]:
return
visit[i][j] = True
self.dfs(arr, i + 1, j, visit, r, c)
self.dfs(arr, i - 1, j, visit, r, c)
self.dfs(arr, i, j + 1, visit, r, c)
self.dfs(arr, i, j - 1, visit, r, c)
def sol(self, A):
r = len(A)
c = len(A[0])
count = 0
visit = [[False for j in range(c)] for i in range(r)]
for i in range(r):
for j in range(c):
if A[i][j] == 'X' and not visit[i][j]:
self.dfs(A, i, j, visit, r, c)
count += 1
return count
x1 = ["OOOXOOO",
"OOXXOXO",
"OXOOOXO"]
x= ["XXX",
"XXX",
"XXX"]
print(Solution().sol(x1))
|
55428f2141b836e5de94d1d9c272118ce368c9ca | Khittyroar/Proyecto | /untitled0.py | 4,696 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 13:37:56 2020
@author: fhwx
"""
class Producto:
def __init__(A,Nombre,CodigoProducto,Marca,Precio,Cantidad,CantidadEstanteria,Vendidos):
A.Nom = Nombre
A.Precio = Precio
A.Cant = Cantidad
A.Vendidos = Vendidos
A.CP = CodigoProducto
A.Marca = Marca
A.CantEsta = CantidadEstanteria
Cl1 = Producto("Frijol",1,"LaAbuelita",3000,12,10,0)
Cl2 = Producto("Arroz ",2,"LaAbuelita",5000,6,10,0)
Cl3 = Producto("Huevos",3,"SantaMaria",4500,32,10,1)
Cl4 = Producto("Leche ",4,"SantaMaria",2000,10,10,14)
Productos = (Cl1,Cl2,Cl3,Cl4)
def Stock():
Menu = print('''---Stock---
1: Vendido hoy
2: Inventario de tienda
3: Productos en estanteria
4: Rellenar Inventario en estanteria
5: Volver a tienda
--> ''')
if Menu == "1":
VendidoHoy()
elif Menu == "2":
InventarioTienda()
elif Menu == "3":
InventarioTienda()
elif Menu == "4":
ProductosEstanteria()
elif Menu == "5":
Product = input('''Introduzca el producto
(recuerde que los productos tienen 5 Caracteres por lo que si su
producto tiene menso de 5 caracteres rellene el espacio restante
con espacios " " hasta tener 5)
--> ''')
Agregar = int(input('''Cuanto desea agregar
--> '''))
RellenarProductoEstanteria(Product,Agregar)
else:
Menu = Menu
#/////////////////////////////////////////////////////////////////////////////
def VendidoHoy():
P = open("VendidoHoy","r")
Ver = P.read()
print(Ver)
P.close()
#/////////////////////////////////////////////////////////////////////////////////
def InventarioTienda():
global Productos
for i in Productos:
print(f"{i.Nom} | {i.Cant}")
#///////////////////////////////////////////////////////////////////////////////
def ProductosEstanteria():
global Productos
for i in Productos:
print(f"{i.Nom} | {i.CantEstanteria}")
#///////////////////////////////////////////////////////////////////////////////
def RellenarProductoEstanteria(Product,Agregar):
global Productos
Verificacion = "2"
Contador = 0
Fallos = 0
while Verificacion == "2":
if Contador == 0:
for i in Productos:
#print(i.Nom,Product)
if i.Nom == Product:
Antiguo = i.CantEsta
i.CantEsta = i.CantEsta + Agregar
#
print(f'''
----Cambio realizado----
{i.Nom}|{Antiguo} --> {i.Nom}|{i.CantEsta}''')
Verificacion = input('''Continuar con los cambios
1: si
2: No
--> ''')
Fallos += 1
if Verificacion == "1":
#print("logro")
break
elif Verificacion == "2":
i.CantEsta = i.CantEsta - Agregar
elif Fallos == len(Productos):
print("Producto invalido. Porfavor ingreselos de nuevo")
i.CantEsta = i.CantEsta - Agregar
Fallos = 0
if Verificacion == "1":
break
Product = input('''Introduzca producto
(recuerde que los productos tienen 5 Caracteres por lo que si su
producto tiene menso de 5 caracteres rellene el espacio restante
con espacios " " hasta tener 5)
--> ''')
Agregar = int(input('''Cuanto desea agregar
--> '''))
Contador =+ 1
for i in Productos:
#print(i.Nom,Product)
if i.Nom == Product:
Antiguo = i.CantEsta
i.CantEsta = i.CantEsta + Agregar
print(f'''----Cambio realizado----
{i.Nom}|{Antiguo} --> {i.Nom}|{i.CantEsta}''')
Verificacion = input('''Continuar con los cambios
1: si
2: No
--> ''')
Fallos += 1
if Verificacion == "1":
#print("logro")
break
elif Verificacion == "2":
i.CantEsta = i.CantEsta - Agregar
elif Fallos == len(Productos):
print("Producto invalido. Porfavor ingreselos de nuevo")
i.CantEsta = i.CantEsta - Agregar
if Verificacion == "2":
i.CantEsta = i.CantEsta - Agregar
#
Pausa = input("Regresando") |
2e11af93dff02e3816d782b3926efed048c60906 | jasonluocesc/CS_E3190 | /P6/coins/coins.py | 1,298 | 3.796875 | 4 | # coding: utf-8
from solution import get_coins
import sys
def read_data_from_file(filename):
"""Read problem instance from file. No error handling!
Parameters
----------
filename : str
Returns
-------
target_value : int
The amount we need to make change for using the different denominations.
denominations : list of int, sorted from smallest to largest
The values of different coins, e.g. [1, 2, 5, 10, 20, 50, 100, 200] for the euro.
"""
with open(filename) as f:
target_value, num_denominations = [int(value) for value in f.readline().split()]
denominations = [int(value) for value in f.readline().split()]
return (target_value, denominations)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: coins.py <input_file>")
sys.exit(1)
(target_value, denominations) = read_data_from_file(sys.argv[1])
coins_used = get_coins(target_value, denominations[:])
if coins_used:
print("%(target_value)d = %(maths)s" %
{'target_value': target_value,
'maths': " + ".join("%d * %d" % (coins_used[i], denominations[i]) for i in range(len(denominations)) if coins_used[i])})
else:
print("Cannot form change of %d." % target_value)
|
70fa819a607da8c4d717a3a5b4e9e552a81d68c2 | BrandonSersion/fizzbuzz_using_helper_function | /fizzbuzz.py | 503 | 3.671875 | 4 | def fizz_buzz(fizz, buzz, limit):
def divisible_by(iterator, divisor):
if iterator % divisor == 0:
return True
for i in range(0, limit):
if divisible_by(i, fizz*buzz):
yield "FizzBuzz"
elif divisible_by(i, fizz):
yield "Fizz"
elif divisible_by(i, buzz):
yield "Buzz"
else:
yield str(i)
def main():
print('\n'.join(fizz_buzz(3, 5, 100)))
if __name__ == "__main__":
main() |
e1c75cc3f5319af615ff7822e93b2a5e3a4aba2c | Alexklai92/micro_projects | /text_alignment_on_width.py | 1,818 | 3.53125 | 4 | text = [
"sdajdksa lksjad kja djkas djkasjd asjkd aksjkdajsd sad as das sdas s",
"asdasd asdsad asdasd das ss d asdasd",
"asdasd jkajs jjkk; csnsdan nasdnasd ksadjiksa jsado",
"sdahdjash hasd asd jhajsdha sjdhsjahd sjd as jdhasdsh ajh h",
"dsahjdsah jjh jh kasjd k u uk suk usku ksu",
"sdasd sad ajksd jaksd jkadj kasjdk jaksdj aksjd kajsd kajsdk jaksj dakjsd kajs"
]
def text_alignment_on_width(text):
max_len = max(list(map(len, text)))
new_text = list()
def add_whitespace(line):
words = line.split()
def alignment(n_words, max_len):
new_line = list()
for i in range(len(n_words)):
l_words = len(''.join(n_words))
if max_len > l_words:
if i - 1 != 0:
n_words[i-1] = f"{' '}{words[i-1]}"
else:
new_line = ''.join(words)
new_text.append(new_line)
return new_line
return alignment(n_words, max_len)
new_line = alignment(words, max_len)
return new_line
for line in text:
if len(line) <= max_len:
add_whitespace(line)
for i in new_text:
print(i)
if __name__ == "__main__":
text_alignment_on_width(text)
"""
example:
sdajdksa lksjad kja djkas djkasjd asjkd aksjkdajsd sad as das sdas s
asdasd asdsad asdasd das ss d asdasd
asdasd jkajs jjkk; csnsdan nasdnasd ksadjiksa jsado
sdahdjash hasd asd jhajsdha sjdhsjahd sjd as jdhasdsh ajh h
dsahjdsah jjh jh kasjd k u uk suk usku ksu
sdasd sad ajksd jaksd jkadj kasjdk jaksdj aksjd kajsd kajsdk jaksj dakjsd kajs
"""
|
69dd38e2a4c252eb51549ced7e16c203f3bc23c9 | dmitry741/geekbrains_python | /Python1/lesson3/hw03_normal.py | 3,998 | 4.1875 | 4 | # Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
''' функция возвращает ряд Фибоначчи с n-элемента до m-элемента.
'''
a1, a2 = 1, 1
f = a1 + a2
while f <= m:
if f >= n:
print(f)
a1 = a2
a2 = f
f = a1 + a2
print("печатаем числа Фибоначчи:")
fibonacci(1, 100)
print("\n")
# Задача-2:
# Напишите функцию, сортирующую принимаемый список по возрастанию.
# Для сортировки используйте любой алгоритм (например пузырьковый).
# Для решения данной задачи нельзя использовать встроенную функцию и метод sort()
def merge_sorted_array(A, B):
''' Сливание двух сортированных массивов в один
'''
iA, iB, iC = 0, 0, 0
C = []
while True:
if iA == len(A):
for b in range(iB, len(B)):
C.append(B[b])
break
if iB == len(B):
for a in range(iA, len(A)):
C.append(A[a])
break
if A[iA] < B[iB]:
C.append(A[iA])
iA += 1
else:
C.append(B[iB])
iB += 1
return C
def sort_to_max(A):
''' сортировка массива методом quicksort
'''
if (len(A) < 2):
return A;
curList = []
for a in A:
ls = []
ls.append(a)
curList.append(ls)
while len(curList) > 1:
i = 0
newList = []
while i < len(curList) - 1:
a1 = curList[i]
a2 = curList[i + 1]
res = merge_sorted_array(a1, a2)
newList.append(res)
i += 2
if all([len(curList) % 2 == 1, len(curList) > 1]):
a1 = newList.pop()
a2 = curList[len(curList) - 1]
res = merge_sorted_array(a1, a2)
newList.append(res)
curList = newList
result = []
result.extend(curList[0])
return result;
sortedArray = sort_to_max([2, 10, -12, 2.5, 20, -11, 4, 4, 0])
print(sortedArray)
# Задача-3:
# Напишите собственную реализацию функции filter.
# Разумеется, внутри нельзя использовать саму функцию filter.
def my_filter(f, ls):
if not callable(f):
return []
result = []
for x in ls:
if f(x):
result.append(x)
return result
ls = [2, 7, 9, 22, 17, 24, 8, 12, 27]
print(my_filter(lambda x: x % 2 == 0, ls))
# Задача-4:
# Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4).
# Определить, будут ли они вершинами параллелограмма.
def is_parallelogram(x1, y1, x2, y2, x3, y3, x4, y4):
def is_equal(x1, y1, x2, y2, x3, y3, x4, y4):
l1 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)
l2 = (x4 - x3) * (x4 - x3) + (y4 - y3) * (y4 - y3)
return l1 == l2
def is_collinear(x1, y1, x2, y2, x3, y3, x4, y4):
ax = x2 - x1
ay = y2 - y1
bx = x4 - x3
by = y4 - y3
return (ax * by - bx * ay) == 0
result = []
result.append(is_equal(x1, y1, x2, y2, x3, y3, x4, y4))
result.append(is_collinear(x1, y1, x2, y2, x3, y3, x4, y4))
result.append(is_equal(x2, y2, x3, y3, x4, y4, x1, y1))
result.append(is_collinear(x2, y2, x3, y3, x4, y4, x1, y1))
return all(result)
print(is_parallelogram(0, 0, 1, 1, 3, 1, 2, 0))
print(is_parallelogram(0, 0, 0, 1, 1, 1, 1, 0))
|
a0f28c9b043afa73347c84e931be1a4c792d1f3e | ZhengLiangliang1996/Leetcode_ML_Daily | /contest/weekcontest99/GroupsSpecialEquivalentString.py | 927 | 3.6875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2022 liangliang <liangliang@Liangliangs-MacBook-Air.local>
#
# Distributed under terms of the MIT license.
class Solution(object):
def numSpecialEquivGroups(self, words):
"""
:type words: List[str]
:rtype: int
"""
d = {}
for word in words:
if word not in d:
even = []
odd = []
for i in range(0,len(word)):
if i %2 == 0:
even.append(word[i])
else:
odd.append(word[i])
even.sort()
odd.sort()
d[word] = [even , odd]
res = []
for word in words:
if d[word] not in res:
res.append(d[word])
return len(res)
|
1be572d6c2eb71886d19365b5c9893bdb70b715c | JoshCWegner/Python-Programming | /all_about_me.py | 651 | 4.21875 | 4 |
my_favorite_food = input("What is your favorite food?")
what_I_like_to_watch = input("What show or shows do you like to watch?")
what_is_your_favorite_team = input("Do you have a team you like to watch?")
do_you_have_any_kids = input("Do you have any kids?")
if do_you_have_any_kids == "yes":
what_are_their_names = input("What are their names?")
print("My favorite food is " + my_favorite_food)
print(what_I_like_to_watch)
print(what_is_your_favorite_team + " is my favorite team")
if do_you_have_any_kids == "yes":
print("My kids names are " + what_are_their_names)
elif do_you_have_any_kids == "no":
print("I do not have any kids") |
e56ad4ab00d2ff186e6052d54744c54c74b7f819 | ks-99/forsk2019 | /week5/day3/breadbasket.py | 1,827 | 3.65625 | 4 | """
Code Challenge:
dataset: BreadBasket_DMS.csv
Q1. In this code challenge, you are given a dataset which has data and time wise transaction on a bakery retail store.
1. Draw the pie chart of top 15 selling items.
2. Find the associations of items where min support should be 0.0025, min_confidence=0.2, min_lift=3.
3. Out of given results sets, show only names of the associated item from given result row wise.
"""
import pandas as pd
import numpy as np
from apyori import apriori
import matplotlib.pyplot as plt
df=pd.read_csv("BreadBasket_DMS.csv")
a=df["Item"].value_counts()
a=a.head(15)
plt.pie(a.values,labels=a.index)
transactions=[]
y=[]
with open("BreadBasket_DMS.csv") as fp:
for item in fp:
x=item.split(",")
y.append(x[2])
y.append(x[3])
transactions.append(y)
y=[]
#transactions.remove(transactions[0])
list1=[]
list2=[]
count=1
for item in transactions:
if( not item):
continue
if(item[0] == str(count)):
list1.append(item[1])
else:
count=item[0]
list2.append(list1)
list1=[]
list1.append(item[1])
list2.remove(list2[0])
rules = apriori(list2, min_support = 0.0025, min_confidence = 0.2, min_lift = 3)
# Visualising the results
results = list(rules)
for item in results:
# first index of the inner list
# Contains base item and add item
pair = item[0]
items = [x for x in pair]
print("Rule: " + items[0] + " -> " + items[1])
#second index of the inner list
print("Support: " + str(item[1]))
#third index of the list located at 0th
#of the third index of the inner list
print("Confidence: " + str(item[2][0][2]))
print("Lift: " + str(item[2][0][3]))
print("=====================================")
|
99fc9aa060e3dbd515ad792def701eaee8a1fae9 | Vamsi027/RegressionModels | /polynomial_regression.py | 779 | 3.859375 | 4 | # Importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing dataset
dataset=pd.read_csv('')#Enter the csv file
X=dataset.iloc[:,1:2].values
Y=dataset.iloc[:,2].values
#Fitting polynomial regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
polynomial_regressor=PolynomialFeatures(degree=4)
X_poly=polynomial_regressor.fit_transform(X)
linear_regressor2=LinearRegression()
linear_regressor2.fit(X_poly,Y)
#Visualizing the dataset on Polynomial Regression
X_grid=np.arange(min(X),max(X),0.1)
X_grid=X_grid.reshape((len(X_grid),1))
plt.scatter(X,Y,color='')
plt.plot(X_grid,linear_regressor2.predict(polynomial_regressor.fit_transform(X_grid)),color='')
plt.title('')
plt.xlabel('')
plt.ylabel('')
plt.show()
|
127a890c1c87c1ca1d7794607f23a325643b4a85 | michaelRobinson84/Sandbox | /password_check.py | 264 | 4.3125 | 4 | MINIMUM_LENGTH = 8
password = input("Please enter a password, minimum length 8 characters: ")
while len(password) < 8:
print("Password is too short!")
password = input("Please enter a password, minimum length 8 characters: ")
print(len(password) * "*")
|
df9cabefb53ec647e6c357de731362a92280d8bc | sharedrepo2021/AWS_Python | /Diptangsu/my_dict.py | 2,367 | 4.03125 | 4 | import json
if __name__ == "__main__":
my_dict = {}
option_dict = {
1: 'display my_dict',
2: 'Exit',
3: 'Add an item to the dictionary',
4: 'Remove specific item dictionary',
5: 'Make a copy of the dictionary',
6: 'Remove all items from the dictionary',
7: 'Access a specific item from the dictionary',
8: 'Display all items as a tuple',
9: 'Display all keys',
10: 'Remove the last item of the dictionary',
11: 'Display all values',
12: 'Search for a key',
13: 'Insert a specific value for all dictionary keys',
14: 'Search for a default value'
}
print(json.dumps(option_dict, indent=5))
while True:
try:
i = int(input("Select an option of your choice: "))
if i == 1:
print(my_dict)
elif i == 2:
print('Thank you')
break
elif i == 3:
my_dict.update({input('Please enter the key to be added in the dictionary: '):(input('Please enter the value for the corresponding key: '))})
elif i == 4:
my_dict.pop(input("Enter the key you want to remove: "))
elif i == 5:
new_dict = my_dict.copy()
print(new_dict)
elif i == 6:
my_dict.clear()
elif i == 7:
print(my_dict.get(input("Enter the key to be extracted: ")))
elif i == 8:
print(my_dict.items())
elif i == 9:
print(my_dict.keys())
elif i == 10:
my_dict.popitem()
elif i == 11:
print(my_dict.values())
elif i == 12:
if input('Enter the key you want to look for: ') in my_dict:
print('It exists')
else:
print('No such Key found')
elif i == 13:
my_dict = dict.fromkeys(my_dict.keys(),input('Enter the value you want to set as default: '))
elif i == 14:
my_dict.setdefault(input('Enter te key: '),input('Enter the value: '))
else:
print('Please select an available option from the dictionary: ')
except:
print('Please enter a valid integer') |
59ef2f5ea040e653694dfece4d77a9726d4967a9 | mipopov/Y.Praktice | /Sprint4/Solutions/TaskA.py | 589 | 3.578125 | 4 | # class Node:
# def __init__(self, value, left=None, right=None):
# self.value = value
# self.right = right
# self.left = left
#
def solution(node, max_elem= float("-inf")) -> int:
if node.value > max_elem:
max_elem = node.value
if node.left:
max_elem = solution(node.left, max_elem)
if node.right:
max_elem = solution(node.right, max_elem)
return max_elem
# th_e = Node(8)
# f_e = Node(15)
# first_e = Node(9, f_e, th_e)
# second_e = Node(11)
# tree_root = Node(10, first_e, second_e)
#
# print(solution(tree_root)) |
e78df9292490d69d8b95312a8273794c2084386e | amandathedev/Python-Fundamentals | /01_python_fundamentals/01_02_seconds_years.py | 253 | 3.75 | 4 | '''
From the previous example, move your calculation of how many seconds in a year to a python executable script.
'''
year = 0
minute = 60
hour = minute * 60
day = hour * 24
year = day * 365
print("There are " + str(year) + " seconds in one year.")
|
9510db5357d6bf064518326f72191514e7636a39 | DvidGs/Python-A-Z | /7 - Estructuras de datos: Conjuntos/ejercicio 5.py | 322 | 3.796875 | 4 | # Ejercicio 5
# Dado un conjunto, crea un programa que nos devuelva el caracter con menor valor ASCII. Debes hacerlo sin
# recurrir a la función min().
valor = {1, 2, "A", "E", "@"}
min = 9999
for i in valor:
if ord(str(i)) < min:
min = ord(str(i))
print("El caracter con menor valor ASCII es: ", chr(min)) |
f0fd37e4cf9b5325a73d04edd896bd17d4b76844 | Spiridd/python | /stepic/sum_decomposition.py | 203 | 3.609375 | 4 | n = int(input())
terms = []
term = 1
while n > 0:
if n-term > term or n == term:
n -= term
terms.append(term)
term += 1
print(len(terms))
[print(term, end=' ') for term in terms]
|
77158902938c70aef7ac824a85ae744cc09cf4ca | lxngoddess5321/python-files-backup | /100例/036.py | 265 | 3.859375 | 4 | import math
def IsPrime(x):
if x == 2:
flag = 1
elif x==1:
flag = 0
else:
# y = int(math.sqrt(x))
y=x//2
for i in range(2,y+1):
if x%i == 0:
flag = 0
break
else:
flag = 1
return flag
for i in range(1,100):
if IsPrime(i):
print(i) |
19b29d3e0150e5367e8abe4bae8bbc6f8bcf2798 | qicst23/LeetCode-pythonSolu | /013 Roman to Integer.py | 830 | 3.859375 | 4 | """
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
"""
__author__ = 'Danyang'
roman2int = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
class Solution:
def romanToInt(self, s):
"""
What happens if current roman char larger than the previous roman char?
:param s: String
:return: integer
"""
result = 0
for ind, val in enumerate(s):
if ind>0 and roman2int[val]>roman2int[s[ind-1]]: # e.g. XIV
result -= roman2int[s[ind-1]] # reverse last action
result += roman2int[val]-roman2int[s[ind-1]]
else:
result += roman2int[val]
return result
|
29f51ca06d5205729fc201f43f5cdfac0011ce0a | Raid55/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 972 | 3.765625 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""
el Test class
"""
def test_standard(self):
""" norm test
"""
self.assertEqual(max_integer([1,6, 100, 4, 0, -1, 10]), 100)
def test_none(self):
""" None test
"""
self.assertEqual(max_integer([]), None)
def test_typdef(self):
""" sending in string
"""
self.assertEqual(max_integer("wasabi and chips"), 'w')
def test_typedefArr(self):
""" sending in arr with diff types
"""
with self.assertRaises(TypeError):
max_integer([1, "GILLET", 33, "THE BEST A MAN CAN GET", 7])
def test_negativeArr(self):
""" sending only negative nums
"""
self.assertEqual(max_integer([-1, -33, -7]), -1)
if __name__ == '__main__':
unittest.main()
|
58336ca676c76301a34135a686a661c0b374b50e | Anupya/leetcode | /medium/q98 validateBST.py | 896 | 4.15625 | 4 | # Given the root of a binary tree, determine if it is a valid binary search tree (BST).
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBSTModified(self, root, minNum, maxNum):
if not root: # empty tree
return True
if minNum < root.val and root.val < maxNum:
left = self.isValidBSTModified(root.left, minNum, root.val)
right = self.isValidBSTModified(root.right, root.val, maxNum)
if left and right:
return True
else:
return False
else:
return False
def isValidBST(self, root: TreeNode) -> bool:
return self.isValidBSTModified(root, float('-inf'), float('inf'))
|
39e2dda8ca36f9bc5f84c8bf440e63d4dde52c34 | Kanchi-Chitaliya/Socket-Programming | /client_udp.py | 2,963 | 3.671875 | 4 | from socket import *
import os
import sys
class Client():
def __init__(self,serverName,serverPort):
self.serverName = serverName
self.serverPort = serverPort
self.clientSocket = socket(AF_INET, SOCK_DGRAM)
self.clientSocket.bind(('',15098))
def create_socket(self):
x= input("Please enter the command. The options presented to the users are:\n 1. put <file name>\n 2. list \n 3. get <file name>\n 4. rename <old_name> <new_name>\n 5. exit \n")
self.clientSocket.sendto(x.encode(),(self.serverName,self.serverPort))
x=x.split(" ")
if x[0]=="put":
self.put(x)
elif x[0]=="list":
self.create_list()
elif x[0]=="get":
self.get(x)
elif x[0]=="Exit":
self.exit()
def put(self,x):
if os.path.isfile(x[1]):
k=os.path.getsize(x[1])
y=str(k)
self.clientSocket.sendto(y.encode(),(self.serverName,self.serverPort))
i=0
file1=open(x[1],"rb")
while i<=k:
msg=file1.read(buffer)
self.clientSocket.sendto(msg,(self.serverName,self.serverPort))
j,serverAddress=self.clientSocket.recvfrom(buffer)
j=j.decode()
while j=="NACK":
self.clientSocket.sendto(msg,(self.serverName,self.serverPort))
j,serverAddress=self.clientSocket.recvfrom(buffer)
j=j.decode()
i=i+len(msg)
file1.close()
else:
print("the file does not exist in the directory")
def create_list(self):
lt,serverAddress=self.clientSocket.recvfrom(buffer)
lt=lt.decode()
a=lt.split(" ")
for items in a:
print(items)
def get(self,x):
size,serverAddress=self.clientSocket.recvfrom(buffer)
i=0
data=open("Received_"+x[1],"wb")
while i<=int(size):
message,serverAddress= self.clientSocket.recvfrom(buffer)
if len(message)>0:
self.clientSocket.sendto("ACK".encode(),(self.serverName,self.serverPort))
data.write(message)
i=i+len(message)
else:
self.clientSocket.sendto("NACK".encode(),(self.serverName,self.serverPort))
data.close()
def change_name(self):
message,serverAddress= self.clientSocket.recvfrom(buffer)
message=message.decode()
print(message)
def exit(self):
quit()
if __name__=='__main__':
while(1):
g=sys.argv[1]
h=int(sys.argv[2])
if h<5000:
print("Invalid port Number")
buffer=1024
client=Client(g,h)
client.create_socket()
|
040c6f857aefd17cde3fef8e8e224bb07a966253 | Aitd1/learnPython | /函数/逆向参数传入.py | 370 | 3.65625 | 4 | #列表,元组
def test(name,age,sex):
print('我的名字叫:'+name+',我的年龄有:'+age+',我的性别是:'+sex)
list=('谢君','27','男')
test(*list)
#字典
def test1(name,age,sex):
print('我的名字叫:' + name + ',我的年龄有:' + age + ',我的性别是:' + sex)
dictinfo={'name':'谢君','age':'27','sex':'男'}
test1(**dictinfo) |
2c3083e216cb5a7add519fe420ffd44f54a441b2 | greatislee/python_demo | /inherit.py | 711 | 3.71875 | 4 | #!/usr/bin/env python
# coding=utf-8
class Hero:
'''
英雄类
'''
def __init__(self,name):
print "Hero.__init__"
self.name = name
def show(self):
print "Hero.showMe"
print self.name
class agility(Hero):
'''
敏捷类
'''
def __init__(self,name,speed):
#调用子类构造 会默认调用父类构造
#python 需要显示的调用父类的构造
Hero.__init__(self,name)
self.speed= speed
def show(self):
print "agility show()"
print self.name
print self.speed
if __name__ == "__main__":
h = Hero ("Icefrog")
h.show()
print "*"*20
a = agility("Mor",522)
a.show()
|
8202281123db123b0f303bd69ec8a166d58f5597 | rafaelgoncalvesmatos/estudandopython | /Curiosidade/curiosidade06.py | 219 | 3.8125 | 4 | #!/usr/bin/python
# Fucando em condicoes dentro de variaveis
x = range(1,11)
x1 = 1
for x in x :
print "Valor de x agora e ",x
print "Valor de x1 e ",x1
x1 = x1 + 1
for x1 in x1 :
print x1,' * ', " = ",x1 * x
|
d3bf66423fc5868fbce776c7866032d8eb289951 | cuihee/LearnPython | /Day01/c0111.py | 559 | 4 | 4 |
"""
列表的嵌套是什么
操作列表的方式
"""
# str
print('\x0a')
print("我叫 %s 今年 %d 岁!" % ('小明', 10))
# list
l1 = ['Google', 'Runoob', 1997, 2000]
print("原始列表 : ", l1)
del l1[2]
print("删除第三个元素 : ", l1)
# 嵌套
l2 = [1, l1]
print(l2[1][0])
# 元组
t1 = (10,) # 不加逗号视括号为运算符,所以没有逗号的t1是int
t2 = 'a',
print(type(t1), type(t2))
# 访问和列表一样 用切片
# 删除只能删除整个元组不能删除其中的一个元素
# 元组的内置函数 len() min() max()
|
a590dd527ab8577d5a44e78a0702ab1b4d9ad51b | Courage-GL/FileCode | /Python/month02/day04/file.py | 382 | 3.609375 | 4 | """
os模块 文件处理小函数
"""
import os
# 获取文件大小 bytes
# print(os.path.getsize("./笔记.txt"))
# 获取目录下的内容
print(os.listdir("/home/tarena"))
# 判断文件是否存在 True False
print(os.path.exists("./04.txt"))
# 判断一个文件是否为普通文件 True False
print(os.path.isfile("./4.txt"))
# 删除文件
# os.remove("笔记.txt")
|
282b9d1c205857616919d8cf4db387f4fb07e206 | r7asmu7s/art_of_doing_python | /02_basic_data_types/04_more_strings.py | 433 | 3.75 | 4 | full_name = '\tJohnny\nsmith'
print(full_name)
first_name = 'mike'
last_name = 'eramo'
full_name = first_name + ' ' + last_name
print(full_name.title())
print(first_name.upper() + ' ' + last_name.upper())
print(4 + 2)
print('4' + '2')
message = 'Hello, how are you doing today? What is going on at home?'
message = message.lower()
print(message)
h_count = message.count('h')
print('Our message has ' + str(h_count) + "h's in it.") |
4d67a0c7c448b79fa22c89c6a5a5f68251c12109 | Eduardo271087/python-udemy-activities | /section-5/while.py | 593 | 4.125 | 4 | # El else se usa cuando termina el ciclo, excepto cuando se hac break
iteracion = 1
while iteracion <= 0:
iteracion += 1
print('Estoy iterando, van = ', iteracion)
else:
print('Imprimo esto porque se terminó y es el else')
iteracion = 1
while iteracion <= 3:
iteracion += 1
print('Estoy iterando, van = ', iteracion)
break
else:
print('Imprimo esto porque se terminó y es el else')
iteracion = 0
while iteracion <= 10:
iteracion += 1
if iteracion == 4:
print('Estoy iterando, van = ', iteracion)
break
else:
print('Imprimo esto porque se terminó y es el else') |
3b4b369b7f8429ee6c3c1f767a395ddf7e0b5dbd | shyamww/Implementation-of-Physical-and-Datalink-layers-in-TCP-IP-Protocol | /physical.py | 573 | 3.890625 | 4 | def encode(data):
enc_data = ""
#blank string
for bit in data:
#change 0 to 1 and -1
if bit == "0":
enc_data += "1-1"
#change 1 to -1 and 1
else:
enc_data += "-11"
return enc_data
def decode(data):
bit_data = ""
#blank string
for i in range(0, len(data), 3):
j = i + 3
bit = data[i:j]
#change 1 and -1 to 0
if bit == "1-1":
bit_data += "0"
#change -1 and 1 to 1
elif bit == "-11":
bit_data += "1"
return bit_data |
0dbb2484cedf4f9ca38b38517d84f23b11c27b10 | skskdmsdl/python-study | /02. Operator/3.1 function.py | 1,587 | 4.03125 | 4 | # 랜덤 함수
from random import *
print(random()) # 0.0 ~ 1.0 미만의 임의의 값 생성
print(random() * 10) # 0.0 ~ 10.0 미만의 임의의 값 생성
print(int(random() * 10)) # 0 ~ 10 미만의 임의의 값 생성
print(int(random() * 10)) # 0 ~ 10 미만의 임의의 값 생성
print(int(random() * 10) + 1) # 1 ~ 10 미만의 임의의 값 생성
print(int(random() * 10) + 1) # 1 ~ 10 미만의 임의의 값 생성
# 로또 랜덤 번호 생성
print(int(random() * 45) + 1) # 1~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1) # 1~ 45 이하의 임의의 값 생성
print(int(random() * 45) + 1)
print(randrange(1, 46)) # 1~ 46 미만의 임의의 값 생성
print(randrange(1, 46)) # 1~ 46 미만의 임의의 값 생성
print(randrange(1, 46)) # 1~ 46 미만의 임의의 값 생성
print(randrange(1, 46)) # 1~ 46 미만의 임의의 값 생성
print(randrange(1, 46)) # 1~ 46 미만의 임의의 값 생성
print(randrange(1, 46)) # 1~ 46 미만의 임의의 값 생성
print(randint(1, 45)) # 1~ 45 이하의 임의의 값 생성
print(randint(1, 45)) # 1~ 45 이하의 임의의 값 생성
print(randint(1, 45)) # 1~ 45 이하의 임의의 값 생성
print(randint(1, 45)) # 1~ 45 이하의 임의의 값 생성
print(randint(1, 45)) # 1~ 45 이하의 임의의 값 생성
print(randint(1, 45)) # 1~ 45 이하의 임의의 값 생성 |
6d3c71e00d760076c9a381746b8d90c9e360abc8 | Aasthaengg/IBMdataset | /Python_codes/p03109/s974406861.py | 220 | 3.515625 | 4 | s = list(input().split('/'))
s = [int(ss) for ss in s]
if s[0] < 2019:
print("Heisei")
elif s[0] == 2019:
if s[1] < 4 or (s[1] == 4 and s[2] <= 30):
print("Heisei")
else:
print("TBD")
else:
print("TBD")
|
e45cfc2c6c63948f5bcd4f9138b8e57b0ddf4846 | ignaziocapuano/workbook_ex | /cap5/ex_111.py | 281 | 4.1875 | 4 | #reverse sorted order
list=[]
num=int(input("Inserisci primo elemento della List: "))
while num!=0:
list.append(num)
num = int(input("Inserisci numero da aggiungere alla List(0 per interrompere): "))
list.sort(reverse=True)
for i in range(len(list)):
print(list[i]) |
ad66410871a614f869dd462d4abfd3961ed3414c | G-J-Morais-DEV/tarm | /folgatarm/app/funcionario/folga.py | 2,476 | 4.03125 | 4 | # -*- coding: utf-8 -*-
from datetime import date,datetime,timedelta
from datetime import *
week = ['Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado', 'Domingo']
time = ["Tarde", "Noite", "Madrugada", "Manhã"]
days_of_Month = [31,28,31,30,31,30,31,31,30,31,30,31]
folga = {}
hj = date.today().toordinal() # data de hoje transformada para fazer soma de dias
days = int(date.today().strftime("%d")) # variável para iniciar dias (no futuro vai receber o date.today())
dayFirst = 0
month = int(date.today().strftime("%m"))
monthrange = days_of_Month[month-1]
folga
dia_da_semana = date.weekday(date.today())
day_off = 0
while dayFirst < monthrange:
dayFirst +=1
day_off +=1
#folga simulada da madrugada
if day_off == 6:
if dayFirst < 10:
folga = date.today().strftime("0"+str(dayFirst)+"/%m/%Y")
print("Madrugada : {}".format(folga))
#print(week[dayFirst])
else:
folga = date.today().strftime(str(dayFirst)+"/%m/%Y")
print("Madrugada : {}".format(folga))
#print(week[dayFirst])# IndexError: list index out of range
#folga simulada da manhã
if day_off == 7:
if dayFirst < 10:
folga = date.today().strftime("0"+str(dayFirst)+"/%m/%Y")
print("Manhã : {}".format(folga))
#print(week[dayFirst])
else:
folga = date.today().strftime(str(dayFirst)+"/%m/%Y")
print("Manhã : {}".format(folga))
#print(week[dayFirst])# IndexError: list index out of range
#folga simulada da tarde
if day_off == 8:
if dayFirst < 10:
folga = date.today().strftime("0"+str(dayFirst)+"/%m/%Y")
print("Tarde : {}".format(folga))
#print(week[dayFirst])
else:
folga = date.today().strftime(str(dayFirst)+"/%m/%Y")
print("Tarde : {}".format(folga))
#print(week[dayFirst])# IndexError: list index out of range
#folga simulada da Noite
if day_off == 9:
if dayFirst < 10:
folga = date.today().strftime("0"+str(dayFirst)+"/%m/%Y")
print("Noite : {}".format(folga))
#print(week[dayFirst])
else:
folga = date.today().strftime(str(dayFirst)+"/%m/%Y")
print("Noite : {}".format(folga))
#print(week[dayFirst])# IndexError: list index out of range
day_off = 3
|
e65f31d0528c252ed18c49635bbf706dbe3d1a0d | falecomlara/CursoEmVideo | /ex049 - tabuada com for.py | 243 | 3.84375 | 4 | #tabuada usando o laco (feito no exercicio 9)
titulo = 'GERADOR DE TABUADAS'
x=len(titulo)
print('='*x)
print(titulo)
print('='*x)
num = int(input('Digite um número: '))
for c in range(1,11):
print('{} x {} = {}'.format(num,c,(num*c)))
|
22d831ac21d59292e7f02ebb0787354173a51e5b | LanderU/PruebasPython | /Entregas/Ejercicio1.py | 345 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*
# Abrimos el fichero
archivo = open("ficheronumero","r")
# Leemos la primera linea
numero = archivo.readline()
# Cerramos el archivo
archivo.close()
# Casteamos el numero para mostrarlo como un String
str(numero)
# Mostramos el valor por pantalla
print ("El contenido del archivo es: %s" %(numero)) |
d0076f805a61189b5315ee5e0ec2086ec4d93312 | victorvg17/HackerRank | /python/set-union-intersection.py | 339 | 3.78125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == "__main__":
n = int(input())
n_st = set(input().split(" "))
b = int(input())
b_st = set(input().split(" "))
all_st = n_st.union(b_st)
both_st = n_st.intersection(b_st)
our_st = all_st.difference(both_st)
print(len(our_st)) |
3761b612fb3c78573c416827c70a43623a530809 | pankaj890/Python | /1. Python - Basics/OOPS/inheritance_constructor.py | 784 | 3.84375 | 4 | class A:
# Super constructor
def __init__(self):
print('In A init')
def feature1(self):
print('feature 1 running')
def feature2(self):
print('feature 2 running')
class B(A):
# Child constructor
def __init__(self):
super().__init__()
print('In B init')
def feature3(self):
print('feature 3 running')
def feature4(self):
print('feature 4 running')
class C:
# Child constructor
def __init__(self):
print('In C init')
# Constructor in Multiple Inheritance where we have multiple super constructors
# Method Resolution Order
class D(A, C):
def __init__(self):
super().__init__()
print('In D init')
a1 = D()
|
be8e7e8e69118eae97342f0a66e7a069bf49480f | kshirsagarsiddharth/Algorithms_and_Data_Structures | /Graphs/TopologicalSort.py | 2,410 | 3.875 | 4 | from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list)
self.vertices = vertices
self.visited_list = defaultdict()
self.output_stack = []
def add_edge(self,From,To):
self.graph[From].append(To)
self.visited_list[From] = False
self.visited_list[To] = False
def topological_sort_util(self,vertex):
if not self.visited_list[vertex]:
self.visited_list[vertex] = True
for neighbour in self.graph[vertex]:
self.topological_sort_util(neighbour)
self.output_stack.insert(0,vertex)
def topology_sort(self):
for vertex in self.visited_list:
self.topological_sort_util(vertex)
"""
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
self.visited_list = defaultdict()
self.output_stack = []
def add_edge(self,From,To):
self.graph[From].append(To)
self.visited_list[From] = False
self.visited_list[To] = False
def topological_sort_util(self,vertex):
if not self.visited_list[vertex]:
self.visited_list[vertex] = True
for neighbors in self.graph[vertex]:
self.topological_sort_util(self,neighbors)
return self.output_stack.insert(0,vertex)
def topological_sort(self):
for vertex in self.visited_list:
self.topological_sort_util(vertex)
"""
class Graph_two:
def __init__(self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
def topological_sort_util(self,v,visited,stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.topological_sort_util(i,visited,stack)
stack.insert(0,v)
def toploogical_sort(self):
visited = [False] * self.vertices
stack = []
for i in range(self.vertices):
if visited[i] == False:
self.topological_sort_util(i,visited,stack)
return stack
|
c4495da1458cfafc8fe4ed1234e282ac7fc7f30d | fefefefe/skat | /skat.py | 3,305 | 4 | 4 | # card game Skat
"""
features so far:
hands out the cards
calculates the Jacks' factor
suit code is:
0 == diamonds
1 == hearts
2 == spades
3 == clubs
rank code is:
0 == 7
1 == 8
2 == 9
3 == 10
4 == Jack
5 == Queen
6 == King
7 == Ace
"""
import random
# variable declarations
hand0 = [] # the players hand
hand1 = [] # cpu1's hand
hand2 = [] # cpu2's hand
skat = [] # the 2 table cards
# build the deck of 32 cards and shuffle it
def makeDeck():
deck = []
for suit in range(0, 4):
for rank in range(0, 8):
deck.append([rank, suit])
random.shuffle(deck)
return deck
# give out the cards to each player
def giveCards(deck):
global hand0
global hand1
global hand2
global skat
hand0 = deck[:3]
hand1 = deck[3:6]
hand2 = deck[6:9]
skat = deck[9:11]
hand0 += deck[11:15]
hand1 += deck[15:19]
hand2 += deck[19:23]
hand0 += deck[23:26]
hand1 += deck[26:29]
hand2 += deck[29:]
# readable hand
def translateHand(hand):
for e in hand:
if e[0] == 0:
e[0] = "7"
elif e[0] == 1:
e[0] = "8"
elif e[0] == 2:
e[0] = "9"
elif e[0] == 3:
e[0] = "10"
elif e[0] == 4:
e[0] = "Jack"
elif e[0] == 5:
e[0] = "Queen"
elif e[0] == 6:
e[0] = "King"
elif e[0] == 7:
e[0] = "Ace"
if e[1] == 0:
e[1] = "Diamonds"
elif e[1] == 1:
e[1] = "Hearts"
elif e[1] == 2:
e[1] = "Spades"
elif e[1] == 3:
e[1] = "Clubs"
print hand
def calcFactor(hand):
jacks = []
for e in hand:
if e[0] == "Jack":
jacks += [e[1]]
withOrWithout = ""
factor = 0
if "Clubs" in jacks:
withOrWithout = "with"
factor += 1
if "Spades" in jacks:
factor += 1
if "Hearts" in jacks:
factor += 1
if "Diamonds" in jacks:
factor += 1
else:
withOrWithout = "without"
factor += 1
if "Spades" not in jacks:
factor += 1
if "Hearts" not in jacks:
factor += 1
if "Diamonds" not in jacks:
factor += 1
print jacks
print "The factor is:", withOrWithout, factor, "plays", factor + 1
return factor
# set up one round
deck = makeDeck()
giveCards(deck)
# to do: sortHand(hand0)
# test: decode hands
print
print "--------------------------------------------"
print " Show all hands "
print "--------------------------------------------"
print
translateHand(hand0)
print
translateHand(hand1)
print
translateHand(hand2)
print
translateHand(skat)
print
# test: calculate Jacks' factor
print
print "--------------------------------------------"
print " Calculate the Jacks' factors "
print "--------------------------------------------"
print
print "Player has the following Jacks:"
calcFactor(hand0)
print
print "CPU1 has the following Jacks:"
calcFactor(hand1)
print
print "CPU2 has the following Jacks:"
calcFactor(hand2)
|
a7e8671661c0465e8870a97f3304004288678caf | lmgty/leetcode | /21.py | 539 | 3.796875 | 4 | # -*- coding: UTF-8 -*-
class Solution:
def generateParenthesis(self, n):
res = []
s = ''
self.recursion(s, res, n, n)
return res
def recursion(self, s, res, left, right):
if left == right == 0:
res.append(s)
if left > 0:
self.recursion(s + '(', res, left - 1, right)
if right > left:
self.recursion(s + ')', res, left, right - 1)
if __name__ == '__main__':
n = 3
checker = Solution()
print(checker.generateParenthesis(n))
|
432e8934862db7c1b13179582e64077b940e0eba | shane-jeon/shane_practice_classes | /prac_classes.py | 4,768 | 4.21875 | 4 | """
Build a base class called AbstractPokemon that contains the following methods:
- __init__(self, name, lv=5)
- eat
- drink
- sleep
Build a Charmander class that inherits from the AbstractPokemon class that allows you to do the following:
- give it a nickname
- level up
- attack
- omnivore
Build a Charizard class that inherits from the Charmander class that allows you to:
- fly
- eats meat --> carnivore
Build a Squirtle class that inherits from the AbstractPokemon class that has the following methods:
- attack using water gun
- swim
- wears sunglasses
- herbivore
"""
# Build a base class called AbstractPokemon that contains the following methods:
# - __init__(self, name, lv=5)
# - eat
# - drink
# - sleep
class AbstractPokemon:
def __init__(self, name, lv=5):
# self.name = name
self.n = name # instance attribute "n" is bound to the value associated with the variable "name"
self.level = lv
def play(self):
print("Yay! I'm playing!")
def eat(self, dietary_status=""):
"""Give the Pokemon something to eat. Then it eats."""
if dietary_status == "carnivore":
print("Yum, I like eating meat. Thanks!")
elif dietary_status == "herbivore":
print("Yum, I like eating veggies. Thanks!")
else:
print("Yum, I like eating food. Thanks!")
self.eat = eat
self.drink = drink
self.sleep = sleep
# Build a Charmander class that inherits from the AbstractPokemon class that allows you to do the following:
# - give it a nickname
# - level up
# - attack
# - omnivore
class Charmander(AbstractPokemon):
dietary_status = "omnivore"
def eat(self):
super().eat(self.dietary_status)
# class Animal:
# # (...snippet)
# def __init__(self, name, species):
# self.name = name
# self.species = species
# # (...snippet)
# class Cat(Animal):
# # (...snippet)
# def __init__(self, name):
# super().__init__(name, 'cat')
# # (...snippet)
# kitty = Cat("kitty")
# print(kitty.species)
# class Pokemon:
# class Animal:
# print("Hello!")
# info = "I am an animal"
# def __init__(self, species):
# self.species = "dog"
# self.sound = 'bark'
# self.is_cute = True
# def speak(self, greet = "Hey there!"):
# print(f"{greet} {self.info}. A {self.type} to be exact. My name is {self.name}.")
# class Cat(Animal):
# def __init__(self,species):
# # self.species = 'cat'
# super().__init__(species, 'cat')
# kitty = Cat()
# print(kitty.species)
# jimmy = Animal("spotted")
# class Animal:
# print('Hello!')
# info ='I am an animal'
# # def __init__(self, color):
# # self.color = color
# # self.is_cute = True
# def speak(self):
# print(f"{self.info}. A {self.type} to be exact. My name is {self.name}.")
# def graduate(self):
# self.speak() #accessing method from above (calling)
# print(f'When I get my PhD, I will be Dr.{self.name}')
# jimmy = Animal()
# jimmy.speak()
# jimmy = Animal("spotted")
# print(jimmy)
# porter = Animal("dirty") #don't have to include is_cute in parameter because it is not called in instance parameter
# porter.type = "dog"
# porter.name = "Porter"
# porter.color = "white" #reassign
# porter.speak()
# porter.graduate()
# print(f"I am always {porter.color}")
# print(Animal.info)
##Other Example##
# class Animal:
# species = "dog"
# class Dog:
# has_fur = True
# def __init__(self, name, color):
# self.name = name
# self.color = color
# dog = Dog("Sparky", "brown")
# new_dog = Dog("Bob", "white")
# print(dog.name, dog.color)
# print(dog.has_fur)
# print(dog.color)
# print(new_dog.color)
# dog.has_fur = False
# print(dog.has_fur, new_dog.has_fur)
##super classes##
# class Animal:
# print('Hello!')
# info ='I am an animal'
# class Dog(Animal):
# info = "I am a dog" #overwrites parent class attribute
# def sound(self):
# print("Woof!")
# def __init__(self):
# self.fur_type = "I have fur."
# self.ears = "I have ears."
# self.tail = "I have a tail."
# def __init__(self, color):
# self.color = color
# self.is_cute = True
# def speak(self):
# print(f"{self.info}. A {self.type} to be exact. My name is {self.name}.")
# def graduate(self):
# self.speak() #accessing method from above (calling)
# print(f'When I get my PhD, I will be Dr.{self.name}')
# rogue = Dog
# print(rogue) |
f78816f51b411871f479260af4fcbe480a950e79 | chickey96/python_practice | /basic_algorithms.py | 488 | 3.859375 | 4 | def sum_list(list):
sum = 0
for num in list:
sum += num
print(sum)
return sum
# number_list = [1, 2, 3]
# sum_list(number_list)
# number_list.append(-4)
# sum_list(number_list)
# does not handle punctuation or capitalization at the moment
def reverse_words(sentence):
words = sentence.split(" ")
answer = []
for word in words:
answer.append(word[::-1])
answer = " ".join(answer)
print(answer)
return answer
reverse_words("Here are some words to reverse") |
9e8cb08932a1b801d2b0bf44ddfa9f5f6aa93cbc | bricewge/adventofcode | /01-1.py | 216 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
puzzle = sys.argv[1]
prev = None
total = 0
for i in puzzle:
if prev == i:
total += int(i)
prev = i
if puzzle[-1] == puzzle[0]:
total += int(i)
print(total)
|
6e4eb5723d4940133221c230f128a6c6066cc60d | balamosh/yandex_contests | /algorithm_training/1.0/04_lection/A/solution.py | 189 | 3.59375 | 4 | size = int(input())
synonyms = {}
for _ in range(size):
first, second = input().split()
synonyms[first] = second
synonyms[second] = first
word = input()
print(synonyms[word])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.