blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
070efabec818ae56bac9f687e686fca8662e66ee | Wanpeng66/Python_learning | /访问数据库/sqlite.py | 619 | 4.03125 | 4 | # python内置了sqlite数据库
import sqlite3
def CreatAndInsert(conn):
cursor = conn.cursor()
cursor.execute("create table user (id varchar(20) primary key, name varchar(20))")
cursor.execute("insert into user (id, name) values ('1', 'Michael')")
print(cursor.rowcount)
cursor.close()
conn.commit()
def search(conn):
cursor = conn.cursor()
cursor.execute("select * from user where id=?", (1,))
all = cursor.fetchall()
print(all)
cursor.close()
if __name__ == "__main__":
conn = sqlite3.connect("C:/Users/14793/Pictures/test.db")
search(conn)
conn.close() |
eddfcb0de86966d42016eabd41433540b0049ffb | m-01101101/udacity-datastructures-algorithms | /3. data_structures/array/duplicate_number.py | 2,925 | 4.25 | 4 | """
You have been given an array of `length = n`.
The array contains integers from `0` to `n - 2`.
Each number in the array is present exactly once
except for one number which is present twice.
Find and return this duplicate number present in the array
**Example:**~
* `arr = [0, 2, 3, 1, 4, 5, 3]`
* `output = 3` (because `3` is present twice)
The expected time complexity for this problem is `O(n)`
The expected space-complexity is `O(1)`
"""
from typing import List
def duplicate_number(arr: List[int]) -> int:
"""
:param - array containing numbers in the range [0, len(arr) - 2]
return - the number that is duplicate in the arr
"""
return [i for i in arr if arr.count(i) > 1][0]
# clever
# expected_sum = sum(list(range(len(arr)-1)))
# current_sum = sum(arr)
# return current_sum - expected_sum
def udacity_duplicate_number(arr):
"""
Notice carefully that
1. All the elements of the array are always non-negative
2. If array length = n, then elements would start from 0 to (n-2),
i.e. Natural numbers 0,1,2,3,4,5...(n-2)
3. There is only SINGLE element which is present twice.
Therefore let's find the sum of all elements (current_sum) of the original array,
and find the sum of first (n-2) Natural numbers (expected_sum).
Trick:
The second occurrence of a particular number (say `x`)
is actually occupying the space that would have been utilized
by the number (n-1).
This leads to:
current_sum = 0 + 1 + 2 + 3 + .... + (n-2) + x
expected_sum = 0 + 1 + 2 + 3 + .... + (n-2)
current_sum - expected_sum = x
"""
current_sum = 0
expected_sum = 0
# Traverse the original array in the forward direction
for num in arr:
current_sum += num
# Traverse from 0 to (length of array-1) to get the expected_sum
# Alternatively, you can use the formula for sum of an Arithmetic Progression to get the expected_sum
# It means that if the array length = n, loop will run form 0 to (n-2)
for i in range(len(arr) - 1):
expected_sum += i
# The difference between the
return current_sum - expected_sum
def multi_duplicates(arr: List[int]) -> List[int]:
"""
another approach
https://www.youtube.com/watch?v=aMsSF1Il3IY
each element in the array is a valid index
(i-1, if the list was 1 to n not 0 to n)
we loop through the list
and make each value at the corresponding index 0
so in the example;
array1 = [4, 2, 3, 1, 4, 0]
we would turn array1[4] to a negative
then we know we've seen the value before
works for finding mulitiple duplicates
"""
dups = []
for i in arr:
i = abs(i)
if arr[i] < 0:
dups.append(i)
else:
arr[i] *= -1
return dups
array1 = [1, 2, 3, 4, 3, 4, 5, 6, 2, 0]
assert multi_duplicates(array1) == [3, 4, 2]
|
ab6a519ff67fba192d60c3fc45b4833034676a9a | malmhaug/Py_AbsBegin | /Ch3E4_GuessMyNumber_V1.02/main.py | 2,503 | 4.21875 | 4 | # Project Name: Ch3E4_GuessMyNumber_V1.02
# Name: Jim-Kristian Malmhaug
# Date: 25 Oct 2015
# Description: This program is a modified version of the
# Guess My Number program from the book, with computer versus player
# Guess My Number - Computer guesser
#
# The user picks a random number between 1 and 100
# The computer tries to guess it.
# Tries = 10
# ---------------------------------------------------------------------------------
# PSEUDO CODE
# ---------------------------------------------------------------------------------
# 1. Welcome user and tell him/her what to do
# 2. Store user input in the_number
# 3. Set guess to 0
# 4. Set tries to 1
# 5. set low_guess to 1
# 6. Set high_guess to 100
# 7. Import random library
# 8. While the computer has not guessed the number and tries are below 10
# 8.1 Computer guess a number between low_guess value and high_guess value
# 8.2 Print the guess
# 8.3 If the guess is higher than the the_number
# 8.3.1 Print lower text and inform of tries left
# 8.3.2 Set high_guess to last guessed number minus one
# 8.4 Else
# 8.4.1 Print higher text and inform of tries left
# 8.4.2 Set low_guess to las guessed number plus one
# 8.5 Increment tries
# 9. If tries is above or equal to 10
# 9.1 Print failure text
# 10. If tries is below 10
# 10.1 Print winner text and winner number
# 10.2 Print tries
# 11. Print exit text, and ask for user enter input
# ---------------------------------------------------------------------------------
print("\tWelcome to 'Guess My Number'!")
print("\nThinking of a number between 1 and 100.")
print("The computer will try to guess your number in 10 tries.")
# set the initial values
the_number = int(input("Enter the number here: "))
guess = 0
tries = 1
low_guess = 1
high_guess = 100
import random
# guessing loop
while (guess != the_number) and (tries < 10):
guess = random.randint(low_guess, high_guess)
print(guess)
if guess > the_number:
print("Lower... Computer has " + str(10 - tries) + " left!")
high_guess = guess - 1
else:
print("Higher... Computer has " + str(10 - tries) + " left!")
low_guess = guess + 1
tries += 1
if tries >= 10:
print("\nThe computer failed insanely!")
else:
print("\nThe computer guessed it! The number was", the_number)
print("And it only took", tries, "tries!\n")
input("\n\nPress the enter key to exit.") |
5e6c34354af40d3914055ed23170baaae3b97b98 | olacodes/algorithm | /codility/odd_occurency_in_array.py | 250 | 3.765625 | 4 |
# The function should return the value of the unpaired element
def solution(A):
# write your code in Python 3.6
for item in A:
count = A.count(item)
if count % 2 != 0:
return item
print(solution([9,9,3,3,2,7,7])) |
e9d0b5fef619cc9b2647d795b7b8684229d20f51 | bkdbansal/CS_basics | /leetcode_python/Tree/merge-two-binary-trees.py | 1,505 | 3.984375 | 4 | # V0
# V1
# https://www.polarxiong.com/archives/LeetCode-617-merge-two-binary-trees.html
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 is not None and t2 is not None:
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
t1.val += t2.val
return t1
return t1 if t2 is None else t2
# V1'
# https://www.jiuzhang.com/solution/merge-two-binary-trees/#tag-highlight-lang-python
class Solution:
"""
@param t1: the root of the first tree
@param t2: the root of the second tree
@return: the new binary tree after merge
"""
def mergeTrees(self, t1, t2):
# Write your code here
if t1 is None:
return t2
if t2 is None:
return t1
t3 = TreeNode(t1.val + t2.val)
t3.left = self.mergeTrees(t1.left, t2.left)
t3.right = self.mergeTrees(t1.right, t2.right)
return t3
# V2
# Time: O(n)
# Space: O(h)
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 is None:
return t2
if t2 is None:
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1 |
ba55f70ff4b11e1b80af467d6359be8ce6e94e68 | shebilantony/NETAHJI | /large.py | 260 | 4.1875 | 4 | num01 = 10
num02 = 14
num03 = 12
if (num01 >= num02) and (num01 >= num03):
largest = num01
elif (num02 >= num01) and (num02 >= num03):
largest = num02
else:
largest = num03
print("The largest number between",num01,",",num02,"and",num03,"is",largest)
|
22136776aeb1746d7c893dfef5b634fbb984cc0d | ssteffens/myWork | /week03/normalise.py | 532 | 4.3125 | 4 | # This program reads in a string, strips any leading or trailing spaces and converts to lower case
# THe program also outputs the length of the original and the normalised string.
# Author: Stefanie Steffens
string = str(input('Please enter a string:'))
normalisedString = string.strip().lower()
lenghtString = len(string)
lengthNormalisedString = len(normalisedString)
print('That string normalised is:{}'.format(normalisedString))
print('We reduced the input string from {} to {} characters.'.format(lenghtString, lengthNormalisedString)) |
ed99b85ba7c093b0d6f60c9f07b3f920a01dad31 | fizzywonda/CodingInterview | /arrays and strings/Reverse Vowels.py | 618 | 3.90625 | 4 | """
reverse only the vowels in a string
"""
def reverseVowels(s: str) -> str:
vset = set(["a", "e", "i", "o", "u"])
n = len(s)
right = n - 1
left = 0
s = list(s)
print(s)
while left < right:
if s[left] in vset and s[right] in vset:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
elif s[left] in vset:
right -= 1
elif s[right] in vset:
left += 1
else:
left += 1
right -= 1
return "".join(s)
if __name__ == '__main__':
print(reverseVowels("hello")) |
d7ebec498da0331cdf727695c026dd43a4885d6b | Blossomyyh/leetcode | /FindFirstandLastPositionElement.py | 2,123 | 4.03125 | 4 | from typing import List
class Solution:
"""iteration"""
# twice binary search
# write binary search with a little twist!!
def binarySearch(self, nums: List[int], target, low, high, findFirst):
while low <= high:
mid = low + (high-low)//2
if findFirst:
if (mid == 0 or target > nums[mid-1]) and target == nums[mid]:
return mid
elif target > nums[mid] :
low = mid +1
else:
# 2 condition: 1. target <mid 2. == but not the leftmost
high = mid - 1
else:
if (mid == len(nums)-1 or nums[mid+1]> target) and nums[mid] == target:
return mid
elif target < nums[mid]:
high = mid -1
else:
low = mid + 1
return -1
"""recursive"""
def binarySearchRe(self, nums: List[int], target, low, high, findFirst):
# cannot find any
if high < low:
return -1
mid = low + (high - low) // 2
if findFirst:
if (mid == 0 or target > nums[mid - 1]) and target == nums[mid]:
return mid
elif target > nums[mid]:
return self.binarySearchRe(nums, target, mid + 1, high, findFirst)
else:
# 2 condition: 1. target <mid 2. == but not the leftmost
return self.binarySearchRe(nums, target, low, mid -1, findFirst)
else:
if (mid == len(nums) - 1 or nums[mid + 1] > target) and nums[mid] == target:
return mid
elif target < nums[mid]:
return self.binarySearchRe(nums, target, low, mid -1, findFirst)
else:
return self.binarySearchRe(nums, target, mid + 1, high, findFirst)
def searchRange(self, nums: List[int], target: int) -> List[int]:
first = self.binarySearch(nums, target, 0, len(nums)-1, True)
last = self.binarySearch(nums, target, 0, len(nums)-1, False)
return [first, last]
|
f789d50e7bd57d5c201da6e677b0afa79556378f | Lunabot87/Python_project | /5_class/5_class_inheritance_ex_5_6_4.py | 1,241 | 3.75 | 4 | class Person:
" 부모클래스 "
def __init__ (self, name, phoneNumber): #메서드 생산자 생성
self.Name = name
self.PhoneNumber = phoneNumber
def PrintInfo(self):
print("Info(Name : {0}, Phone : {1})".format(self.Name, self.PhoneNumber))
def PrintPersonData(self):
print("Person(Name : {0}, Phone : {1})".format(self.Name, self.PhoneNumber))
class Student(Person):
" 자식클래스 "
def __init__(self, name, phoneNumber, subject, studentID):
Person.__init__(self, name, phoneNumber)
self.Subject = subject
self.StudentID = studentID
def PrintStudentData(self):
print("Student(Subject : {0}, StudentID : {1})".format(self.Subject, self.StudentID))
def PrintInfo(self): #Person의 PrintInfo() 재정의 (Method Overriding)
#print("Info(Name : {0}, Phone : {1})".format(self.Name, self.PhoneNumber)) #위의 정의되어진 것을 다시 재정의 한것과 같으므로 명시적 정의를 하는 방법으로 최소한이 작업으로 할 수 있다.
Person.PrintInfo(self)
print("Info(Subject : {0}, StudentID : {1})".format(self.Subject, self.StudentID))
p = Person("Derick", "010-8244-1341")
s = Student("Marry", "010-123-4567", "Computer Science", "990999")
p.PrintInfo()
s.PrintInfo() |
081c470fdf62eae4d49d955f2d718c353a8ee157 | odedahay/compareroute-coi-v1 | /handlers/validation_checker.py | 14,595 | 4.03125 | 4 | import itertools
import operator
# Variable for validation:
error_Num_of_truck = "Add more Truck! <br />The minimum balance number of delivery truck "
response = {}
def cargo_unit_checker_for_comp(num_comp_val, postal_sequence_company, **truck_capacity_dict):
errors = []
error_cargo_unit_companies_priority = " has been exceeding to maximum Truck Capacity <br />"
# count the company entered:
# if two companies
if int(num_comp_val) == 2:
truck_capacity_c1 = truck_capacity_dict['truck_capacity_c1']
truck_capacity_c2 = truck_capacity_dict['truck_capacity_c2']
# separate each company
company1 = postal_sequence_company[0]
company2 = postal_sequence_company[1]
# Iterate each cargo unit
# check if there is more than minimum value of cargo unit
for company_grp_1, company_grp_2 in itertools.izip(company1, company2):
# iterate for company 1
postal_code1 = company_grp_1[0]
cargo_unit1 = int(company_grp_1[2])
company_id1 = company_grp_1[3]
# iterate for company 2
postal_code2 = company_grp_2[0]
cargo_unit2 = int(company_grp_2[2])
company_id2 = company_grp_2[3]
# if there is more the minimum value throw an error:
# print "error_cargo1", cargo_unit1 > int(truck_capacity_c1)
if cargo_unit1 > int(truck_capacity_c1):
errors.extend([company_id1, ", ", postal_code1, error_cargo_unit_companies_priority])
if cargo_unit2 > int(truck_capacity_c2):
errors.extend([company_id2, ", ", postal_code2, error_cargo_unit_companies_priority])
return errors
# if three companies
elif int(num_comp_val) == 3:
truck_capacity_c1 = truck_capacity_dict['truck_capacity_c1']
truck_capacity_c2 = truck_capacity_dict['truck_capacity_c2']
truck_capacity_c3 = truck_capacity_dict['truck_capacity_c3']
# separate each company
company1 = postal_sequence_company[0]
company2 = postal_sequence_company[1]
company3 = postal_sequence_company[2]
# Iterate each cargo unit
# check if there is more than minimum value of cargo unit
for company_grp_1, company_grp_2, company_grp_3 in itertools.izip(company1, company2, company3):
# iterate for company 1
postal_code1 = company_grp_1[0]
cargo_unit1 = int(company_grp_1[2])
company_id1 = company_grp_1[3]
# iterate for company 2
postal_code2 = company_grp_2[0]
cargo_unit2 = int(company_grp_2[2])
company_id2 = company_grp_2[3]
# iterate for company 3
postal_code3 = company_grp_2[0]
cargo_unit3 = int(company_grp_2[2])
company_id3 = company_grp_2[3]
# if there is more the minimum value throw an error:
if cargo_unit1 > int(truck_capacity_c1):
errors.extend([company_id1, " ", postal_code1, error_cargo_unit_companies_priority])
if cargo_unit2 > int(truck_capacity_c2):
errors.extend([company_id2, " ", postal_code2, error_cargo_unit_companies_priority])
if cargo_unit3 > int(truck_capacity_c3):
errors.extend([company_id3, " ", postal_code3, error_cargo_unit_companies_priority])
return errors
# if three companies
elif int(num_comp_val) == 4:
truck_capacity_c1 = truck_capacity_dict['truck_capacity_c1']
truck_capacity_c2 = truck_capacity_dict['truck_capacity_c2']
truck_capacity_c3 = truck_capacity_dict['truck_capacity_c3']
truck_capacity_c4 = truck_capacity_dict['truck_capacity_c4']
# separate each company
company1 = postal_sequence_company[0]
company2 = postal_sequence_company[1]
company3 = postal_sequence_company[2]
company4 = postal_sequence_company[3]
# Iterate each cargo unit
# check if there is more than minimum value of cargo unit
for company_grp_1, company_grp_2, company_grp_3, company_grp_4 in itertools.izip(company1, company2, company3, company4):
# iterate for company 1
postal_code1 = company_grp_1[0]
cargo_unit1 = int(company_grp_1[2])
company_id1 = company_grp_1[3]
# iterate for company 2
postal_code2 = company_grp_2[0]
cargo_unit2 = int(company_grp_2[2])
company_id2 = company_grp_2[3]
# iterate for company 3
postal_code3 = company_grp_2[0]
cargo_unit3 = int(company_grp_2[2])
company_id3 = company_grp_2[3]
# iterate for company 4
postal_code4 = company_grp_2[0]
cargo_unit4 = int(company_grp_2[2])
company_id4 = company_grp_2[3]
# if there is more the minimum value throw an error:
if cargo_unit1 > int(truck_capacity_c1):
errors.extend([company_id1, " ", postal_code1, error_cargo_unit_companies_priority])
if cargo_unit2 > int(truck_capacity_c2):
errors.extend([company_id2, " ", postal_code2, error_cargo_unit_companies_priority])
if cargo_unit3 > int(truck_capacity_c3):
errors.extend([company_id3, " ", postal_code3, error_cargo_unit_companies_priority])
if cargo_unit4 > int(truck_capacity_c4):
errors.extend([company_id4, " ", postal_code4, error_cargo_unit_companies_priority])
return errors
# if three companies
elif int(num_comp_val) == 5:
truck_capacity_c1 = truck_capacity_dict['truck_capacity_c1']
truck_capacity_c2 = truck_capacity_dict['truck_capacity_c2']
truck_capacity_c3 = truck_capacity_dict['truck_capacity_c3']
truck_capacity_c4 = truck_capacity_dict['truck_capacity_c4']
truck_capacity_c5 = truck_capacity_dict['truck_capacity_c5']
# separate each company
company1 = postal_sequence_company[0]
company2 = postal_sequence_company[1]
company3 = postal_sequence_company[2]
company4 = postal_sequence_company[3]
company5 = postal_sequence_company[4]
# Iterate each cargo unit
# check if there is more than minimum value of cargo unit
for company_grp_1, company_grp_2, company_grp_3, company_grp_4, company_grp_5 in itertools.izip(company1, company2, company3, company4, company5):
# iterate for company 1
postal_code1 = company_grp_1[0]
cargo_unit1 = int(company_grp_1[2])
company_id1 = company_grp_1[3]
# iterate for company 2
postal_code2 = company_grp_2[0]
cargo_unit2 = int(company_grp_2[2])
company_id2 = company_grp_2[3]
# iterate for company 3
postal_code3 = company_grp_2[0]
cargo_unit3 = int(company_grp_2[2])
company_id3 = company_grp_2[3]
# iterate for company 4
postal_code4 = company_grp_2[0]
cargo_unit4 = int(company_grp_2[2])
company_id4 = company_grp_2[3]
# iterate for company 5
postal_code5 = company_grp_2[0]
cargo_unit5 = int(company_grp_2[2])
company_id5 = company_grp_2[3]
# if there is more the minimum value throw an error:
if cargo_unit1 > int(truck_capacity_c1):
errors.extend([company_id1, " ", postal_code1, error_cargo_unit_companies_priority])
if cargo_unit2 > int(truck_capacity_c2):
errors.extend([company_id2, " ", postal_code2, error_cargo_unit_companies_priority])
if cargo_unit3 > int(truck_capacity_c3):
errors.extend([company_id3, " ", postal_code3, error_cargo_unit_companies_priority])
if cargo_unit4 > int(truck_capacity_c4):
errors.extend([company_id4, " ", postal_code4, error_cargo_unit_companies_priority])
if cargo_unit5 > int(truck_capacity_c5):
errors.extend([company_id5, " ", postal_code5, error_cargo_unit_companies_priority])
return errors
# else:
#
#
# return True
# def minimum_truck_checker_comp(num_comp_val, propose_result_company, starting_postal_list,
# num_of_truck_c1, num_of_truck_cc1,
# num_of_truck_c2, num_of_truck_cc21,
# num_of_truck_c3, num_of_truck_cc31,
# type_of_truck_c2,type_of_truck_cc1,type_of_truck_cc21,
# type_of_truck_c1,
# type_of_truck_c3,
# add_truck_cc1, add_truck_cc2,add_truck_cc3):
#
# # add_truck_dict = {
# # "add_truck_cc1": add_truck_cc1,
# # "add_truck_cc2": add_truck_cc2,
# # "add_truck_cc3": add_truck_cc3,
# # }
# #
# # num_of_truck_dict = {
# #
# # "num_of_truck_c1": num_of_truck_c1,
# # "num_of_truck_cc1": num_of_truck_cc1,
# # "num_of_truck_cc2": num_of_truck_cc2,
# # "num_of_truck_cc3": num_of_truck_cc3,
# #
# # "num_of_truck_c2": num_of_truck_c2,
# # "num_of_truck_cc21": num_of_truck_cc21,
# # "num_of_truck_cc22": num_of_truck_cc22,
# # "num_of_truck_cc23": num_of_truck_cc23,
# #
# # "num_of_truck_c3": num_of_truck_c3,
# # "num_of_truck_cc31": num_of_truck_cc31,
# # "num_of_truck_cc32": num_of_truck_cc32,
# # "num_of_truck_cc33": num_of_truck_cc33,
# #
# # }
#
# # type_of_truck_dict = {
# # "type_of_truck_cc1": type_of_truck_cc1,
# # "type_of_truck_cc2": type_of_truck_cc2,
# # "type_of_truck_cc3": type_of_truck_cc3,
# # }
#
# if int(num_comp_val) == 2:
#
# # type_of_truck_cc1 = type_of_truck_dict['type_of_truck_cc1']
# #
# # num_of_truck_c1 = num_of_truck_dict['num_of_truck_c1']
# # num_of_truck_cc1 = num_of_truck_dict['num_of_truck_cc1']
# # num_of_truck_c2 = num_of_truck_dict['num_of_truck_c2']
#
# company_1 = int(len(propose_result_company[0]))
# company_2 = int(len(propose_result_company[1]))
#
# # HQ
# hq_comp_1 = starting_postal_list[0]
# hq_comp_2 = starting_postal_list[1]
#
# if add_truck_cc1 == "true" and not add_truck_cc2 == "true":
#
# if company_1 > int(num_of_truck_cc1) + int(num_of_truck_c1):
# errors.extend([error_Num_of_truck, type_of_truck_cc1, " : ", company_1, "<br />"])
#
# if add_truck_cc1 == "true" and add_truck_cc2 == "true":
#
# if company_1 > int(num_of_truck_cc1) + int(num_of_truck_c1):
# errors.extend([error_Num_of_truck, " for ", hq_comp_1, ", Type Truck: ", type_of_truck_cc1, " is ", company_1, "<br />"])
#
# if company_2 > int(num_of_truck_cc21) + int(num_of_truck_c2):
# errors.extend([error_Num_of_truck, " for ", hq_comp_2, ", Type Truck: ", type_of_truck_cc21, " is ", company_2, "<br />"])
#
# if not add_truck_cc1 == "true" and not add_truck_cc2 == "true":
#
# if company_1 > int(num_of_truck_c1):
# errors.extend([error_Num_of_truck, " for ", hq_comp_1, ", Type Truck: ", type_of_truck_c1, " is ", company_1, "<br />"])
#
# if company_2 > int(num_of_truck_c2):
# errors.extend([error_Num_of_truck, " for ", hq_comp_2, ", Type Truck: ", type_of_truck_c2, " is ", company_2, "<br />"])
#
# return errors
#
# if int(num_comp_val) == 3:
#
# company_1 = int(len(propose_result_company[0]))
# company_2 = int(len(propose_result_company[1]))
# company_3 = int(len(propose_result_company[2]))
#
# # HQ
# hq_comp_1 = starting_postal_list[0]
# hq_comp_2 = starting_postal_list[1]
# hq_comp_3 = starting_postal_list[2]
#
# if add_truck_cc1 == "true" and not add_truck_cc2 == "true":
#
# if company_1 > int(num_of_truck_cc1) + int(num_of_truck_c1):
# errors.extend([error_Num_of_truck,
# type_of_truck_cc1, " : ", company_1, "<br />"])
#
# if add_truck_cc1 == "true" and add_truck_cc2 == "true" and not add_truck_cc3 == "true":
#
# if company_1 > int(num_of_truck_cc1) + int(num_of_truck_c1):
# errors.extend([error_Num_of_truck, " for ", hq_comp_1, ", Type Truck: ", type_of_truck_cc1, " is ", company_1, "<br />"])
#
# if company_2 > int(num_of_truck_cc21) + int(num_of_truck_c2):
# errors.extend([error_Num_of_truck, " for ", hq_comp_2, ", Type Truck: ", type_of_truck_cc21, " is ", company_2, "<br />"])
#
# if company_3 > int(num_of_truck_cc31) + int(num_of_truck_c2):
# errors.extend([error_Num_of_truck, " for ", hq_comp_3, ", Type Truck: ", num_of_truck_cc31, " is ", company_3, "<br />"])
#
# if not add_truck_cc1 == "true" and not add_truck_cc2 == "true" and not add_truck_cc3 == "true":
#
# if company_1 > int(num_of_truck_c1):
# errors.extend([error_Num_of_truck, " for ", hq_comp_1, ", Type Truck: ", type_of_truck_c1, " is ", company_1, "<br />"])
#
# if company_2 > int(num_of_truck_c2):
# errors.extend([error_Num_of_truck, " for ", hq_comp_2, ", Type Truck: ", type_of_truck_c2, " is ", company_2, "<br />"])
#
# if company_3 > int(num_of_truck_c3):
# errors.extend([error_Num_of_truck, " for ", hq_comp_3, ", Type Truck: ", type_of_truck_c3, " is ", company_3, "<br />"])
#
# return errors |
5fbc83bd9bc94c787a22559186d359defbc86220 | nanyangcheng/chengpeng.github.io | /python_learning/py3-2.py | 282 | 3.78125 | 4 | mdd=['chengdu','xian','hangzhou','shanghai']
print(mdd)
print(sorted(mdd))
print(mdd)
print(sorted(mdd,reverse=True))
print(mdd)
mdd.reverse()
print(mdd)
mdd.reverse()
print(mdd)
mdd.sort()
print(mdd)
mdd.sort()
print(mdd)
print(len(mdd))
for value in range(1,6):
print=(value)
|
dcc278e963685c65614f6489cfdfcd782e059390 | mochita314/algorithm | /spiral/alds1_4_b.py | 434 | 3.5 | 4 | n = int(input())
S = list(map(int,input().split()))
q = int(input())
T = list(map(int,input().split()))
def binary_search(lst,key):
left = 0
right = len(lst)
while left<right:
mid = (left+right)//2
if lst[mid]==key:
return 1
elif key < lst[mid]:
right = mid
else:
left = mid+1
return 0
ans = 0
for key in T:
ans+=binary_search(S,key)
print(ans) |
e9429473ab3f93559d05a3ce942d2c6f802c4e1e | qor4/Analysis-of-hitting-shots-for-amateurs | /퀴즈/9주차 퀴즈.py | 2,377 | 3.8125 | 4 | import turtle
import random
import sqlite3
def SaveLine(): ##데이터베이스에 데이터 저장
con, cur = None, None
sql = " "
con = sqlite3.connect("Turtle") # DB가 저장된 폴더까지 지정
cur = con.cursor()
sql = "INSERT INTO Turtle VALUES(" + str(ID) + "," + str(r) + "," + str(g) + "," + str(b) + "," + str(
Turn) + "," + str(curX) + "," + str(curY) + ")"
cur.execute(sql)
con.commit()
con.close()
def ReversePaint(): ##순서 거꾸로 그리기
sql = ""
con = sqlite3.connect("Turtle") # DB가 저장된 폴더까지 지정
cur = con.cursor()
sql = "SELECT R, G, B, X, Y FROM Turtle WHERE lineID=" + str(ID) + " AND Turn=" + str(j)
cur.execute(sql)
row = cur.fetchone()
r = row[0]
g = row[1]
b = row[2]
curx = row[3]
cury = row[4]
if (j == turn[ID]):
turtle.penup()
turtle.goto(curx, cury)
turtle.pendown()
turtle.pencolor((r, g, b))
elif (j == 2):
turtle.goto(curx, cury)
turtle.pencolor((r, g, b))
turtle.goto(0, 0)
else:
turtle.goto(curx, cury)
turtle.pencolor((r, g, b))
con.close()
## 전역 변수 선언 부분 ##
swidth, sheight, pSize, exitCount, ID, Turn = 300, 300, 3, 0, 1, 2
r, g, b, angle, dist, curX, curY = [0] * 7
turn = [0, 0, 0, 0, 0, 0]
## 메인 코드 부분 ##
turtle.title('거북이가 맘대로 다니기')
turtle.shape('turtle')
turtle.pensize(pSize)
turtle.setup(width=swidth + 30, height=sheight + 30)
turtle.screensize(swidth, sheight)
while True:
r = random.random()
g = random.random()
b = random.random()
turtle.pencolor((r, g, b))
angle = random.randrange(0, 360)
dist = random.randrange(1, 100)
turtle.left(angle)
turtle.forward(dist)
curX = turtle.xcor()
curY = turtle.ycor()
SaveLine()
Turn += 1
if (-swidth / 2 <= curX and curX <= swidth / 2) and (-sheight / 2 <= curY and curY <= sheight / 2):
pass
else:
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turn[ID] = Turn - 1
ID += 1
Turn = 2
exitCount += 1
if exitCount >= 5:
ID -= 1
break
turtle.clear()
for i in range(ID, 0, -1):
for j in range(turn[ID], 1, -1):
ReversePaint()
ID -= 1
turtle.done()
|
3125af0c1212adfc38d3abb64b7927e0f5f02e3a | KC-Simmons/Self-Work | /NNFunc.py | 4,168 | 3.53125 | 4 | import numpy as np
#Activation Function (0,1)
sigmoid = lambda i: (1/(1+np.exp(-i)))
vectorized_sigmoid = np.vectorize(sigmoid)
#Set-up Learning Rate
LR = 0.9
class NN(object):
def __init__(self, NumIL, NumHL, NumOL):
self.NumIL = NumIL
self.NumHL = NumHL
self.NumOL = NumOL
#Creates the Weights Matrices
self.weightsHL = (np.random.rand(NumHL,NumIL)*2)-1
self.weightsOL = (np.random.rand(NumOL,NumHL)*2)-1
#Create Bias Matrices
self.biasHL =((np.random.rand(NumHL,1))*2)-1
self.biasOL =((np.random.rand(NumOL,1))*2)-1
def feedforward(self,ffinput):
hiddenlayer = (self.weightsHL.dot(ffinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
return outputlayer
def train(self,trinput,answers):
#Rerun FF code in the train
hiddenlayer = (self.weightsHL.dot(trinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
outputs = outputlayer
#Find the Errors
outputserrors = answers - outputs
weightsOL_t = np.transpose(self.weightsOL)
hiddenerrors = weightsOL_t.dot(outputserrors)
hidden_T = np.transpose(hiddenlayer)
gradients = (LR * outputserrors * outputs * (1 - outputs))
weight_ho_deltas = gradients.dot(hidden_T)
self.weightsOL = self.weightsOL + weight_ho_deltas
self.biasOL = self.biasOL + np.sum(gradients)
input_T = np.transpose(trinput)
hidden_gradients = (LR * hiddenerrors * hiddenlayer * (1 - hiddenlayer))
weight_ih_deltas = hidden_gradients.dot(input_T)
self.weightsHL = self.weightsHL + weight_ih_deltas
self.biasHL = self.biasHL + np.sum(hidden_gradients)
class CopyNN(object):
def __init__(self, NumIL, NumHL, NumOL, weightsHL, weightsOL, biasHL, biasOL):
self.NumIL = NumIL
self.NumHL = NumHL
self.NumOL = NumOL
self.weightsHL = weightsHL
self.weightsOL = weightsOL
self.biasHL = biasHL
self.biasOL = biasOL
def feedforward(self,ffinput):
hiddenlayer = (self.weightsHL.dot(ffinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
return outputlayer
def train(self,trinput,answers):
#Rerun FF code in the train
hiddenlayer = (self.weightsHL.dot(trinput)) + self.biasHL
hiddenlayer = vectorized_sigmoid(hiddenlayer)
outputlayer = (self.weightsOL.dot(hiddenlayer)) + self.biasOL
outputlayer = vectorized_sigmoid(outputlayer)
outputs = outputlayer
#Find the Errors
outputserrors = answers - outputs
weightsOL_t = np.transpose(self.weightsOL)
hiddenerrors = weightsOL_t.dot(outputserrors)
hidden_T = np.transpose(hiddenlayer)
gradients = (LR * outputserrors * outputs * (1 - outputs))
weight_ho_deltas = gradients.dot(hidden_T)
self.weightsOL = self.weightsOL + weight_ho_deltas
self.biasOL = self.biasOL + np.sum(gradients)
input_T = np.transpose(trinput)
hidden_gradients = (LR * hiddenerrors * hiddenlayer * (1 - hiddenlayer))
weight_ih_deltas = hidden_gradients.dot(input_T)
self.weightsHL = self.weightsHL + weight_ih_deltas
self.biasHL = self.biasHL + np.sum(hidden_gradients
NeuralNetwork = NN(2,5,1)
ffinputtest = np.array([[1,0,1,0],[0,1,1,0]])
targets = np.array([1,1,0,0])
print(NeuralNetwork.feedforward(ffinputtest))
for i in range(10000):
NeuralNetwork.train(ffinputtest, targets)
print(NeuralNetwork.feedforward(ffinputtest))
ffinputreal = np.array([[1],[1]])
print(NeuralNetwork.feedforward(ffinputreal))
##ffinput for feedforward alg are read by array
|
3719ad6825098818256152db8c4f2a810b4e36f2 | KrIstIaN430/PROGRAM | /PYTHON/CowsAndBulls.py | 1,255 | 3.65625 | 4 | import random
#Guess the 4 digits in their right place
# cows = right number, right place
# bulls = right number, wrong place
number_to_guess = [int(x) for x in str(random.randint(1000, 9999))] #Generate the number to guess
ctr = 1
def check_size(number_to_check):
temp_list = [int(x) for x in number_to_check]
global ctr
if len(temp_list) != 4:
print("Number must be 4 digits.. Try again.")
temp_list = check_size(input("Enter a 4 digit number: "))
ctr += 1
return temp_list
def check_cows_bulls(number_to_check):
temp_list = check_size(number_to_check)
temp_list2 = number_to_guess.copy()
cows = 0
bulls = 0
for num in range(4):
if temp_list[num] == number_to_guess[num]:
cows += 1
temp_list2[num] = None
elif temp_list[num] in temp_list2:
bulls += 1
print(str(cows) + " cows, " + str(bulls) + " bulls")
if cows == 4:
print("Guesses: " + str(ctr))
return cows
print("Welcome to the Cows and Bulls Game!")
#print("Number to guess: " + str(number_to_guess)) #Print the generated number to guess
while check_cows_bulls(input("Enter a 4 digit number: ")) != 4:
ctr += 1
|
af1a18415e72570a5317d96e3ea5f84ee2291038 | zzz136454872/leetcode | /Twitter.py | 1,908 | 3.90625 | 4 |
from typing import *
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.log=[]
self.f={}
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
self.log.append((userId,tweetId))
def getNewsFeed(self, userId: int) -> List[int]:
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
"""
if userId in self.f.keys():
ids=self.f[userId]
else:
ids=[]
ids.append(userId)
count=0
out=[]
for news in self.log[::-1]:
if news[0] in ids:
count+=1
out.append(news[1])
if count>=10:
break
return out
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId in self.f.keys():
if f not in self.f[followerId]:
self.f[followerId].append(followeeId)
else:
self.f[followerId]=[followeeId]
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if followerId in self.f.keys() and followeeId in self.f[followerId]:
self.f[followerId].remove(followeeId)
twitter = Twitter();
twitter.postTweet(1, 5)
print(twitter.getNewsFeed(1))
print(type(twitter))
twitter.follow(1, 2)
twitter.postTweet(2, 6)
print(twitter.getNewsFeed(1))
twitter.unfollow(1, 2)
twitter.getNewsFeed(1)
|
55f0192987863f56f3f386c4cc170301f12cd5b0 | chenshanghao/Interview_preparation | /Leetcode_250/Problem_101/learning_iterative.py | 1,374 | 4.15625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
"""
:type root: TreeNode
:rtype: bool
"""
# stack used to hold the matching pairs
stack = []
# if root=None, or if root has no children, root is symmetric
if not root or (not root.left and not root.right):
return True
stack.append((root.left, root.right))
while len(stack):
# the order of node retrieval matters little here, because we only care about
# pair content and not the relative order of different pairs; queue is quicker
# at finding shallow discrepancy, where stack is quicker at finding deeper
# discrepancy
left, right = stack.pop()
# if left and right are not symmetric, return false
if not left or not right or (left.val != right.val):
return False
# only append if the corresponding pairs exist
if left.left or right.right:
stack.append((left.left, right.right))
if left.right or right.left:
stack.append((left.right, right.left))
return True
|
1cf2d5296a91d979c047d6bb39b2167e70283d41 | FireFlyRealWorldProject/analytics-server | /src/check.py | 2,653 | 3.625 | 4 | """ Checks symptoms of a patient to see if they have anthrax or not """
import json as JSON
import symptom as symptomLoader
import patient as PatientMod
def check(patient):
"""Takes a patient object and checks it for symptoms"""
symptoms = patient.patientData['Symptoms'] #Get the symptoms
patientChanceRank = 0 #The current total ranking points the patient has
for patientSymptoms in symptoms: #For every symptom the patient has
print(patientSymptoms)
try:
savedSymptoms = symptomLoader.loadSymptoms()
for types in savedSymptoms.items(): #For every type of symptoms we've loaded
for givenSymptoms in types[1]: #For every symptom in that type
json = dict()
json = JSON.loads(givenSymptoms) #load it
if "total" in json: #If this is the total symptoms number, then store it!
totalSymptoms = int(json['total'])
continue #There wont be any more info in this record
try:
name = json['name'] #TODO catch key error #Get the fields
rank = json['rank']
if name.lower() == patientSymptoms['name'].lower(): #If they're equal
print("match")
patientChanceRank += rank #Add the ranking points from that symptom
except KeyError:
print("Couldent get keys")
except TypeError: #Catch if loadSymptoms() returns None
return 0
return patientChanceRank / totalSymptoms * 100
def checkID(db,patientID):
""" Checks if the patient has anthrax, sets that status in the DB, and returns true or false """
p = PatientMod.patient(db.getPatientDetails(patientid=patientID))
print(type(p.patientData))
percentageChance = check(p)
# p.patientData['percentage_chance'] = percentageChance #Add the new data to the patient record
# db.write(p) #Write the new record!
#TODO We should probably write back to the DB here the chance that they got
return percentageChance #get the id and check it.
def checkName(db, name):
p = PatientMod.patient(db.getPatientDetails(patientsurname=name))
percentageChance = check(p)
p.patientData['percentage_chance'] = percentageChance #Add the new data to the patient record
db.write(p) #Write the new record!
#TODO We should probably write back to the DB here the chance that they got
return percentageChance #get the id and check it.
|
e0946d0d01ce38c9ca7181f3cf4b15e88b58209c | paulopimenta6/ph_codes | /python/arq_1.py | 321 | 4 | 4 | nome = raw_input("Digite seu nome: ") #raw_iput recebe string
idade = int(input("Digite sua idade: "))
saldo = float(input("Digite o saldo da sua conta bancaria: "))
print("O nome do correntista e: %s " % nome)
print("A idade e: %d " % idade)
print("O saldo e: %d " % saldo)
print("###################################") |
c458e8e62e5b3130022be3f6cee80d8dab9be5b4 | rkp872/Python | /6)Functions/PassingListToFunction.py | 494 | 4.125 | 4 | myList=[]
n=int(input("Enter number of elements in the list: "))
for i in range(n):
tem=int(input("Enter a value: "))
myList.append(tem)
def evenOdd(list):
even=0
odd=0
for i in list:
if(i%2==0):
even=even+1
else:
odd=odd+1
return even,odd
even,odd=evenOdd(myList)
# print("Number of even: ",even)
# print("Print Number of odd: ",odd)
print("Even : {} and Odd : {}".format(even,odd)) #format() replaces the {} |
23cf56614688f1aa80ec4782f55d15a474cbeceb | umeshsaug/pythonTry | /src/collection/sets.py | 231 | 3.6875 | 4 | my_set = {1,2,5,7,5,10,8,2,1}
my_set_1 = {2,5,9,11,15,20}
print(my_set)
print(my_set_1)
print("Union = ", my_set|my_set_1)
print("Intrsectino = ", my_set & my_set_1)
print("Difference = ", my_set - my_set_1)
# Set methods
|
aa466c3998f44ab3e44a35acbbc054bb85a43615 | hahahayden/CPE101 | /Project6/crimetime.py | 10,382 | 3.75 | 4 | # Project6-Function/Main file
#
# Name: Hayden Tam
# Instructor: S. Einakian
# Section: 05
# Take in the inputs and split into lines
class Crime:
def __init__(self, iD, category):
self.iD = iD
self.category = category
self.day_of_week = None
self.month = None
self.hour = None
def __eq__(self, other):
# and self.day_of_week == other.category and self.month == other.month and self.hour == other.hour)
return type(self) == type(other) and \
self.iD == other.iD and self.category == other.category and self.day_of_week == other.day_of_week and \
self.month == other.month and self.hour == other.hour
def __repr__(self):
return(("{},{}".format(
self.iD, self.category))) # self.day_of_week, self.month, self.hour)))
def set_time(self, month, hour):
numString = ""
if (int(hour) > 12):
numString = str(int(hour)-12)+"PM"
elif(0 < int(hour) < 12):
numString = str((int(hour)))+"AM"
elif(int(hour) == 0):
numString = str(12)+"AM"
elif(int(hour) == 12):
numString = str(12)+"PM"
self.hour = numString
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
stringRep = months[int(month)-1]
self.month = stringRep
# Purpose: creates crime obj
# Signature: list->list
def create_crimes(crimeList):
#test = open("Test.txt", "w")
robberyListID = []
robberyObjectList = []
for count in range(0, len(crimeList), 1):
iD = crimeList[count][0]
iD.strip()
category = crimeList[count][1]
# 150025138
category = category.split()
if(category[0] == "ROBBERY" and iD not in robberyListID):
robberyListID.append(iD)
robberyObject = Crime(iD, "ROBBERY")
robberyObjectList.append(robberyObject)
return robberyObjectList
# Purpose: takes in the list of objects and sorts them
# Signature: list (Crime obj)->list(Crime obj)
def sort_crimes(crimes):
for i in range(len(crimes)):
minIndex = i
for k in range(i + 1, len(crimes)):
if (int(crimes[k].iD)) < int((crimes[minIndex].iD)):
minIndex = k
swap(crimes, minIndex, i)
return crimes
# Purpose: swaps the variables around in the list accordingly
# Signature: list, int,int->None
def swap(A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
# crimes is the sorted robbery list list of objects
# Purpose: takes in the sorted crime list and the lines from times.tsv and updates each object accordingly
# Signature: list,list-> list
def update_crimes(crimes, lines):
# print(crimes)
updatedCrimes = []
for line in lines:
sections = line.split("\t")
# print(sections)
fc = find_crime(crimes, sections[0])
month = str(sections[2])
mnth = month.split("/")
mnth = mnth[0]
hr = sections[3]
hr = hr.split(":")
hr = hr[0]
hr = hr.split(":")
hr = hr[0]
hr = hr.strip()
#hr = changeTime((hr))
if fc[0] == True: # found ID is from the times file; list of all the ones that are robberies
# fc.day_of_week = str(sections[1])
crimes[fc[1]].day_of_week = str(sections[1])
crimes[fc[1]].set_time(mnth, hr)
for crime in crimes:
updatedCrimes.append(crime)
return updatedCrimes
# Purpose: finds the crime within the times. tsv file through binary research and returns the index if found to update the necessary object
# Signatuer: list(Obj list),int->tuple(bool,int)
def find_crime(robberList, crime_id):
first = 0 # binary search
last = len(robberList)-1
found = False
while first <= last and not found:
midpoint = (first + last)//2
if int(robberList[midpoint].iD) == int(crime_id):
found = True
mid = midpoint
else:
if int(crime_id) < int(robberList[midpoint].iD):
last = midpoint-1
else:
first = midpoint+1
return found, midpoint
# Purpose: gets the mode for most crimes happening within a day, hour, and month
# Signature: list(Crime list)->tuple(string,string,string)
def stats(updatedCrimes):
binofdays = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
numberofRobberies = len(updatedCrimes)
countDays = [0, 0, 0, 0, 0, 0, 0]
for count in updatedCrimes:
if(count.day_of_week == "Monday"):
countDays[0] += 1
elif(count.day_of_week == "Tuesday"):
countDays[1] += 1
elif(count.day_of_week == "Wednesday"):
countDays[2] += 1
elif(count.day_of_week == "Thursday"):
countDays[3] += 1
elif(count.day_of_week == "Friday"):
countDays[4] += 1
elif(count.day_of_week == "Saturday"):
countDays[5] += 1
elif(count.day_of_week == "Sunday"):
countDays[6] += 1
maxofDays = max(countDays)
idxmaxDay = countDays.index(maxofDays)
dayMax = binofdays[idxmaxDay]
binofmonths = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
countmonthList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for countmonths in updatedCrimes:
if(countmonths.month == "January"):
countmonthList[0] += 1
elif(countmonths.month == "February"):
countmonthList[1] += 1
elif(countmonths.month == "March"):
countmonthList[2] += 1
elif(countmonths.month == "April"):
countmonthList[3] += 1
elif(countmonths.month == "May"):
countmonthList[4] += 1
elif(countmonths.month == "June"):
countmonthList[5] += 1
elif(countmonths.month == "July"):
countmonthList[6] += 1
elif(countmonths.month == "August"):
countmonthList[7] += 1
elif(countmonths.month == "September"):
countmonthList[8] += 1
elif(countmonths.month == "October"):
countmonthList[9] += 1
elif(countmonths.month == "November"):
countmonthList[10] += 1
elif(countmonths.month == "December"):
countmonthList[12] += 1
maxMonthNum = max(countmonthList)
idxmaxMonth = countmonthList.index(maxMonthNum)
maxMonth = binofmonths[idxmaxMonth]
binofTimes = ["12AM", "1AM", "2AM", "3AM", "4AM", "5AM", "6AM", "7AM", "8AM", "9AM", "10AM",
"11AM", "12PM", "1PM", "2PM", "3PM", "4PM", "5PM", "6PM", "7PM", "8PM", "9PM", "10PM", "11PM"]
countTime = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for countingTime in updatedCrimes:
if countingTime.hour == "12AM":
countTime[0] += 1
elif countingTime.hour == "1AM":
countTime[1] += 1
elif countingTime.hour == "2AM":
countTime[2] += 1
elif countingTime.hour == "3AM":
countTime[3] += 1
elif countingTime.hour == "4AM":
countTime[4] += 1
elif countingTime.hour == "5AM":
countTime[5] += 1
elif countingTime.hour == "6AM":
countTime[6] += 1
elif countingTime.hour == "7AM":
countTime[7] += 1
elif countingTime.hour == "8AM":
countTime[8] += 1
elif countingTime.hour == "9AM":
countTime[9] += 1
elif countingTime.hour == "10AM":
countTime[10] += 1
elif countingTime.hour == "11AM":
countTime[11] += 1
elif countingTime.hour == "12PM":
countTime[12] += 1
elif countingTime.hour == "1PM":
countTime[13] += 1
elif countingTime.hour == "2PM":
countTime[14] += 1
elif countingTime.hour == "3PM":
countTime[15] += 1
elif countingTime.hour == "4PM":
countTime[16] += 1
elif countingTime.hour == "5PM":
countTime[17] += 1
elif countingTime.hour == "6PM":
countTime[18] += 1
elif countingTime.hour == "7PM":
countTime[19] += 1
elif countingTime.hour == "8PM":
countTime[20] += 1
elif countingTime.hour == "9PM":
countTime[21] += 1
elif countingTime.hour == "10PM":
countTime[22] += 1
elif countingTime.hour == "11PM":
countTime[23] += 1
maxCountTime = max(countTime)
idxmaxTime = countTime.index(maxCountTime)
maxHour = binofTimes[idxmaxTime]
return dayMax, maxMonth, maxHour
#testFile = open("Testing.txt", "w")
#Purpose: main
# Signature: none->none
def main():
writeFile = open("robberies.tsv", "w")
writeFile.write("ID"+"\t"+"Category"+"\t" +
"DayOfWeek"+"\t"+"Month"+"\t"+"Hour")
writeFile.write("\n")
listofCrimes = open("crimes.tsv", "r")
actualListofCrimes = []
for count in listofCrimes:
count = count.strip().split("\t")
actualListofCrimes.append(count)
listofCrimes.close()
# .split if index 1==robbery and index 0 not in list and then append it
robberyObj = create_crimes(actualListofCrimes)
sortedRobberyListID = sort_crimes(robberyObj) # list of obj sorted
# 3638, should be 3636 because of #150028825 #150025138
fin = open("times.tsv")
lines = fin.readlines()[1:]
updatedCrimes = update_crimes(sortedRobberyListID, lines)
stat = stats(updatedCrimes)
for count3 in updatedCrimes:
writeFile.write(str(count3.iD)+"\t"+str(count3.category)+"\t" +
str(count3.day_of_week)+"\t" + str(count3.month)+"\t" + str(count3.hour))
writeFile.write("\n")
print("\n")
print("NUMBER OF PROCESSED ROBBERIES:" + str(len(updatedCrimes)))
print("\n")
print("DAY WITH MOST ROBBERIES:"+str(stat[0]))
print("\n")
print("MONTH WITH MOST ROBBERIES:"+str(stat[1]))
print("\n")
print("HOUR WITH MOST ROBBERIES:"+str(stat[2]))
writeFile.close()
if __name__ == '__main__':
main()
|
f7e3514213a8316cdf43c02a3d1e81310a22c549 | hulk-56/DS- | /practical3c.py | 509 | 3.9375 | 4 | class DoublyLinkedList:
def _init_(self):
self.__head = None
self.__tail = None
self.__size = 0
def is_empty(self) -> bool:
return self.__size == 0
def get_size(self) -> int:
return self.__size
def __display_backward(self):
if self.is_empty():
print("Doubly Linked List is empty")
return
last = self.__tail
print("The List: ", end='')
print("[" + last.element, end='')
last = last.prev
|
de92d4706fb43d9f0bbbbe7f76cec077dbaef07b | podsi08/advent-of-code-2015 | /day_2/day_2.py | 997 | 3.59375 | 4 | import re
def part_1(l, w, h):
list_1 = [l, w, h]
list_1.sort()
area = 2 * (l * w + l * h + w * h) + list_1[0] * list_1[1]
return area
def part_2(l, w, h):
list_1 = [l, w, h]
list_1.sort()
total_length = 2 * (list_1[0] + list_1[1]) + l * w * h
return total_length
def main():
with open("input.txt", "r") as file_input:
pattern = re.compile(
"^(?P<length>\d+)x"
"(?P<width>\d+)x"
"(?P<height>\d+)$"
)
paper_area = 0
ribbon = 0
for line in file_input:
match = pattern.match(line)
if match is not None:
length = int(match.group("length"))
width = int(match.group("width"))
height = int(match.group("height"))
paper_area += part_1(length, width, height)
ribbon += part_2(length, width, height)
print(paper_area)
print(ribbon)
if __name__ == '__main__':
main() |
de77b282098fd8e812381f7f5c2fbbb72f8562f5 | EricFuma/Algorithm_github | /算法思想/搜索/Backtracking/11. 子集/solution.py | 880 | 3.65625 | 4 |
# 此为未优化方法,用到了中间变量,并且多了一些无用的遍历
# 也即 tmp.append(seq)
'''
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = [[]]
for num in nums:
tmp = []
for i,seq in enumerate(result):
tmp.append(seq)
tmp.append(seq+[num])
result = tmp
return result
'''
# 非递归方法借鉴了层序遍历
# 此为去除中间变量、省掉无用遍历后的非递归方法
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = [[]]
for num in nums:
length = len(result)
total = length
while length > 0:
idx = total - length
length -= 1
result.append(result[idx]+[num])
return result
|
27cce374a5d14f11c328bf63d0f6145455fa636c | svenJonis138/Project_3_Artwork_Catalog | /controls_utils.py | 2,937 | 3.71875 | 4 | import artwork_db
"""this module checks all user given data for validity before calling DB functions"""
def artist_already_in_db(artist_name):
"""checks if artist is already registered"""
current_artists = artwork_db.get_all_artists()
names = []
for artist in current_artists:
names.append(artist.artist_name)
if artist_name.upper() in names:
return True
else:
return False
def artist_email_not_unique(artist_email):
"""checks to ensure email is unique"""
current_artists = artwork_db.get_all_artists()
for artist in current_artists:
if artist.email.upper() == artist_email.upper():
return True
else:
return False
def artist_has_work_in_db(artist_name):
"""checks if a registered artist has any work in DB"""
current_artwork = artwork_db.get_all_artwork()
names =[]
for artwork in current_artwork:
names.append(artwork.artist_name)
if artist_name in names:
return True
else:
return False
def artwork_name_is_unique(artwork_name):
"""checks if an artwork name is unique"""
current_artwork = artwork_db.get_all_artwork()
titles = []
for artwork in current_artwork:
titles.append(artwork.artwork_name.upper())
if artwork_name.upper() in titles:
return False
else:
return True
def price_is_right(price):
"""checks to ensure string price input is actually a number safe to parse to int"""
if price.isdigit():
return True
else:
return False
def artwork_exists(artwork_query):
"""checks to ensure a piece of art is in the database"""
current_artwork = artwork_db.get_all_artwork()
titles = []
for artwork in current_artwork:
titles.append(artwork.artwork_name.upper())
if artwork_query.upper() in titles:
return True
else:
return False
def name_of_artist(artwork_to_change):
"""grabs the name of the artist associated with either selling a piece or deleting
to use to confirm with user before updating the DB"""
current_artwork = artwork_db.get_all_artwork()
for artwork in current_artwork:
if artwork.artwork_name == artwork_to_change:
return artwork.artist_name
def response_affirmative(response):
"""checks the validity of yes no answers used to confirm updating DB"""
if response.upper() == 'Y':
return True
elif response.upper() == 'X':
print('exiting ')
return False
else:
return False
def artwork_available(artwork_name, artist):
"""checks if an artwork is available"""
currently_available = artwork_db.get_available_artwork_from_one_artist(artist)
titles = []
for artwork in currently_available:
titles.append(artwork.artwork_name.upper())
if artwork_name.upper() in titles:
return True
else:
return False
|
102f20ae50fd52442e6bb89b69b365fedea1c9af | magezil/holberton-system_engineering-devops | /0x16-api_advanced/0-subs.py | 626 | 3.578125 | 4 | #!/usr/bin/python3
"""
Finds number of subscribers for given subreddit account,
or 0 if invalid subreddit
"""
import requests
def number_of_subscribers(subreddit):
"""
Sends a query to Reddit API
Returns the number of subscribers for given subreddit
"""
url = "https://api.reddit.com/r/{}/about".format(subreddit)
headers = {'User-Agent': 'CustomClient/1.0'}
r = requests.get(url, headers=headers, allow_redirects=False)
if r.status_code != 200:
return 0
r = r.json()
if 'data' in r:
return r.get('data').get('subscribers')
else:
return 0
|
75d9131ed4cfc49aa7e1f471fd3d0456fb735821 | NguyenThuHuongg/BTVN | /prefixcodetree.py | 1,591 | 3.5 | 4 | class Node:
def __init__(s, data):
s.right = None
s.left = None
s.data = data
def isLeave(s):
return (s.right is None) and (s.left is None)
class PrefixCodeTree:
def __init__(s):
s.root = Node('')
def insert(s, codeword, symbol):
node = s.root
for code in codeword:
if (code == 0):
if (node.left is None):
node.left = Node('')
node = node.left
else:
node = node.left
else:
if (node.right is None):
node.right = Node('')
node = node.right
else:
node = node.right
node.data = symbol
def decode(s, encodedData, datalen):
data = ''
result = ''
node = s.root
# Convert encodedData to bit data
for byte in encodedData:
data += f'{byte:08b}'
# Decode encodedData
for i in range(datalen):
if (data[i] == '0'):
node = node.left
else:
node = node.right
if (node.isLeave()):
result += node.data
node = s.root
return result
if __name__ == '__main__':
codeTree = PrefixCodeTree()
codebook = {
'x1': [0],
'x2': [1, 0, 0],
'x3': [1, 0, 1],
'x4': [1, 1]
}
for symbol in codebook:
codeTree.insert(codebook[symbol], symbol)
print(codeTree.decode(b'\xd2\x9f\x20', 21))
|
c4a4d3bf94ffd001401a1eedb20b20864415ab89 | devThinKoki/learning_repo | /JetBrains_Academy/Python_Development_Course/Medium_Arithmetic-Exam-Application/02_Task-generator/02_[Others_class].py | 905 | 3.953125 | 4 | import random
class Calculator:
def __init__(self):
self.a = 0
self.b = 0
self.sign = None
self.result = 0
def operation(self):
if self.sign == '+':
self.result = self.a + self.b
elif self.sign == '-':
self.result = self.a - self.b
elif self.sign == '*':
self.result = self.a * self.b
def create_operation(self):
type_operation = ['+', '-', '*']
self.sign = random.choice(type_operation)
self.a = random.randint(2, 9)
self.b = random.randint(2, 9)
print(f'{self.a} {self.sign} {self.b}')
def compare_result(self):
answer = int(input())
if self.result == answer:
print('Right!')
else:
print('Wrong!')
data_calc = Calculator()
data_calc.create_operation()
data_calc.operation()
data_calc.compare_result() |
5881b53f26e3ff217453c92cea1cd77b91d8aa73 | AryanSamadzadaOPHS/Y10OPHSv2-1 | /While Loop Challenge03.py | 239 | 4.09375 | 4 | num1 = int(input("Enter a number"))
total = num1
loop = "y"
while loop == "y":
num2 = int(input("Enter another number "))
total += num2
loop = input("Do you want to add another number? Y or N").lower()
print(total)
|
49efcfbca1b4c0a096a55bbe25a7e83663c42119 | Ahmed-Abdelhak/Python | /Hackerrank API Certificate/Football Competition Winner's Goals/[API] getWinnerTotalGoals.py | 1,703 | 3.640625 | 4 | """
# Complete the 'getWinnerTotalGoals' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. STRING competition
# 2. INTEGER year
#
"""
import requests
import json
def goals_in_half_season(half, year, team, competition):
total_pages = 1
page = 1
data = ""
goals = 0
url = f"https://jsonmock.hackerrank.com/api/football_matches?competition={competition}&year={year}&team{half}={team}&page={page}"
data = requests.get(url)
json_data = json.loads(data.content)
sub_goals = [int(i[f'team{half}goals']) for i in json_data['data']]
goals += sum(sub_goals)
total_pages = int(json_data['total_pages'])
if total_pages > 1:
for i in range(2, total_pages+1):
url = f"https://jsonmock.hackerrank.com/api/football_matches?competition={competition}&year={year}&team{half}={team}&page={i}"
data = requests.get(url)
json_data = json.loads(data.content)
sub_goals = [int(i[f'team{half}goals']) for i in json_data['data']]
goals += sum(sub_goals)
return goals
def getTotalGoals(team, year,competition):
return goals_in_half_season(1, year, team, competition)+goals_in_half_season(2, year, team, competition)
def getWinnerTotalGoals(competition, year):
url = f"https://jsonmock.hackerrank.com/api/football_competitions?name={competition}&year={year}"
data = requests.get(url)
json_data = json.loads(data.content)
obj_data = json_data['data']
winner = obj_data[0]
team = winner['winner']
return getTotalGoals(team, year, competition)
# print(getWinnerTotalGoals("English Premier League", 2014))
|
543f38d899b4bca1a492278980e04f05af63b9dd | call-fold/python-test-everyday | /Test12_ExchangeFilteredWords/ExchangeFilteredWords.py | 690 | 3.640625 | 4 | #! /usr/bin/env python
# -*- coding: utf8 -*-
__author__ = "call_fold"
import Test11_FilteredWords.FilteredWords
def exchange_filtered_words(input_str, filtered_words_set):
out_str = input_str
for word in filtered_words_set:
word_len = len(word)
exchange_part = '*' * word_len
out_str = out_str.replace(word, exchange_part)
print(out_str)
if __name__ == '__main__':
words_set = Test11_FilteredWords.FilteredWords.get_filter_words('filtered_words.txt')
flag = True
while flag:
my_input_str = input('Input a word: ')
if '#' == my_input_str:
flag = False
exchange_filtered_words(my_input_str, words_set) |
69771d59d3ffab3a008135ef2cb271f9fdc2adea | schmit/sheepherding | /sheepherding/ai/neural.py | 4,315 | 3.859375 | 4 | '''
A small Neural Network implementation.
Note that since we are training using only residual, this module isn't that useful for other applications.
Here we use a list representation of features where each element of list corresponds to (key, value).
This helps with using very sparse features
'''
import random
from math import exp
class NeuralNetwork:
''' One hidden layer neural network '''
def __init__(self, regularization=0.000001):
self.layer = []
self.weights = []
self.updates = 0
self.bias = 0
self.regularization = regularization
def add_unit(self, unit):
self.layer.append(unit)
# initialize with random weight
self.weights.append(2*(random.random()-0.5))
def compute_activations(self, features):
activations = []
for unit in self.layer:
activations.append(unit.compute_output(features))
return activations
def predict(self, features):
activations = self.compute_activations(features)
return self.bias + sum(value * self.weights[index] for (index, value) in enumerate(activations))
def update(self, features, residual, stepsize=0.001):
self.updates += 1
# update bias
self.bias -= stepsize * -residual
# update weights and units
activations = self.compute_activations(features)
for index, activation in enumerate(activations):
partial = -residual * activation
self.weights[index] -= stepsize * partial + self.regularization * self.weights[index]
self.layer[index].update_weights(features, partial, stepsize)
class Unit:
def __init__(self, regularization=0.000001):
self.weights = {}
self.bias = self.random_weight()
self.regularization = regularization
def compute_output(self, features):
wx = self.wx(features)
return self.f(wx)
def wx(self, features):
''' compute inner product of weights and features '''
wx = 0
for key, value in features:
if key not in self.weights:
self.weights[key] = self.random_weight()
wx += value * self.weights[key]
return wx + self.bias
def update_weights(self, features, partial, stepsize):
# update bias
self.bias -= stepsize * partial
# update weights
derivatives = self.df(features)
for key, derivative in derivatives:
gradient = partial * derivative
self.weights[key] -= stepsize * gradient + self.regularization * self.weights[key]
def random_weight(self):
return (random.random() - 0.5)
def f(self, outcome):
'''Compute the activation function'''
raise NotImplementedError
def df(self, features, residual):
'''Compute the derivative of the activation function'''
raise NotImplementedError
class LinearUnit(Unit):
def f(self, wx):
''' Linear unit: f(x) = x '''
return wx
def df(self, features):
derivatives = {}
for key, value in features:
derivatives.append((key, value))
return derivatives
class RectifierUnit(Unit):
def f(self, wx):
''' Rectifier unit: f(x) = max(0, x) '''
return max(0, wx)
def df(self, features):
derivatives = []
if self.compute_output(features) > 0:
for key, value in features:
derivatives.append((key, value))
return derivatives
class SigmoidUnit(Unit):
def f(self, wx):
''' Sigmoid unit: f(x) = 1/(1+e^-x) '''
return 1.0 / (1.0 + exp(-wx))
def df(self, features):
wx = self.wx(features)
outcome = self.f(wx)
derivatives = []
if self.compute_output(features) > 0:
for key, value in features:
derivatives.append((key, value * outcome * (1-outcome)))
return derivatives
# helper functions to easily instantiate networks
def rectifier_network(nUnits):
network = NeuralNetwork()
for _ in xrange(nUnits):
network.add_unit(RectifierUnit())
return network
def sigmoid_network(nUnits):
network = NeuralNetwork()
for _ in xrange(nUnits):
network.add_unit(SigmoidUnit())
return network
|
a092a3e993050734423039a6dc76c41d4c526435 | gabriellaec/desoft-analise-exercicios | /backup/user_093/ch171_2020_06_22_18_42_39_701975.py | 329 | 3.671875 | 4 | class Carrinho:
def __init__(self):
self.dic={}
def adiciona(self,nome_produto,preco):
if not nome_produto in self.dic:
self.dic[nome_produto]=preco
else:
self.dic[nome_produto]+=preco
def total_de_produto (self,nome_produto):
return self.dic[nome_produto]
|
773898449c6549aa1b74dcb53c7607d3e52355bf | inhyebaik/Practice-Coding-Questions | /data_structures/LinkedList/linked_list.py | 840 | 3.859375 | 4 | class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def __repr__(self):
return '<Node val={}>'.format(self.value)
class LinkedList(object):
def __init__(self, values=None):
self.head = None
self.tail = None
if values:
self.add_multiple(values)
def __repr__(self):
values = []
curr = self.head
while curr:
values.append(str(curr.value))
curr = curr.next
return ' ->'.join(values)
def add(self, value):
if not self.head:
self.tail = self.head = Node(value)
else:
self.tail.next = Node(value)
self.tail = self.tail.next
def add_multiple(self, values):
for v in values:
self.add(v)
|
2bd8cdb755b29d185b159f02de9aec24e17e6ea0 | Iseke/BFDjango | /week1/CodeingBat/Warmup-2/string_bits.py | 105 | 3.703125 | 4 | def string_bits(str):
res=""
for x in range(len(str)):
if x%2==0:
res+=str[x]
return res
|
e7d46a61f1f138a07273f9a2128469a942146761 | chengsig/python-practice | /python-fundamentals/03-last_element/last_element.py | 184 | 3.796875 | 4 | def last_element(list):
if len(list) == 0:
return None
else:
return list[-1]
#better way to do this: if list: #true if it is not an empty list
|
0448fad0476d008fd3c54d2cec1d077a374a727e | katiebug2001/mitx.6.00.1x | /final/longest_run.py | 2,634 | 4.15625 | 4 | import unittest
def longest_run(L):
"""
Assumes L is a list of integers containing at least 2 elements.
Finds the longest run of numbers in L, where the longest run can
either be monotonically increasing or monotonically decreasing.
In case of a tie for the longest run, choose the longest run
that occurs first.
Does not modify the list.
Returns the sum of the longest run.
"""
length_longest_run = 0
list_longest_run = []
up_length_this_run = 0
up_list_this_run = []
down_length_this_run = 0
down_list_this_run = []
prev_num = None
for this_num in L:
#print('the number is {} & the previous number is {}'.format(this_num, prev_num))
try:
if prev_num <= this_num:
up_length_this_run += 1
up_list_this_run.append(this_num)
else:
up_length_this_run = 1
up_list_this_run = [this_num]
if prev_num >= this_num:
down_length_this_run += 1
down_list_this_run.append(this_num)
else:
down_length_this_run = 1
down_list_this_run = [this_num]
except TypeError:
up_length_this_run += 1
down_length_this_run += 1
up_list_this_run.append(this_num)
down_list_this_run.append(this_num)
prev_num = this_num
finally:
if up_length_this_run > length_longest_run:
length_longest_run, list_longest_run = up_length_this_run, up_list_this_run
elif down_length_this_run > length_longest_run:
length_longest_run, list_longest_run = down_length_this_run, down_list_this_run
prev_num = this_num
#print('this up is {}'.format(up_list_this_run))
#print('this down is {}'.format(down_list_this_run))
#print('current longest is {}'.format(list_longest_run))
return sum(list_longest_run)
# class test_longest_run(unittest.TestCase):
# """
# tests longest_run()
# """
#
# def test_this_longest_run(self):
# """
# tests that longest_run returns the correct value for [1, 2, 3, 2, 0] (should be 6); for [3, 2, 0, -1, 2] (should be 4) and [1] (should be 1)
# """
# test_sums = [6, 4, 1]
# test_lists = [[1, 2, 3, 2, 0], [3, 2, 0, -1, 2], [1]]
# self.assertEqual([longest_run(test_lists[0]), longest_run(test_lists[1]), longest_run(test_lists[2])], test_sums)
#
#
# if __name__ == '__main__':
# unittest.main()
print(longest_run([1, 2, 3, 2, -1, -10])) |
4803561553d179de8ad0aec8360124b665e2ee43 | DelRoos/crypto-tools | /package/classics/substitution/vigenere_class.py | 1,211 | 3.5 | 4 | class Vigenere:
def __init__(self, all_set: list):
self.all_set = all_set
def crypt(self, text: str, key: str)-> str:
key = self.__generate_key(text=text, key=key)
crypt_text = [
self.all_set[
(self.all_set.index(key[i]) + self.all_set.index(text[i])) % len(self.all_set)
]
for i in range(len(text))
]
return "".join(map(str, crypt_text))
def decrypt(self, text: str, key: str)-> str:
key = self.__generate_key(text=text, key=key)
crypt_text = [
self.all_set[
(self.all_set.index(text[i]) - self.all_set.index(key[i])) % len(self.all_set)
]
for i in range(len(text))
]
return "".join(map(str, crypt_text))
def __generate_key(self, text: str, key: str):
length_key = len(key)
length_text = len(text)
if length_text == length_key:
return key
if length_text < length_key:
key = key[:length_text]
elif length_text > length_key:
key = key*(length_text//length_key)+key[:(length_text%length_key)]
return key |
b01ebef36cedda7c5a28af34087c4eb211f4ad48 | hsqStephenZhang/Fluent-python | /可迭代的对象-迭代器-生成器/14.9标准库的生成器函数.py | 1,414 | 3.5625 | 4 | """
除了show1中的递归文件系统之外,itertools还提供了几大类生成器
1.过滤;2.映射;3.无中生有
"""
import os
import itertools
def show1(): # 递归搜索文件系统
for root, dirs, file in os.walk("E:/DESKTOP/GitHub"):
if dirs:
print("root:{},dirs:{}".format(root, dirs))
else:
print("files:{}".format(file))
def show2():
a = [i for i in range(2)]
b = [j for j in range(4)]
for a1, b1 in itertools.zip_longest(a, b, fillvalue=-1): # 以较长的可迭代对象为准
print(a1, ":", b1, end=",")
print("\n", end="")
try:
for a1, b1 in zip(a, b): # 只要有一个可迭代对象到头了,就停止了
print("{}:{}".format(a1, b1), end=" ")
except BaseException:
print("two iter object's length don't match")
def show3():
a = [1, 2, 3]
b = [4, 5, 6]
for i in itertools.chain(a, b):
print(i, end=" ")
def show4(): # 生成笛卡尔积
a = [1, 2, 3]
b = list("abc")
for elem in itertools.product(a, b, repeat=2):
print(elem, end=" ")
def show5():
nums = ['a', 'C', 'c', 'B', 'B', '1']
myiter = itertools.groupby(nums, key=lambda x: (x.isdigit()))
for key, value in myiter:
print(key, list(value), sep=":", end=" ")
if __name__ == '__main__':
# show1()
# show2()
# show3()
# show4()
show5()
|
93f2e0b0858880ab80eb5cbeb4e438568f76a108 | juanfer0002/NumericalAnalysis | /LagrangeInterpolation.py | 756 | 3.5625 | 4 | X_POINTS = [2, 2.5, 3.2, 4]
FX_POINTS = [8, 14, 15, 8]
def printFunction(L):
fx = ''
for l in L:
fx += ('%s + ') % l
# End for
fx = fx[0:len(fx)-2]
print(('f(x): %s') % (fx))
# End def
def getFraction(i):
numerator = ''
denominator = 1
currentX = X_POINTS[i]
for j in range(0, len(X_POINTS)):
if (i != j):
numerator += ('(x - %.2f)') % (X_POINTS[j])
denominator *= (currentX - X_POINTS[j])
# End if
# End for
return ('[ %s / %.2f ] * %.2f ') % (numerator, denominator, FX_POINTS[i])
# End getDenominator
def init():
L = []
for i in range(0, len(X_POINTS)):
L.append(getFraction(i))
# End for
printFunction(L)
# End init
init() |
36292b4ff16bc3292b6481faa5f8311ba152ebb6 | BIGduzy/Python-block-1 | /les_3/exercise_2.py | 509 | 3.8125 | 4 | # Practice Exercises les 3
# 3_2 (functie met list-parameter)
print('------------------------------------------------------------------------')
print('------------- Exercise 3_2 (functie met list-parameter) ---------------')
print('------------- Nick Bout - 1709217 - V1Q - Programming - HU -------------')
print('------------------------------------------------------------------------')
def som(intergers):
return sum(intergers)
print(som([1, 2, 3]), 'som([1, 2, 3]) == 6:', som([1, 2, 3]) == 6)
print()
|
5c0661d9a30308b83f12d2df5989a1ff32537a2d | Rublev09/edx600 | /6.00x/Midterm1/numpens.py | 485 | 3.796875 | 4 | def numPens(n):
"""
n is a non-negative integer
Returns True if some non-negative integer combination of 5, 8 and 24 equals n
Otherwise returns False.
"""
# Your Code Here
if n % 5 == 0 or n % 8 == 0:
return True
countfive = n / 5
counteight = n / 8
for i in range(countfive +1):
for p in range(counteight+1):
if (i * 5) + (p * 8) == n:
return True
else:
return False
|
4eab12c17018a4af05a9a240b1a84ccd3bd53bf3 | ovr1/test | /test1/test2_test18/test18_calcul_test.py | 722 | 3.5 | 4 | import mycalc
def test_add():
assert mycalc.add(1, 2) == 3
print("add(a, b) OK")
def test_mul():
if mycalc.mul(2, 5) == 10:
print("mul(a, b) OK")
else:
print("mul(a, b) NOT OK")
def test_sub():
if mycalc.sub(4, 2) == 2:
print("sub(a, b) OK")
else:
print("sub(a, b) NOT OK")
def test_div():
if mycalc.div(8, 4) == 2:
print("div(a, b) OK")
else:
print("div(a, b) NOT OK")
def test_sqrt():
if (mycalc.sqrt(9) - 3) < 0.000000001:
print("sqrt(a, b) OK")
else:
print("sqrt(a, b) NOT OK")
try:
test_add()
except AssertionError:
print("test_add(a, b) NOT OK")
test_mul()
test_sub()
test_div()
test_sqrt() |
9c6b56394d93750bebdcb3889012f805bae4901e | slumflower/mit-intro-to-cs-python | /ProblemSet1/pset2/solution.py | 138 | 3.859375 | 4 | numBobs = 0
for i in range(len(s)):
if s[i:i+3] == 'bob':
numBobs +=1
print('Number of times bob occurs is: '+ str(numBobs))
|
4a685da92b00e861eda9c1c6ef6eb074d7c85e9c | audhiaprilliant/indonesian-id-card-identification | /src/utils/helper.py | 232 | 3.703125 | 4 | # Module for binary search
from bisect import bisect_left
def binary_search(a, x):
elem = bisect_left(a, x)
# check the data
status = False
if elem != len(a) and a[elem] == x:
status = True
return status |
d36f23aa8d7da4be3cc978919890d94bb0f0cf25 | Umangsharma9533/Essentials_For_DataScientist | /Introduction_To_Database_Using_SQLAlchemy/Select_query_using_orderby.py | 1,653 | 3.828125 | 4 | # Import create_engine function
from sqlalchemy import create_engine
# Import desc
from sqlalchemy import select,desc
# Create an engine to the census database
engine = create_engine('postgresql+psycopg2://student:datacamp@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com:5432/census')
# Use the .table_names() method on the engine to print the table names
print(engine.table_names())
# Build a query to select the state column: stmt
stmt = select([census.columns.state])
# Order stmt by the state column
stmt = stmt.order_by(census.columns.state)
# Execute the query and store the results: results
results = connection.execute(stmt).fetchall()
# Print the first 10 results
print(results[:10])
#==================================================
#orderby()= Descending
# Build a query to select the state column: stmt
stmt = select([census.columns.state])
# Order stmt by state in descending order: rev_stmt
rev_stmt = stmt.order_by(desc(census.columns.state))
# Execute the query and store the results: rev_results
rev_results = connection.execute(rev_stmt).fetchall()
# Print the first 10 rev_results
print(rev_results[:10])
#=======================================================
#Order one column in ascending and one in descending
# Build a query to select state and age: stmt
stmt = select([census.columns.state,census.columns.age])
# Append order by to ascend by state and descend by age
#orderby method will get sorted from left to right
stmt = stmt.order_by(census.columns.state, desc(census.columns.age))
# Execute the statement and store all the records: results
results = connection.execute(stmt).fetchall()
# Print the first 20 results
print(results[:20])
|
497542216c1da5222c3a0afbcce79a3d2f331511 | jrobinson-vs/fiftyone | /docs/source/tutorials/query_flickr.py | 2,383 | 3.609375 | 4 | """
Simple utility to download images from Flickr based on a text query.
Requires a user-specified API key, which can be obtained for free at
https://www.flickr.com/services/apps/create.
Copyright 2017-2021, Voxel51, Inc.
voxel51.com
"""
import argparse
from itertools import takewhile
import os
import flickrapi
import eta.core.storage as etas
def query_flickr(
key, secret, query, number=50, path="data", query_in_path=True
):
# Flickr api access key
flickr = flickrapi.FlickrAPI(key, secret, cache=True)
# could also query by tags and tag_mode='all'
photos = flickr.walk(
text=query, extras="url_c", per_page=50, sort="relevance"
)
urls = []
for photo in takewhile(lambda _: len(urls) < number, photos):
url = photo.get("url_c")
if url is not None:
urls.append(url)
if query_in_path:
basedir = os.path.join(path, query)
else:
basedir = path
print(
"Downloading %d images matching query '%s' to '%s'"
% (len(urls), query, basedir)
)
client = etas.HTTPStorageClient()
for url in urls:
outpath = os.path.join(basedir, client.get_filename(url))
client.download(url, outpath)
print("Downloading image to '%s'" % outpath)
if __name__ == "__main__":
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument("key", type=str, help="Flickr API key")
parser.add_argument("secret", type=str, help="Secret to Flickr API key")
parser.add_argument("query", type=str, help="Query string to use")
parser.add_argument(
"-n",
"--number",
type=int,
default=50,
help="number of images to download (default: 50)",
)
parser.add_argument(
"-p",
"--path",
type=str,
default="data",
help="path to download the images (created if needed)",
)
parser.add_argument(
"--query-in-path", "-i", dest="query_in_path", action="store_true"
)
parser.add_argument(
"--no-query-in-path", dest="query_in_path", action="store_false"
)
parser.set_defaults(query_in_path=True)
args = parser.parse_args()
query_flickr(
key=args.key,
secret=args.secret,
query=args.query,
number=args.number,
path=args.path,
query_in_path=args.query_in_path,
)
|
4ed6f7b7943c324349bc0b3721e246b87a12d1bc | superhman/DSC510Spring2020 | /Gunasekaran_DS510/Gunasekaran_DS510_week8_1.py | 1,998 | 3.96875 | 4 | # File : Gunasekaran_DS510_week8_1.py
# Name : Ragunath Gunasekaran
# Date : 05/01/2020
# Course : DSC-510 - Introduction to Programming
# Assignment :
# Open the file and process each line.
# Either add each word to the dictionary with a frequency of 1
# or update the word’s count by 1.
# Print the output, in this case from high to low frequency
import string
def process_line(line, word_dict):
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Remove the punctuation marks from the line
line = line.translate(line.maketrans("", "", string.punctuation))
# Split the line into words
words = line.split(" ")
process_add(words, word_dict)
def process_add(words, word_dict):
for word in words:
# Check if the word is already in dictionary
if word in word_dict:
# Increment count of word by 1
word_dict[word] = word_dict[word] + 1
else:
# Add the word to dictionary with count 1
word_dict[word] = 1
# Print the contents of dictionary
def format_print(word_dict, word_num):
# Print the contents of dictionary
print('Length of the dictionary :', len(word_dict))
print("{:<20} {:<15} ".format('Word', 'Count'))
print("---------------------------")
# for key in list((d.keys())):
for key in sorted(word_dict, key=word_dict.get, reverse=True):
# print(key, ":", d[key])
print("{:<20} {:<15} ".format(key, word_dict[key]))
def main():
# Open the file in read mode
gba_file = open("D:\Python\gettysburg.txt", "r")
# Create an empty dictionary
word_dict = dict()
# Loop through each line of the file
for line in gba_file:
process_line(line, word_dict)
gba_file.close()
format_print(word_dict, len(word_dict))
if __name__ == '__main__':
main()
|
3b82645421d1c39f622296c139a6ba6632e30fe5 | mak705/Python_interview | /python_prgrams/testpython/strings8.py | 90 | 3.84375 | 4 | fruit = raw_input('Enter the name of a fruit: ')
for letter in fruit[::-1]: print(letter)
|
d8e5f5c5a7e34035d39235ed52b07576c4cbfe5e | Pradnya1208/Python_tkinter101 | /03. Widgets/buttons.py | 409 | 3.921875 | 4 | from tkinter import *
root = Tk()
def clickFunction():
label = Label(root, text = "this is tkinter buttons example")
label.pack()
button1 = Button(root, text="click", command = clickFunction, fg = "white", bg = "Black")
button2 = Button(root, text="Next", state = DISABLED)
button3 = Button(root, text="Back", padx = 50, pady = 10)
button1.pack()
button2.pack()
button3.pack()
root.mainloop()
|
e214bbdc5d7e82f3543d78c729ae68aae17589db | lvah/201903python | /day32/09_数组拼接.py | 1,475 | 3.90625 | 4 | """
concatenate 连接沿现有轴的数组序列
stack 沿着新的轴加入一系列数组。
hstack 水平堆叠序列中的数组(列方向)
vstack 竖直堆叠序列中的数组(行方向)
"""
import numpy as np
print("******************** concatenate ****************")
a = np.array([[1, 2], [3, 4]])
print('第一个数组:')
print(a)
print('\n')
b = np.array([[5, 6], [7, 8]])
print('第二个数组:')
print(b)
print('\n')
# 两个数组的维度相同
# x轴和y轴, 1轴和0轴
print('沿轴 0 连接两个数组:')
print(np.concatenate((a, b)))
print('\n')
print('沿轴 1 连接两个数组:')
print(np.concatenate((a, b), axis=1))
print("*************************stack*********************************")
a = np.array([[1, 2], [3, 4]])
print('第一个数组:')
print(a)
print('\n')
b = np.array([[5, 6], [7, 8]])
print('第二个数组:')
print(b)
print('\n')
print('沿轴 0 堆叠两个数组:')
print(np.stack((a, b), axis=0))
print('\n')
print('沿轴 1 堆叠两个数组:')
print(np.stack((a, b), axis=1))
#
#
print("**************************************hstack + vstack*************************************")
a = np.array([[1, 2], [3, 4]])
print('第一个数组:')
print(a)
print('\n')
b = np.array([[5, 6], [7, 8]])
print('第二个数组:')
print(b)
print('\n')
print('水平堆叠:')
c = np.hstack((a, b))
print(c)
print('\n')
print('竖直堆叠:')
c = np.vstack((a, b))
print(c)
print('\n') |
881180be6abf69369f97b49f00181aa24f657dcd | AfaqueAhmed1198/python | /calculate radius.py | 178 | 4.5 | 4 | # program calculate radius
from math import pi
r = float(input("Enter the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str(r**2)) |
f11b403f2460346c783e1a744ac550cecf8b093f | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /Conditional/Lista 1/Vitor Lameirão/Ex9.py | 404 | 3.96875 | 4 | #Entrada
x,y=map(int,input("Digite um ponto no plano cartesiano, separado por vírgula: ").split(","))
#Processamento
if x>0:
if y>=0:
print("Primeiro quadrante.")
else:
print("Quarto quadrante.")
else:
if x<0:
if y<=0:
print("Terceiro quadrante.")
else:
print("Segundo quadrante.")
else:
print("Origem.")
|
d558b674725dc21fdf69d447c336851fbe8478e3 | sklationd/boj | /src/18301/18301.py | 111 | 3.53125 | 4 | n1,n2,n12 = input().split(' ')
n1 = int(n1)
n2 = int(n2)
n12 = int(n12)
print(int( (n1+1)*(n2+1)/(n12+1) - 1 )) |
4316230503e1a9b734370a9fd188f8a410738f1d | songyingxin/python-algorithm | /动态规划/offer/offer_70_rect_cover.py | 406 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# 动态规划方程: f(1) = 1, f(2) = 2, f(n) = f(n-1) + f(n-2)
class Solution:
def rectCover(self , number: int) -> int:
# write code here
if number == 0:
return 0
start_one = 1
start_two = 2
for i in range(number-1):
start_one, start_two = start_two, start_one + start_two
return start_one
|
9b2942af2f9323c4e45505b47279953e4edf81d2 | sahilsamgi/SECU2002_SBABA09 | /lab03/hangman.py | 978 | 3.84375 | 4 | class Hangman:
pass
print "welcome"
secret_phrase = open("secret_phrase.txt").read()
# text = open("secret_phrase.txt", "r") #tester
# print(text.read()) #tester
shown_phrase = []
wrong = []
tries=10
while tries>0:
out = ""
for letter in secret_phrase:
if letter in shown_phrase:
out = out + letter
else:
out = out + "_"
if out == secret_phrase:
print "you have guessed", secret_phrase
break
print "guess the word and press enter", out
guess = raw_input()
if guess in shown_phrase or guess in wrong:
print "Already guessed", guess
elif guess in secret_phrase:
print "correct"
shown_phrase.append(guess)
else:
print "incorrect, you have: ", tries, "left","\n"
tries=tries-1
wrong.append(guess)
if tries:
print "you have guessed", secret_phrase
else:
print "you did not get", secret_phrase
print "game over"
print
|
2b27332a74b0c61159cf131c8cb20ab15eaf483a | timlehane/Code | /Python/stack_ADT_tetris_variant.py | 7,022 | 4.34375 | 4 | """ Classes and methods that use the Stack ADT.
"""
import stacksLecture
from stacksLecture import Stack
def create_stack():
""" Create and return a stack using one implementation of the ADT. """
return Stack()
def test():
""" Test the basic functionality of the stack.
Is exactly the same as the class method in each stack implementation.
"""
stack = create_stack()
stack.push(1)
stack.push(2)
stack.push(3)
print('stack should be |-1-2-3-->, and is', stack)
print('stack.length should be 3, and is', stack.length())
print('stack.is_empty() should be False, and is', stack.is_empty())
print('stack.top() should be 3, and is', stack.top())
print('stack.pop() should be 3, and is', stack.pop())
print('stack should now be |-1-2-->, and is', stack)
print('stack.length() should be 2, and is', stack.length())
stack.pop()
stack.pop()
print('popped two more items; stack.length() should be 0, and is', stack.length())
print('stack.top() should be None, and is', stack.top())
print('stack.pop() should be None, and is', stack.top())
print('stack should be |-->, and is', stack)
def reverse(stack):
""" turn a stack upside down.
Note: assume stack is genuinely a stack.
"""
result = create_stack()
while (stack.length() > 0):
result.push(stack.pop())
return result
def test_reverse_stack():
emptystack = create_stack()
print('stack =', emptystack)
print('reversed stack =', reverse(emptystack))
stack = create_stack()
inputstring = 'abcdefgh'
for x in inputstring:
stack.push(x)
print('stack =', stack)
print('reversed stack =', reverse(stack))
def infix_to_postfix(string):
""" Convert an infix string to postfix, using a stack.
Elements must be separated by spaces.
"""
tokenlist = string.split()
output = []
stack = create_stack()
for token in tokenlist:
if token == '(':
stack.push(token)
elif token == ')':
toptoken = stack.pop()
while toptoken != '(':
output.append(toptoken)
toptoken = stack.pop()
elif token == '*' or token == '/':
toptoken = stack.top()
while toptoken in ['*','/']:
output.append(stack.pop())
toptoken = stack.top()
stack.push(token)
elif token == '+' or token == '-':
toptoken = stack.top()
while toptoken in ['*','/','+','-']:
output.append(stack.pop())
toptoken = stack.top()
stack.push(token)
else:
output.append(token)
while stack.length() > 0:
output.append(stack.pop())
space= ' '
newstr = space.join(output)
return newstr
def evaluate_infix(string):
""" Evaluate an infix expression, using two stacks. """
return postfix(infix_to_postfix(string))
def match(str1, str2):
""" Determine whether two ingle-char strings are matching brackets. """
if ( (str2 == '[' and str1 == ']')
or (str2 == '{' and str1 == '}')
or (str2 == '(' and str1 == ')')):
return True
return False
def balanced_string(string):
""" Determine whether the brackets in a string are balanced. """
stack = create_stack()
pos = 0
while pos < len(string):
if string[pos] in '[{(':
stack.push(string[pos])
elif string[pos] in ']})':
pair = stack.pop()
if not match(string[pos], pair):
return False
pos = pos+1
#return stack.length()
if stack.length() == 0:
return True
else:
return False
import random
import time
def colour_tetris_1D(rounds):
""" Play single stack colour tetris, for specified # of rounds. """
charstr = 'RGB'
blocklist = []
stack = create_stack()
count = 0
for i in range(rounds):
blocklist.append(charstr[random.randint(0,2)])
#print('blocklist =', blocklist)
prefix = ' '
i = 1
for block in blocklist:
output = str(i) + ': Accept ' + block + '?'
clocktime0 = time.time()
ans = input(output)
clocktime1 = time.time()
elapsed = clocktime1 - clocktime0
success = ' '
if elapsed > 2:
print('TOO LATE (', elapsed, ' sec), block accepted')
ans = 'y'
if ans == 'y' or ans == 'Y':
if stack.top() == block:
stack.pop()
count = count + 1
success = block + '-' + block + ' * '
else:
stack.push(block)
print(success + 'Score = ' + str(count) + '; Stack: ' + str(stack))
i = i+1
print(stack.length(), 'still in stack')
print('Score:', count - stack.length())
def colour_tetris(stacks, colours, rounds, th, secs):
""" Play multi-stack colour tetris.
stacks is the number of stacks.
colours is the number of colours.
rounds is the number of blocks to be generated (up to 7).
th is the maximum height for a stack.
secs is the number of seconds available for each move.
"""
stacklist = []
for i in range(stacks):
stacklist.append(create_stack())
charstr = 'RGBOYIV'
#generate the list of blocks
blocklist = []
for i in range(rounds):
blocklist.append(charstr[random.randint(0,colours-1)])
i = 0
matches = 0
threshold = True
#reveal each block in turn, until exhausted or threshold breached
while i < len(blocklist) and threshold:
block = blocklist[i]
i = i+1
#display the block and get the user response
output = str(i) + ': ' + block + '?'
clocktime0 = time.time()
ans = input(output)
clocktime1 = time.time()
elapsed = clocktime1 - clocktime0
#now propcess the user response
if elapsed > secs:
print('TOO LATE (', elapsed, ' sec), block add to stack 1')
ans = '1'
if ans in['1','2','3','4']:
value = int(ans)-1
else:
value = 0
#now try to match the block with the top of the user's chosen stack
if stacklist[value].top() == block: #successful match
stacklist[value].pop()
print(' ******************************** ')
matches = matches + 1
else: #failed match, so grow the stack
stacklist[value].push(block)
if stacklist[value].length() >= th:
threshold = False
else:
j = 0
while j < len(stacklist):
print((j+1), ':', stacklist[j])
j = j+1
if threshold:
print('Congratulations! You beat the system, and made', matches, 'matches.')
else:
print('You lasted for', i, 'rounds, and made', matches, 'matches.')
|
a67db4cf217b9bdae04bd499c468fafb0322b6d6 | jeffmorice/web-caesar | /helpers.py | 799 | 4.15625 | 4 | import string
def alphabet_position(letter):
# return the 0-based position of the letter in the alphabet
# case-INsensitive
uppercase = string.ascii_uppercase
up_str = letter.upper()
#print(up_str)
for char in range(len(uppercase)):
if uppercase[char] == up_str:
return char
#uppercase = string.ascii_uppercase
#print(type(uppercase))
#print(alphabet_position("Z"))
def rotate_character(char, rot):
uppercase = string.ascii_uppercase
lowercase = string.ascii_lowercase
pos = alphabet_position(char)
if char in uppercase:
new_char = uppercase[(pos + rot) % 26]
elif char in lowercase:
new_char = lowercase[(pos + rot) % 26]
else:
new_char = char
return new_char
#print(rotate_character("%", 13))
|
da6868c4bed46fb1e5e973889cd40b78b7f0721a | MarvinChen003/TechDegree-Project-3 | /phrasehunter/phrase.py | 1,515 | 3.71875 | 4 |
class Phrase():
def __init__(self, phrase):
self.phrase = phrase
def display(self, guesses):
for letter in self.phrase:
if letter == " ":
print(" ", end=" ")
else:
matches_guess = False
for guess in guesses:
if guess == letter:
print(f"{letter}", end=" ")
matches_guess = True
if matches_guess == False:
print("_", end=" ")
# matches_guess might not necessary here
# if guess == letter:
# print(f"{letter}", end=" ")
# else:
# print("_", end=" ")
def check_phrase(self, guess):
value = 0
if guess in self.phrase:
value += 1
return value
# From the code it looks like a counter, but it is kind of a boolean
# if guess in lower(self.phrase):
# return True
# might be enough
def check_complete(self, guesses):
check_complete_value = True
for letter in self.phrase:
if letter not in guesses:
check_complete_value = False
return check_complete_value
# line 28 -32, indent
# might change to something like following:
# ===
# for letter in self.phrase:
# if letter not in guesses:
# return False
# return True |
3f358a891d29b8d1151b5f8a5a9d1eee43b9ea8e | bam8r4/algorithims-proj-1 | /recursiveFib.py | 833 | 4.3125 | 4 | #Author of this code:Brent Moran
#This code outputs the nth fibonacci number by computing it recursively and outputs the time required to reach that result.
#I am importing time to measure how long the execution takes.
import time
#Prompt the user for an input.
print("Input value for N: ")
#Taking input from the user to determine which fib number to solve for.
N = input()
def recur(N):
if N < 0:
print("That is not a correct input")
elif N == 0:
return 0
elif N == 1:
return 1
elif N==2:
return 1
else:
return recur(N-1) + recur(N-2)
#We will start the timer before and end it after the execution of the function is completed.
start = time.time()
print("The result is:")
print(recur(N))
end = time.time()
print("The time required in seconds for this size input is: ")
print(end-start)
|
e2b9c5488326881969f82549f655b7b7bf88bed2 | VetKira/daotrongcuong-fundamentals-c4e23 | /session2/ptbac2.py | 403 | 3.671875 | 4 | a= int(input("a= "))
b= int(input("b= "))
c= int(input("c= "))
delta = b*b-(4*a*c)
print(delta)
if delta <0:
print("pt vo nghiem")
elif delta == 0: # 2 dau bang , 1 dau bang la gan gia tri , 2 dau la dem ra so sanh
print("pt co 1 nghiem")
x= (-b)/(2*a)
print(x)
elif delta >0:
print("pt co 2 nghiem")
x1= ((-b)+delta**0.5)/(2*a)
x2= ((-b)-delta**0.5)/(2*a)
print(x1,x2)
|
5320d760aa23d920ed4c33e1a690067520e2e604 | kathirraja/Think-Python-exercises-solutions | /is anagram.10.7.py | 346 | 3.890625 | 4 | def is_anagram(str1,str2):
word1 = list(str1)
word2 = list(str2)
if(len(word1)==len(word2)):
for letter in word1:
if letter in word2:
word2.remove(letter)
else:
return False
if len(word2)==0:
return True
else:
return False
|
df63577de468f719c42174ff81a49f99907c8772 | hlthu/PyTorch-Learn | /tutorial/08_simple_dnn_nn_package.py | 1,181 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
This is a simple example of DNN using Pytorch's nn package
"""
import torch
from torch.autograd import Variable
# data type: CPU or GPU
# dtype = torch.FloatTensor
dtype = torch.cuda.FloatTensor
# N batch: size
# D_in: input size
# D_out: output size
# H: hidden size
N, D_in, H, D_out = 16, 1024, 256, 128
# create input and output data
x = Variable(torch.randn(N, D_in).type(dtype))
y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False)
# using nn.Sequential() to create a model instance
model = torch.nn.Sequential(
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out),
)
# send the model to GPU
model.cuda()
# define a MSE loss function using nn
loss_fn = torch.nn.MSELoss(size_average=False)
# Training
learning_rate = 1e-5
for t in range(1000):
# forward
y_pred = model(x)
# loss
loss = loss_fn(y_pred, y)
if t % 100 == 99:
print(t+1, loss.data[0])
# zeros the grads
model.zero_grad()
# backward
loss.backward()
# update the parameters in the model
for param in model.parameters():
param.data -= learning_rate * param.grad.data
|
efea1110eecc95e220c031853949329cb984c3e8 | kmgowda/kmg-leetcode-python | /can-place-flowers/can-place-flowers.py | 435 | 3.78125 | 4 | // https://leetcode.com/problems/can-place-flowers
class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
tmp = [0]+flowerbed+[0]
for i in range(1, len(tmp)-1):
if tmp[i-1] == tmp[i] == tmp[i+1] == 0:
tmp[i] = 1
n-=1
return n<1
|
098f83712463ba888097a595ad0618a08ecb001c | jangxyz/springnote.py-with-oauth | /test/hamcrest/core/internal/.svn/text-base/hasmethod.py.svn-base | 212 | 3.625 | 4 | def hasmethod(obj, methodname):
"""Does obj have a method named methodname?"""
if not hasattr(obj, methodname):
return False
method = getattr(obj, methodname)
return callable(method)
|
24c3dc43943cee5b5ddcd534aeaecf036c9bd889 | RubeusH/Python_Learning | /Chapter-03/Exercises/Exercise-16.py | 1,053 | 4.4375 | 4 | #This program solves the following problem:
#The month of February normally has 28 days. But if it is a leap year, February has 29 days.
#Write a program that asks the user to enter a year. The program should then display the number
#of days in February that year. Use the following criteria to identify leap years:
#1. Determine whether the year is divisible by 100. If it is, then it is a leap year if and only if it
#is also divisible by 400. For example, 2000 is a leap year, but 2100 is not.
#2. If the year is not divisible by 100, then it is a leap year if and only if it is divisible by 4. For
#example, 2008 is a leap year, but 2009 is not.
#Here we declare our constants
TEST1 = 100
SUBTEST1 = 400
TEST2 = 4
DIVIDES = 0
#Gets user input
year = int(input("Enter a year here: "))
#Test the year
if year % TEST1 == DIVIDES:
if year % TEST2 == DIVIDES:
print(year, "was a leap year")
else:
print(year, "was not a leap year")
else:
if year % TEST2 == DIVIDES:
print(year, "was a leap year")
else:
print(year, "was not a leap year")
|
7704e7a43f831467935606960ee7b75f3f0752cc | dolphinsboy/algorithem | /python/leetcode/1_two_sum.py | 560 | 3.515625 | 4 | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
pair = {}
idx_list = []
for idx,n in enumerate(nums):
val = target - n
if val in pair:
idx_list.append(pair[val])
idx_list.append(idx)
break
else:
pair[n] = idx
return idx_list
s = Solution()
nums = [-1,-2,-3,-4,-5]
target = -8
print s.twoSum(nums, target)
|
7b3a094b9bee34533763f8ed39cb2ebd5bc2bd02 | EsaikaniL/Python-exercise | /maxamong10numbers.py | 154 | 3.875 | 4 | number=[]
n=int(raw_input("Enter number of elements:"))
for i in range(0,n):
b=int(raw_input())
number.append(b)
number.sort()
print(number[n-1])
|
fe1bdbcb0228d2279bbfbc8f96b961fa0f602d94 | mashache/homework | /Programming/hw 4/hw4 var6.py | 109 | 3.859375 | 4 | word = input('Введите ваше слово: ')
for i in word:
print (word[1:])
word = word[1:]
|
ec3fef26aa5d0ec21e31d5d6f6f8807813753042 | grapefruit623/leetcode | /easy/532_k_diffsPairsInAnArray.py | 1,267 | 3.6875 | 4 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import unittest
from typing import List
class Solution:
'''
AC
'''
def findPairs(self, nums: List[int], k:int)->int:
nums = sorted(nums)
table = dict()
ans = 0
# absoulte difference must be not negative value
if k < 0:
return 0
for n in nums:
table[n] = table.setdefault(n, 0) + 1
for n in table.keys():
if n + k == n :
if table[n] >= 2:
ans += 1
elif n + k in table:
ans += 1
return ans
class Unittest_findPairs(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_sample1(self):
inp = [3,1,4,1,5]
k = 2
self.assertEqual(2, self.sol.findPairs(inp, k))
def test_sample2(self):
inp = [1,2,3,4,5]
k = 1
self.assertEqual(4, self.sol.findPairs(inp, k))
def test_sample3(self):
inp = [1,3,1,5,4]
k = 0
self.assertEqual(1, self.sol.findPairs(inp, k))
def test_sample5(self):
inp = [1,2,3,4,5]
k = -1
self.assertEqual(0, self.sol.findPairs(inp, k))
if __name__ == "__main__":
unittest.main()
|
cd3fcdd1e3e2c373e3b6ee0cf58352140cca9ed4 | Chaosye/BIO_131 | /Week 3/HW3/anna_challenge_functions.py | 5,642 | 3.5625 | 4 | ## Functions for HW3
## Written by Anna Ritz
## Last Edited Feb 5, 2016
import sys
#######################################################
## Functions to Manipulate Datasets
#######################################################
def getData(dataset):
'''
Given a dataset name, returns five things:
- DNA string
- exonStarts list
- intronStarts list
- strand string (either '+' or '-')
- mRNA string (for comparison)
- peptide string (for comparison)
NOTE: The datafiles/ directory must be in the same location as the .py file.
'''
sequenceFile = 'datafiles/'+dataset+'-sequences.fasta'
dna,rna,peptide = readFasta(sequenceFile)
## add a STOP codon to the peptide sequence.
peptide = peptide + '*'
tablefile = 'datafiles/'+dataset+'-exon-info.txt'
exonStarts,intronStarts,strand = readTable(tablefile)
return dna,exonStarts,intronStarts,strand,rna,peptide
def readTable(infile):
'''
Reads a knownGene table from the UCSC Genome Browser.
Specifications: this table has two lines, one of row headers and one
of a single isoform of a gene. The columns are specified by the UCSC
genome browser. See the schema here:
http://genome.ucsc.edu/cgi-bin/hgTables and click "describe table schema"
Input: a file name, including the directory name.
Outputs three things:
exonStarts - a list of exon starting points
intronStarts - a list of intron starting points
strand - a string that is either '+' or '-'.
Example: readTable('datafiles/testPositiveStrand-exon-info.txt')
returns [[3, 19], [9, 28], '+'].
Usage: exonStarts,intronStarts,strand = readTable('datafiles/testPositiveStrand-exon-info.txt')
'''
# Read and parse the elements in the row.
tableLines = open(infile,'r').readlines()
row = tableLines[1].split()
strand = row[2]
transcriptionStart = int(row[3]) # convert the string to an int
transcriptionEnd = int(row[4])
codingRegionStart = int(row[5])
codingRegionEnd = int(row[6])
exonStarts = [int(start) for start in row[8].split(',') if len(start) != 0]
intronStarts = [int(start) for start in row[9].split(',') if len(start) != 0]
## The variables now have the original values from the table. We need
## to transform them by (1) moving indices of the non-coding portions
## of exons and (2) adjusting the indices to they start at 0.
## First, identify the positions of the coding regions.
## Sometimes entire exons are non-coding! Remove these.
indicesAbove5PrimeUTR = [i for i in range(len(intronStarts)) if intronStarts[i]>codingRegionStart]
indicesBelow3PrimeUTR = [i for i in range(len(exonStarts)) if exonStarts[i]<codingRegionEnd]
indicesToKeep = [i for i in range(len(exonStarts)) if i in indicesAbove5PrimeUTR and i in indicesBelow3PrimeUTR]
exonStarts = [exonStarts[i] for i in indicesToKeep]
intronStarts = [intronStarts[i] for i in indicesToKeep]
## the exonStarts and intronStarts must be adjusted to be coding regions only.
## We can now adjust the start point of the first exon and the end point
## of the last exon.
if codingRegionStart > transcriptionStart:
exonStarts[0] = codingRegionStart
if transcriptionEnd > codingRegionEnd:
intronStarts[-1] = codingRegionEnd
# Print the number of exons, if we have completely removed some.
#if len(exonStarts) != int(row[7]):
# print('After removing non-coding exons, %d exons left.' % (len(exonStarts)))
## shift the exon Starts and Ends to be 0.
exonStarts = [start-transcriptionStart for start in exonStarts]
intronStarts = [start-transcriptionStart for start in intronStarts]
## return the exonStarts and the intronStarts (indexed at 0)
## and the strand (+/-)
return exonStarts,intronStarts,strand
def readFasta(infile):
'''
Returns the sequences in the FASTA file, with the line breaks (newlines)
removed.
Specifications: this file must have THREE sequences, labeled by three headers
named '>dna','>rna','>peptide'.
Input: a file name, including the directory name.
Output: three strings representing the DNA, RNA, and peptide sequencs.
Example: readFasta('testPos')
'''
## fileLines is a list of strings from the infile variable.
fileLines = open(infile,'r').readlines()
## dna, rna, and peptide will eventually contain the sequences
## we will return.
dna = ''
rna = ''
peptide = ''
## thisheader will contain the most recent header (line with a ">").
thisheader = ''
## go through each line in fileLines...
for line in fileLines:
## remove newlines
strippedLine = line.strip()
## update the header if this line starts with a ">"
## otherwise, add the line to either dna, rna, or peptide.
if strippedLine[0] == '>':
thisheader = strippedLine
else:
## make line upper case
strippedLine = strippedLine.upper()
## check the header to see which variable to add the string to.
if thisheader == '>dna':
dna = dna + strippedLine
elif thisheader == '>rna':
rna = rna + strippedLine
elif thisheader == '>peptide':
peptide = peptide + strippedLine
else:
## The header wasn't one of the ones above - print an error message.
sys.exit('Error! Header "'+thisheader+'" is not >dna, >rna, or >peptide. Exiting.\n')
return dna,rna,peptide
|
c0cc51389691205d2d2d7ac932025b55119d5d17 | ezdennis/Food-Delivery-System | /userData.py | 286 | 3.6875 | 4 | import sqlite3 as lit
#define connection and cursor
connection = lit.connect('userdata.db')
cursor = connection.cursor()
#create username table
command1 = """CREATE TABLE IF NOT EXISTS
users(username TEXT,password TEXT,name TEXT,email TEXT,field TEXT)"""
cursor.execute(command1) |
f9542b245031a7ae8f32dc8010c0fe717c6f0113 | uniquearya70/Python_Practice_Code | /q74.py | 349 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 18 16:13:08 2018
@author: arpitansh
"""
'''
Please write a program to print the running time of execution of "1+1" for 100 times.
Hints:
Use timeit() function to measure the running time.
'''
from timeit import Timer
t = Timer("for i in range(100):1+1")
print (t.timeit()) |
657c23f914b221d82e21c9fed9580c40f711def2 | PSFREITASUEA/estcmp060 | /TriangleClick.py | 511 | 4 | 4 | import turtle
def draw_triangle(x_axis_coordinate, y_axis_coordinate):
turtle_pen.penup()
turtle_pen.goto(x_axis_coordinate, y_axis_coordinate)
turtle_pen.pendown()
for i in range(0, 3):
turtle_pen.forward(100)
turtle_pen.left(120)
turtle_pen.forward(100)
if __name__ == '__main__':
turtle_screen = turtle.Screen()
turtle_pen = turtle.Turtle()
turtle_pen.pencolor("black")
turtle.onscreenclick(draw_triangle, 1)
turtle.listen()
turtle.done()
|
3c5a50938743b21d3cc487dd60c260fdf0a99b9c | b1ueskydragon/PythonGround | /dailyOne/P07/P07.py | 1,255 | 3.515625 | 4 | # head to tail
def count_decode(msg):
if len(msg) == 0: # basic case: ""
return 1
count = 0
for i in [1, 2]:
if i > len(msg):
break
head = msg[:i]
tail = msg[i:]
if head.startswith('0') or int(head) > 26:
break
count += count_decode(tail)
return count
print(count_decode("111"))
print(count_decode("12345"))
print(count_decode("26"))
print(count_decode("27"), '\n')
# tail to head
def count_decode_later_parts(msg):
buff = [0 for i in range(len(msg) + 1)] # リスト内包記法
buff[len(msg)] = 1 # base case: ""
for i in reversed(range(len(msg))): # reverse the list: the recurrence depends on the later parts of the structure
for head_length in [1, 2]: # head: 元のリストの tail 該当部分を先に計算
if i + head_length > len(msg):
break
head = msg[i: i + head_length]
if head.startswith('0') or int(head) > 26:
break
buff[i] += buff[i + head_length]
return buff[0]
print(count_decode_later_parts("111"))
print(count_decode_later_parts("12345"))
print(count_decode_later_parts("26"))
print(count_decode_later_parts("27"), '\n')
|
0a562e417fbb930f538f5c878004052afc465424 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/d2bda618e6f24395a7e51cacc25b999c.py | 976 | 3.921875 | 4 | import datetime
import time
RECUR = {
'teenth': 0,
'1st' : 1,
'2nd' : 2,
'3rd' : 3,
'4th' : 4,
'last' : 5
}
def meetup_day(year, month, day, recur):
# Make Monday a one. Little easier to work with.
weekday_num = (time.strptime(day, '%A').tm_wday) + 1
# Get whatever day of the week the month starts with.
first_weekday = datetime.date(year, month, 1).weekday()
if weekday_num <= first_weekday:
mod = RECUR[recur] * 7
elif weekday_num > first_weekday:
mod = (RECUR[recur] - 1) * 7
offset = weekday_num - first_weekday
# Stolen from:
# http://www.wilsonzhao.com/blog/index.html
# Because I have no idea what the hell a 'teenth' is.
if recur == 'teenth':
if 14 + offset > 12 and 14 + offset < 20:
mod = 14
meetup_day = offset + mod
return datetime.date(year, month, meetup_day)
if __name__ == '__main__':
meetup_day(2013, 5, 'Tuesday', '1st')
|
db77105be2ffcd494b42e789740161a07ac5241a | GGMagenta/exerciciosMundo123 | /ex059.py | 1,191 | 4.125 | 4 | # Pegar 2 valores e mostrar o menu do que fazer com os valores
operacao = 0
v1 = float(input('Digite o primeiro valor: '))
v2 = float(input('Digite o segundo valor: '))
print("""Operações disponiveis:
[1]Somar
[2]Multiplicar
[3]Maior
[4]Novos números
[5]Sair""")
operacao = 0
while operacao != 5:
operacao = int(input('Selecione a operação: '))
if operacao == 1:
print('A soma entre {} e {} é igual a {}'.format(v1,v2,v1 + v2))
elif operacao == 2:
print('A multiplicação entre {} e {} é igual a {}'.format(v1, v2, v1 * v2))
elif operacao == 3:
if v1 > v2:
print('Entre {} e {} o maior é {}'.format(v1,v2,v1))
elif v2>v1:
print('Entre {} e {} o maior é {}'.format(v1, v2, v2))
else:
print('Os 2 números são iguais.')
elif operacao == 4:
print('Você escolheu selecionar novos números.')
v1 = float(input('Digite o primeiro valor: '))
v2 = float(input('Digite o segundo valor: '))
elif operacao == 5:
print('Você escolheu sair do programa.')
else:
print('Valor invalido.')
print('Programa finalizado.') |
1f4df65100174651359e1a852bc57e0863c31627 | Robert-Moringa/News | /app/news_source_test.py | 939 | 3.546875 | 4 | import unittest
from models import sources
Source = sources.Source
class SourcesTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Movie class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_source = Source('NTV','NTV News','The Covid 19 infections are on an alarming rise, be warned!','ntv.com','general')
def test_instance(self):
self.assertTrue(isinstance(self.new_source,Source))
def test_to_check_instance_variables(self):
self.assertEqual(self.new_source.id,'NTV')
self.assertEqual(self.new_source.name,'NTV News')
self.assertEqual(self.new_source.description,'The Covid 19 infections are on an alarming rise, be warned!')
self.assertEqual(self.new_source.url,'ntv.com')
self.assertEqual(self.new_source.category,'general')
if __name__ == '__main__':
unittest.main() |
1bb3174d31a99f65bb5101d6fbc913844ae98272 | pengliangs/python-learn | /基础语法/day2/10.字典遍历.py | 588 | 3.78125 | 4 | # 遍历字典
# keys() 返回字典所有key
user_info = {
"name":"张三",
"age":18,
"sex":"男"
}
for item in user_info.keys() :
print("key:",item,",value:",user_info[item])
print("--------------------------------------------------")
# values()
for item in user_info.values() :
print("value:",item)
print("--------------------------------------------------")
# items()
for item in user_info.items() :
print("item:",item)
print("--------------------------------------------------")
# items()
for k,v in user_info.items() :
print("key:",k,",value:",v) |
8fddd760595d9044ec3295d25821015c49f12ad4 | NineOnez/Python_Language | /14_Maximum.py | 1,477 | 4.34375 | 4 | # max or min:
findValue = input("What Do you to find (max or min)? : ")
# input 3 Numbers for find max or equal
a = float(input("Enter your number1 :"))
b = float(input("Enter your number2 :"))
c = float(input("Enter your number3 :"))
print()
if findValue == "max":
# algorithm max Value
if a > b:
if a > c:
print(": A is max")
elif a == c:
print(": AC are max")
else:
print(": C is max")
elif a > c:
if b > a:
print(": B is max")
elif a == b:
print(": AB are max")
else:
print(": A is max")
elif b == c:
if b == a:
print(": ABC are equal")
else:
print(": BC are max")
elif a < c:
if c > b:
print(": C is max")
else:
print(" B is max")
if findValue == "min":
# algorithm for min value
if a < b:
if a < c:
print(": A is min")
elif a == c:
print(": AC are min")
else:
print(": C is min")
elif a < c:
if b < a:
print(": B is min")
elif a == b:
print(": AB are min")
else:
print(": A is min")
elif b == c:
if b == a:
print(": ABC are equal")
else:
print(": BC are min")
elif a > c:
if c < b:
print(": C is min")
else:
print(": B is min")
|
95c52892d8d20a68b1cd0e4a6e9ed55514a723b4 | LongylG/python-try | /base/variable.py | 687 | 3.6875 | 4 | mount1 = 100 # 整数
mount2 = 100.0 # 浮点数
arr = [1, 2, 3] # 数组
arr2 = [[1, 2], [2, 3]] # 二维数组
map = {"a": "1", "b": 1, "c": "123"} # map
str1 = "hello word"
flag = True # 0-False 1-Ture,可与数字相加
print(mount1)
print(mount2)
print(arr[0])
print(arr2[0][0])
print(map["a"])
print(str1)
print(flag)
print(flag + 1)
# 输出类型
print(type(mount1))
print(type(mount2))
print(type(arr))
print(type(arr2))
print(type(str1))
print(type(map))
print(type(flag))
# 判断变量是否属于该类型
print(isinstance(flag,str))
# 变量类型转换
print(int(mount2))
print(str(mount2))
print(int(flag))
print(str(flag))
print(chr(flag))
print(chr(65))
|
219ff9a14542125656fbc6b413987fca489511ab | impramodp/FSDP2019 | /day17/bluegill.py | 1,762 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
bluegills.csv
How is the length of a bluegill fish related to its age?
In 1981, n = 78 bluegills were randomly sampled from Lake Mary in Minnesota. The researchers (Cook and Weisberg, 1999) measured and recorded the following data (Import bluegills.csv File)
Response variable(Dependent): length (in mm) of the fish
Potential Predictor (Independent Variable): age (in years) of the fish
How is the length of a bluegill fish best related to its age? (Linear/Quadratic nature?)
What is the length of a randomly selected five-year-old bluegill fish? Perform polynomial regression on the dataset.
NOTE: Observe that 80.1% of the variation in the length of bluegill fish is reduced by taking into account a quadratic function of the age of the fish.
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Importing the dataset
dataset = pd.read_csv('bluegills.Csv')
features = dataset.iloc[:,:1].values
labels = dataset.iloc[:, 1].values
dataset.plot(x='age', y='length', style='o')
plt.title('age vs length')
plt.xlabel('age')
plt.ylabel('length')
plt.show()
from sklearn.preprocessing import PolynomialFeatures
poly_object = PolynomialFeatures(degree = 5)
features_poly = poly_object.fit_transform(features)
from sklearn.linear_model import LinearRegression
lin_reg_2 = LinearRegression()
lin_reg_2.fit(features_poly, labels)
plt.scatter(features, labels, color = 'red')
plt.plot(features, lin_reg_2.predict(poly_object.fit_transform(features)), color = 'blue')
plt.title('Polynomial Regression')
plt.xlabel('age')
plt.ylabel('length')
plt.show()
print("Predicting result with Polynomial Regression for age=5")
print(lin_reg_2.predict(poly_object.transform(np.reshape(5,(1,-1)))))
|
1429b3e4953a90890f7f956b65c2bbb2906d4c49 | bupthl/Python | /Python从菜鸟到高手/chapter17/demo17.06.py | 1,691 | 3.8125 | 4 | '''
--------《Python从菜鸟到高手》源代码------------
欧瑞科技版权所有
作者:李宁
如有任何技术问题,请加QQ技术讨论群:264268059
或关注“极客起源”订阅号或“欧瑞科技”服务号或扫码关注订阅号和服务号,二维码在源代码根目录
如果QQ群已满,请访问https://geekori.com,在右侧查看最新的QQ群,同时可以扫码关注公众号
“欧瑞学院”是欧瑞科技旗下在线IT教育学院,包含大量IT前沿视频课程,
请访问http://geekori.com/edu或关注前面提到的订阅号和服务号,进入移动版的欧瑞学院
“极客题库”是欧瑞科技旗下在线题库,请扫描源代码根目录中的小程序码安装“极客题库”小程序
关于更多信息,请访问下面的页面
https://geekori.com/help/videocourse/readme.html
'''
import threading
from time import sleep, ctime
class MyThread(object):
def __init__(self, func, args):
self.func = func
self.args = args
def __call__(self):
self.func(*self.args)
def fun(index, sec):
print('开始执行', index, ' 时间:', ctime())
sleep(sec)
print('结束执行', index, '时间:', ctime())
def main():
print('执行开始时间:', ctime())
thread1 = threading.Thread(target = MyThread(fun,(10, 4)))
thread1.start()
thread2 = threading.Thread(target = MyThread(fun,(20, 2)))
thread2.start()
thread3 = threading.Thread(target = MyThread(fun,(30, 1)))
thread3.start()
thread1.join()
thread2.join()
thread3.join()
print('所有的线程函数已经执行完毕:', ctime())
if __name__ == '__main__':
main()
|
6321d6a6e5b0959b7eeb6cb431e8ba54cca255d7 | yajinwuzl/algorithm012 | /Week_08/reverse_bits.py | 681 | 3.765625 | 4 | """
python3.6
@author:ya-jin-wu
@license: Apache Licence
@file: reverse_bits.py
@time: 2020/08/30
@contact: yajinwu@163.com
@software: PyCharm
「『「『「☃」』」』」
"""
'''
190.颠倒二进制位
思路:位运算
'''
class Solution:
def reverseBits1(self, n):
ret, power = 0, 31
while n:
ret += (n & 1) << power
n = n >> 1
power -= 1
return ret
def reverseBits2(self, n: int) -> int:
return int(bin(n)[2::].zfill(32)[::-1], 2)
if __name__ == '__main__':
sol = Solution()
nums = 0o0000010100101000001111010011100
print(sol.reverseBits1(nums))
print(sol.reverseBits2(nums)) |
3dfb07da426ee318a25a4b223d85c7d44e232a0f | ananda-ch/python-practice | /exer1/str_rev.py | 216 | 4.0625 | 4 | import sys
def reverse_string(arg):
result = ''
for s in range(len(arg)):
result = result + arg[len(arg) - (s + 1)]
return result
str_input = sys.argv[1]
print reverse_string(str_input) |
ce77e4e8128b7fafc7f6487045c73b193eae8aeb | AllenLiuX/Aitai-Bill-Analysis-with-NN | /Liushui/Modules/sqlite3.py | 2,017 | 3.546875 | 4 | import sqlite3
import pymysql
class Database():
def __init__(self, db):
self.conn = sqlite3.connect(db)
# self.conn = pymysql.connect(host='rm-uf6z3yjw3719s70sbuo.mysql.rds.aliyuncs.com', user='bank_dev', password='072EeAb717e269bF',
# db='bank_dev')
self.cursor = self.conn.cursor()
def drop_table(self, table):
print(table, 'table is deleted.')
sql = 'DROP TABLE ' + table
self.cursor.execute(sql)
self.conn.commit()
def show_table(self, table):
sql = 'select * from ' + table
self.cursor.execute(sql)
res = self.cursor.fetchall()
# print(res)
return res
def close_db(self):
self.conn.close()
def create(self, table, cols):
self.cursor.execute("select name from sqlite_master where type='table' order by name")
table_lists = self.cursor.fetchall()
if len(table_lists)>0:
print(table_lists)
if table in table_lists[0]:
print('table already exist. skip create.')
return
sql = 'CREATE TABLE ' + table + ' ('
for c in cols:
sql += c + ', '
sql = sql[:-2]
sql += ')'
print(sql)
self.cursor.execute(sql)
self.conn.commit()
def insert(self, table, vals, cols=[]):
sql = 'INSERT INTO '+table
if cols:
sql += '('
for c in cols:
sql += c+', '
sql = sql[:-1]
sql += ')'
sql += ' VALUES ('
for v in vals:
sql += v+', '
sql = sql[:-2]
sql += ')'
print(sql)
self.cursor.execute(sql)
self.conn.commit()
if __name__ == '__main__':
db = Database('test1.db')
# db.drop_table('REPORTS')
db.create('REPORTS', ['BEGIN_DATE TEXT', 'END_DATE TEXT'])
db.insert('REPORTS', ['20000101', '20000103'])
res = db.show_table('reports')
print(res)
db.close_db()
|
0d1b6426c030b7e651cdb2c758132548ae69561f | sarari0318/leetcode | /Others/str_ro_int_60.py | 1,212 | 3.515625 | 4 | MAPPING = {
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"0": 0,
}
MAX_INT = 2**31-1
MIN_INT = -(2**31)
class Solution:
def myAtoi(self, string):
'''
Parameters
----------
string: str
'string' consists of English letters (lower-case and upper-case),
digits (0-9), ' ', '+', '-', and '.'.
Returns
-------
int
⇨ return the number included in string as integer.
'''
# stringの無駄なスペースを削除
s = string.lstrip(' ')
if not s:
return 0
# 正負を判別する変数
sign = -1 if s[0] == "-" else 1
if sign != 1 or s[0] == "+":
s = s[1:]
res = 0
for char in s:
if char not in MAPPING:
return self.limit(res * sign)
# 次の桁へ
res *= 10
res += MAPPING[char]
return self.limit(res * sign)
def limit(self, x: int) -> int:
if x > MAX_INT:
return MAX_INT
if x < MIN_INT:
return MIN_INT
return x |
091ab3d05148fb2fec18dcf49188643100388f66 | Auralcat/100-days-of-code | /scripts/hangman.py | 1,991 | 4.25 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Importing the time module
import time
# Welcoming the user
name = input("What's your name? >>")
print("Hello, " + name + ", time to play hangman! ✊")
# Adding some ASCII art!
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
# Here we set the target word
word = "secret"
# Turn limit
turns = 10
current_word = "-" * len(word)
fail_limit = 6
fails = 0
while turns > 0:
turns -= 1
print(HANGMANPICS[fails - fail_limit - 1] + '\n')
print(current_word)
guess = input("Type a character: ")
# Find the characters in the target string and count them
if (word.count(guess) >= 1):
char_index_arr = [pos for pos, char in enumerate(word) if char == guess]
# This is how you split a string into a letter array
current_arr = list(current_word)
# print(current_arr)
# Add the correct guesses to the displayed string
for index in char_index_arr:
current_arr[index] = guess
current_word = ''.join(current_arr)
else:
fails += 1
print("Whoops, that letter isn't in the word! You got " + str(fail_limit - fails) + " more tries.")
if (current_word == word):
print("Congratulations, you found the secret word in " + str(turns) + " turns!")
break
if (fails == fail_limit):
print("Aww, you don't have any more tries. Sorry, you lose.")
break
print("Game is over.")
|
3e0937ab5ce3677e485647eccb65156780ec910b | vmontich/curso-de-python | /pythonexercicios/ex082.py | 435 | 3.71875 | 4 | lista = []
lista_par = []
lista_impar = []
opcao = "S"
while opcao.upper() == "S":
num = int(input("Digite um número inteiro: "))
lista.append(num)
if num % 2 == 0:
lista_par.append(num)
else:
lista_impar.append(num)
opcao = input("Deseja continuar? [S / N] ")
print(f"Lista principal: {lista}")
print(f"Lista de números pares: {lista_par}")
print(f"Lista de números ímpares: {lista_impar}")
|
c60c963abb5d17fdba3a664b720019e2f16b2982 | Jinx-Heniux/Python-2 | /maths/fibonacci_recursion.py | 503 | 4.125 | 4 | def fibonacci(number: int) -> int:
"""
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(3)
2
>>> fibonacci(4)
3
>>> fibonacci(5)
5
>>> fibonacci(6)
8
>>> fibonacci(7)
13
>>> fibonacci(8)
21
"""
return (
number
if number == 0 or number == 1
else fibonacci(number - 1) + fibonacci(number - 2)
)
if __name__ == "__main__":
from doctest import testmod
testmod()
|
90ce868ad03793c77e4c813caee6091f088ff751 | yubo-yue/yubo-python | /Intro.to.Prog.Using.Python/ComputeArea.py | 135 | 3.84375 | 4 | #!/usr/bin/python3.4
radius = 20
area = radius * radius * 3.14159
print("The area for the circle of radius ", radius, " is ", area)
|
6717d0651d47bc0a9893865bc102225835053721 | VeryOrange/Yahtzee-Upper-Section-Scoring | /yahtzee.py | 585 | 4 | 4 | #!/usr/bin/env python3
#This code returns the greatest possible score from a yahtzee roll
def yahtzee_upper(a):
great = 0
#Determines the maximum possible score of given roll
a = list(map(int,a))
for i in range(len(a)):
if(a[i]>great):
great = a[i]
elif (a[i] == a[i-1]):
great += a[i]
return great
def main():
print("Give me your yahtzee roll!")
a = input()
lis = a.split(" ")
if(len(lis) != 5):
print("Invalid yahtzee roll.")
main()
ret = yahtzee_upper(lis)
print(ret)
main()
|
5362e19128cca3be957d80f6dfbb395855f96656 | vasu-kukkapalli/python_git | /python_session_trilochan/prog_Continue.py | 345 | 3.828125 | 4 | #break...!
for number in range(10):
if number ==7:
break
print(number)
#continue...!
for number in range(10):
if number ==7:
continue
print(number)
#break
l1 = [5,10,15,20]
l2 = [10,20,30]
for i in l1:
for j in l2:
if j == 20:
break
print(i*j)
print('this is a nested loop')
|
cacb0d8c3a1d42489287d33be2b78ac30c1b20bf | SandeshDhawan/PythonPrograms | /If_Else_Program/PositiveNegativeNumbers.py | 278 | 3.875 | 4 | class PositiveNegativeNumber:
def checkNumber(self, n):
if n < 0:
print(n, " is a Negative Number")
else:
print(n, " is a Positive Number")
number = int(input("Enter Any Number"))
ob = PositiveNegativeNumber()
ob.checkNumber(number) |
8b0597b1bed02bcd2c781a6743145e2737ec6bec | estewart1/Python | /summy.py | 169 | 3.984375 | 4 | def summy(string_of_ints):
return sum(int(n) for n in string_of_ints.split())
strofints = (" 1 2 3 ")
print summy(strofints)
#Codewars
#Find sum of numbers in a list |
20ff3da1fb75db14ad85e66c56586e059f69173c | JanithDeSilva/hacktoberfest_2021 | /sumOfDigits.py | 102 | 3.640625 | 4 | def getSum(n):
sum = 0
for digit in str(n):
sum += int(digit)
return sum |
540aa19c777fb0829760630f807ef9bb06645568 | eman19-meet/YL1-201718 | /my_project/myProject.py | 1,697 | 3.75 | 4 | import turtle
import time
import random
from ball.py import Ball
class Ball(Turtle):
def __init__(self,x,y,dx,dy,r,color):
Turtle.__init__(self)
self.penup()
self.setpos(x,y)
self.dx=dx
self.dy=dy
self.r=r
self.shape("circle")
self.shapesize(r/10)
self.color(color)
def move(self,screen_width,screen_height):
self.current_x=self.xcor()
self.new_x=self.current_x+dx
self.current_y=self.ycor()
self.new_y=self.current_y+dy
self.right_side_ball=new_x+r
self.left_side_ball=new_x-r
self.up_side_ball=new_y+r
self.down_side_ball=new_y-r
self.goto(new_x,new_y)
if right_side_ball > -screen_width/2:
self.goto(new_x - self.dx , new_y)
if left_side_ball < -screen_width/2:
self.goto(new_x + self.dx , new_y)
if up_side_ball > -screen_height/2:
self.goto(new_x , new_y - self.dy)
if down_side_ball < -screen_height/2:
self.goto(new_x , new_y + self.dy)
turtle.tracer(0)
turtle.hideturtle()
RUNNING=True
SLEEP=0.0077
SCREEN_WIDTH=turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT=turtle.getcanvas().winfo_height()/2
MY_BALL=Ball(0,0,3,3,10,"blue")
NUMBER_OF_BALLS=5
MINIMUM_BALL_RADIUS=10
MAXIMUM_BALL_RADIUS=100
MINIMUM_BALL_DX=-5
MINIMUM_BALL_DY=-5
MAXIMUM_BALL_DY=5
MAXIMUM_BALL_DX=5
BALLS=[]
for i in range(NUMBER_OF_BALLS):
x=random.randint(-SCREEN_WIDTH + MAXIMUM_BALL_RADIUS , SCREEN_WIDTH - MAXIMUM_BALL_RADIUS)
y=random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS , SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS)
dx=random.randint(MINIMUM_BALL_DX , MAXIMUM_BALL_DX)
dy=random.randint(MINIMUM_BALL_DY , MAXIMUM_BALL_DY)
radius=random.randint(MINIMUM_BALL_RADIUS , MAXIMUM_BALL_RADIUS)
color=random.randint(random.random(),random.randint())
|
1ba80673cd1a4df7a56519f52c13ef81bc78aeb0 | Kipngetich33/password-locker | /user_test.py | 3,539 | 3.640625 | 4 | import pyperclip
import unittest # this line imports the unittest module
from user import User # this lines imports the class User from user.py
class TestUser(unittest.TestCase):
'''
Test class that defines the test cases for the user
class behaviours
Args:
unnitest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(self):
'''
this is the set up method that should run before each test case
'''
self.new_user= User("Vincent","Empharse")
def tearDown(self):
'''
cleans up after each test case has run
'''
User.list_of_users=[]
def test_init(self):
'''
this function tests an a user object is properly initialized
'''
self.assertEqual(self.new_user.name,"Vincent")
self.assertEqual(self.new_user.password,"Empharse")
def test_save_user(self):
'''
this function tests the save function appends
a new user object to the contact list'''
self.new_user.save_user()# this line calls the save user contact from user.py
self.assertEqual(len(User.list_of_users),1)
def test_save_multiple_contacts(self):
'''
this function tests if the application can save multiple contats
'''
self.new_user.save_user()# this line calls the save user contact from user.py
test_user= User("test_user","test_user_password")
test_user.save_user()# this line save the user test_user to the list_of_users
self.assertEqual(len(User.list_of_users),2)
def test_delete_user(self):
'''
determines whether the app can delete a user from the list of users
'''
self.new_user.save_user()
test_user= User("test_user","test_user_password")
test_user.save_user()# this line save the user test_user to the list_of_users
self.new_user.delete_user()# this lines deletes the user
self.assertEqual(len(User.list_of_users),1)
def test_find_user_by_name(self):
'''
test the function find_user_by_name from user.py
if it can find by a user with the name and return the user
'''
self.new_user.save_user()
test_user= User("test_user","test_user_password")
test_user.save_user()# this line save the user test_user to the list_of_users
found_by_name = User.find_user_by_name("test_user")
self.assertEqual(found_by_name.password,test_user.password)
def test_user_exists(self):
'''
test whether a user actually exists by calling a method
user_exist in user.py
'''
self.new_user.save_user()
test_user= User("test_user","test_user_password")
test_user.save_user()# this line save the user test_user to the list_of_users
user_exist= User.user_exists("test_user")
self.assertTrue(user_exist)
def test_display_all_users(self):
'''
test that determines whether the function
display_all_users can accurately display all users
'''
self.assertEqual(User.display_all_users(),User.list_of_users)
def test_copy_found_password(self):
'''
tests whether the copy_name_found_user can can find and copy the
password of a found user
'''
self.new_user.save_user()
User.copy_found_password("Vincent")
self.assertEqual(self.new_user.password,pyperclip.paste())
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.