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 |
|---|---|---|---|---|---|---|
9c8f4cfc063f8eac099d4e666fb060a514d0781f | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/gbrpri001/question2.py | 438 | 4.09375 | 4 | """PRIYANKA GOBERDHAN
QUESTION TWO
08/05/14"""
count=0
def string_count(word):
global count
if word == '':
return count
else:
if(len(word) > 1 and word[0] == word[1]):
count = count + 1
return string_count(word[2:len(word)])
else:
return string_count(word[1:len(word)])
x=input("Enter a message:\n")
print("Number of pairs:", string_count(x)) |
07094a7fc43f88aba275bd3d89ffbdde7d67990c | MarcosRios1/GuessingGame | /GuessingGame.py | 1,307 | 4.25 | 4 | import random
guess = 3
def guessing_game():
input("Let's play the guessing game! I'm going to ask you to select a range to guess between.\n\
Press any key to start! ")
min_ = input("What's the beginning number of the range? ")
max_ = input("What's the max number of the range? ")
global guess_num
guess_num = range(int(min_), int(max_))
guess_num = random.choice(guess_num)
while(guess):
g1 = input("You've got {} tries! What's your guess? \n" .format(guess))
check_guess(int(g1))
def check_guess(x):
global guess
if x == guess_num:
print("You won!! Nice job")
guess = 0
elif x > guess_num:
guess -= 1
if(guess):
print("Too high! Try again, you have {} guesses remaining" .format(guess))
else: check_loss()
else:
guess -= 1
if(guess):
print("Too low! Try again, you have {} guesses remaining" .format(guess))
else: check_loss()
def check_loss():
global guess
if guess == 0:
play = input('You lost! Sorry :( Press L if you want to play again, or anything else to quit! ')
if play == 'L' or play == 'l':
guess = 3
guessing_game()
guessing_game()
|
1b7c7c99b6ee34bec5c3f951987d38cc0d5d93b7 | Built00/Leetcode | /Target_Sum.py | 3,421 | 4.3125 | 4 | # -*- encoding:utf-8 -*-
# __author__=='Gan'
# You are given a list of non-negative integers, a1, a2, ..., an,
# and a target, S. Now you have 2 symbols + and -. For each integer,
# you should choose one from + and - as its new symbol.
# Find out how many ways to assign symbols to make sum of integers equal to target S.
# Example 1:
# Input: nums is [1, 1, 1, 1, 1], S is 3.
# Output: 5
# Explanation:
# -1+1+1+1+1 = 3
# +1-1+1+1+1 = 3
# +1+1-1+1+1 = 3
# +1+1+1-1+1 = 3
# +1+1+1+1-1 = 3
# There are 5 ways to assign symbols to make the sum of nums be target 3.
# TLE
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
def search(index, cur_sum, res = 0):
if index == len(nums):
if S == cur_sum:
res += 1
return res
return search(index + 1, cur_sum + nums[index]) + search(index + 1, cur_sum - nums[index])
res = search(0, 0)
return res
# 139 / 139 test cases passed.
# Status: Accepted
# Runtime: 118 ms
# Your runtime beats 84.89 % of python submissions.
import collections
# This solution can also replace defaultdict with list.
# res_list = [0] * (target + 1)
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
sum_ = sum(nums)
if sum_ < S or (sum_ + S) % 2:
return 0
target = (sum_ + S) // 2
res_dic = collections.defaultdict(int)
res_dic[0] = 1
for num in nums:
for i in range(target, num - 1, -1):
if i - num in res_dic:
res_dic[i] += res_dic[i-num]
return res_dic[target]
# 139 / 139 test cases passed.
# Status: Accepted
# Runtime: 72 ms
# Your runtime beats 99.75 % of python submissions.
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
sum_ = sum(nums)
if sum_ < S or (sum_ + S) % 2:
return 0
target = (sum_ - S) // 2
res_list = [0] * (target + 1)
res_list[0] = 1
for num in nums:
for i in range(target, num-1, -1):
# if i - num in res_list: Do not need to judge.
res_list[i] += res_list[i - num]
return res_list[target]
# 139 / 139 test cases passed.
# Status: Accepted
# Runtime: 316 ms
# Your runtime beats 58.47 % of python submissions.
class Solution(object):
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
sum_ = sum(nums)
if sum_ < S or (sum_ + S) % 2:
return 0
res_dict = {nums[0]: 1, -nums[0]: 1} if nums[0] else {0:2}
for num in nums[1:]:
dummy_dict = {}
for d in res_dict:
dummy_dict[d-num] = dummy_dict.get(d-num, 0) + res_dict.get(d, 0)
dummy_dict[d+num] = dummy_dict.get(d+num, 0) + res_dict.get(d, 0)
res_dict = dummy_dict
return res_dict[S]
if __name__ == '__main__':
print(Solution().findTargetSumWays([1, 1, 1, 1, 1], 3))
print(Solution().findTargetSumWays([1,2,7,9,981], 1000000000))
|
ef13e0688688b1590ad1e636890f83239d3598ee | shingyipcheung/study-path-backend | /edxDB/permutations_brutal_pruning.py | 2,648 | 3.78125 | 4 | # permutation example by Luc
def find_node_set(dictionary):
'''
**goal**: find the set of:
1. all nodes
2. all nodes that is some others' parent
3. all nodes that is some others' child
:param dictionary: dictionary of edges, parent -> list of children
'''
from itertools import chain
all_parents = set(dictionary.keys())
all_children = set(chain(*[v for v in dictionary.values()]))
all_nodes = all_parents | all_children
return all_nodes, all_parents, all_children
def create_dependency_map_with_index(dictionary, all_nodes):
'''
**goal**: convert nodes with string names into integer indices
:param dictionary: dictionary of edges, parent -> list of children
:param all_nodes: set of all nodes
'''
node_cnt = len(all_nodes)
import numpy as np
node2ind = {n: i for i, n in enumerate(all_nodes)}
indmap = np.zeros((node_cnt, node_cnt))
# map: row=parent, col=child
for p in all_nodes:
if p in dictionary:
for c in dictionary[p]:
indmap[node2ind[p], node2ind[c]] = 1
return node2ind, indmap
# === brutal pruning ===
def permutation(all_nodes:set, node2ind, indmap):
visited = []
unvisited = set((node2ind[n] for n in all_nodes)) # create set of unvisited indices
all_possible = []
def _step():
nonlocal unvisited, visited, all_possible, indmap
if not unvisited:
# if unvisited is empty, then this is a legal permutation
all_possible.append(tuple(visited))
return
for i in unvisited:
# check if valid
for j in visited:
# if j->i, i.e. indmap[j,i] != 0, then illegal
if indmap[j,i] != 0:
return
# put into visited, visit next position
visited.append(i)
unvisited.remove(i)
_step()
# remove from visited
del visited[-1]
unvisited.add(i)
_step()
return all_possible
CONCEPT_EDGES = {
"primitive_type": ["operator", "array", "variable"],
"operator": ["branch"],
"branch": ["loop"],
"array": ["nd_array", "string"],
"variable": ["array", "instance_variable"],
"object_class": ["instance_variable", "method"],
"instance_variable": ["method"],
"method": ["recursion"]
}
all_nodes, all_parents, all_children = find_node_set(CONCEPT_EDGES)
node_cnt = len(all_nodes)
node2ind, indmap = create_dependency_map_with_index(CONCEPT_EDGES, all_nodes)
ret = permutation(all_nodes, node2ind, indmap)
print(len(ret))
|
b5bf52bd7af17042aa158d3d9a03584706ea39cf | Jesta398/project | /while loop/even number(lower-upper.py | 157 | 4 | 4 | lower=int(input("enter the lower limit:"))
upper=int(input("enter the upper limit:"))
while(lower<=upper):
if(lower%2==0):
print(lower)
lower+=1
|
28f1bb4b2d19ce7579bddb3872a0f02376755cce | zksheikh/Hangman | /main.py | 911 | 3.90625 | 4 | import random
a = ["dog", "mouse", "cat"]
word = random.choice(a)
print(len(word))
count = 0
#Lives in the game
lives = 6
#location of the character in the word
location = 0
used = ""
def new_guess(guess):
global count
global lives
global location
global used
if guess not in used:
used += guess
if guess in word:
for n in word:
if n == guess:
count += 1
else:
print("Try Again")
lives -= 1
else:
print("You tried this letter already")
# Keep playing
while len(word) > count and lives > 0:
answer = ""
for letter in word:
if letter in used:
answer += letter
else:
answer += "_"
print(answer)
letter = input("Enter a letter: ")
new_guess(letter)
if lives == 0:
print("Loser")
else:
print("You are a winner!") |
9611399328bd7973d5b77106a1bbd8584cc79b7e | OmarMontero/150-challenges-for-python | /eighty-two.py | 434 | 3.78125 | 4 |
def main():
sentence = "No es verdad ángel de amor, que en aquella apartada orilla, si tu novio nos pilla, las hostias me las llevo yo?."
limit = len(sentence)
print(sentence)
low_limit = int(input(f"Type in the low limit(between 0 and {limit}): "))
top = int(input(f"Type in the high limit(between 0 and {limit}): "))
print(sentence[low_limit:top])
if __name__ == '__main__':
main() |
71b3eed6fe39e359f5ec20b1d015aa35d7be5b18 | allenwhc/Algorithm | /Company/Microsoft/ReverseWordsString(M).py | 674 | 3.8125 | 4 | class Solution(object):
"""
String reverse solution
Time complexity: O(nk), n is length of s, k is average length of each word
Extra space: O(1)
"""
def reverseWords(self, s):
"""
:type s: a list of 1 length strings (List[str])
:rtype: nothing
"""
if not len(s): return
s.reverse()
start,n=0,len(s)
def reverseS(s,start,end):
if 0<=start<end<len(s):
c=s[start]
s[start]=s[end]
s[end]=c
reverseS(s,start+1,end-1)
for i in range(n):
if i==n-1:
reverseS(s,start,i)
if s[i]==' ':
reverseS(s,start,i-1)
start=i+1
s=['h','e','l','l','o',' ','w','o','r','l','d']
print s
sol=Solution()
sol.reverseWords(s)
print s
|
a255422f6fb1c26902741b59bce5636a1a357b94 | codeBeefFly/bxg_python_basic | /Day08/21.多态.py | 1,427 | 3.65625 | 4 | '''---------------------- 父类 ----------------------'''
class Human:
def eat(self):
print('人类吃饭')
'''---------------------- 中国人 ----------------------'''
class ZhHuman(Human):
def eat(self):
print('用筷子吃饭')
'''---------------------- 美国人 ----------------------'''
class USHuman(Human):
def eat(self):
print('用刀叉吃饭')
'''---------------------- 非洲人 ----------------------'''
class AfricaHuman(Human):
def eat(self):
print('用手抓恩希玛')
'''---------------------- 狗 ----------------------'''
class Dog:
def eat(self):
print('狗啃骨头')
'''---------------------- 函数 ----------------------'''
# java c++静态类型语言 可以确定参数类型 Human
# python只要具备eat功能对象,都可以传递进去
def translate(human):
'''
传递一个具备吃饭功能的Human对象
:param human: Human对象
:return:
'''
human.eat()
# human.makeMoney()
# 创建对象
# human = Human()
zhHuman = ZhHuman()
usHuman = USHuman()
afHuman = AfricaHuman()
# 调用函数
# translate(human)
# translate(zhHuman)
# translate(usHuman)
# translate(afHuman)
'''---------------------- 鸭子模型 ----------------------'''
# 创建Dog对象
dog = Dog()
translate(dog)
# translate(40)
# 动物:叫起来 像鸭子 跳起来像鸭子
# python认为是一个鸭子
# int a = 10
# a = 10 |
f189a2dedc078bdb6e3f13a1f2bc3797df2ac944 | shifty049/LeetCode_Practice | /Medium/1609. Even Odd Tree.py | 1,910 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isEvenOddTree(self, root: TreeNode) -> bool:
queue = [root]
lst = []
level = 0
while queue:
lst.append([])
new_queue = []
for node in queue:
if not lst[level]:
if level%2:
if not node.val%2:
lst[level].append(node.val)
else:
return False
else:
if node.val%2:
lst[level].append(node.val)
else:
return False
else:
if level%2:
if not node.val%2 and node.val < lst[level][-1]:
lst[level].append(node.val)
else:
return False
else:
if node.val%2 and node.val > lst[level][-1]:
lst[level].append(node.val)
else:
return False
if node.left:
new_queue.append(node.left)
if node.right:
new_queue.append(node.right)
queue = new_queue
level+=1
return True
#Runtime: 504 ms, faster than 67.39% of Python3 online submissions for Even Odd Tree.
#Memory Usage: 45.9 MB, less than 30.78% of Python3 online submissions for Even Odd Tree.
#Fu-Ti, Hsu
#shifty049@gmail.com |
0da63ab02aa037dd36ddf85c2fd41a662a3093f5 | ztaylor2/data-structures | /src/radixsort.py | 1,704 | 3.96875 | 4 | """Radix sort."""
from collections import OrderedDict
from que_ import Queue
def stringify_nums(nums_list):
"""."""
stringified_nums = []
for num in nums_list:
stringified_nums.append(str(num))
return stringified_nums
def while_condition(string_unsorted_list):
"""."""
num_lengths = []
for num in string_unsorted_list:
num_lengths.append(len(num))
return max(num_lengths)
def unravel_buckets(bucket_dict):
"""."""
unraveled_nums = []
for bucket in bucket_dict:
while bucket_dict[bucket].peek():
unraveled_nums.append(bucket_dict[bucket].dequeue())
return unraveled_nums
def push_into_buckets(stringified_nums, i, buckets_dict):
"""."""
for num in stringified_nums:
try:
buckets_dict[num[-i]].enqueue(num)
except IndexError:
buckets_dict['none'].enqueue(num)
return buckets_dict
def radixsort(unsorted_list):
"""."""
if len(unsorted_list) == 0:
return unsorted_list
stringified_nums = stringify_nums(unsorted_list)
while_condition_int = while_condition(stringified_nums)
buckets_dict = OrderedDict({
'none': Queue(),
'0': Queue(),
'1': Queue(),
'2': Queue(),
'3': Queue(),
'4': Queue(),
'5': Queue(),
'6': Queue(),
'7': Queue(),
'8': Queue(),
'9': Queue(),
})
i = 0
while i <= while_condition_int:
buckets_dict = push_into_buckets(stringified_nums, i, buckets_dict)
stringified_nums = unravel_buckets(buckets_dict)
i += 1
numified_nums = [int(x) for x in stringified_nums]
return numified_nums
|
46d98ee77939b7203096a2eafabf627506f3ae9d | bgmacris/100daysOfCode | /Day81/funciones.py | 1,221 | 3.8125 | 4 | def f_len(word):
count = 0
for i in word:
count += 1
return count
def f_split(text_string, delimiter):
lista = []
word = ''
for char in text_string:
if char == delimiter:
lista.append(word)
word = ''
else:
word = word + char
if word != '': lista.append(word)
return lista
def f_sort(num_list):
for num in range(1, len(num_list)):
cur_val = num_list[num]
pos = num
while pos > 0 and num_list[pos-1] > cur_val:
num_list[pos] = num_list[pos-1]
pos = pos - 1
num_list[pos] = cur_val
return num_list
def f_join(list_string, delimiter):
text_string = ''
for string in list_string:
text_string = text_string + string + delimiter
return text_string[:-1]
def f_sum(int_string):
total = 0
for i in int_string:
total = total + i
return total
def f_max(int_string):
return f_sort(int_string)[-1]
def f_min(int_string):
return f_sort(int_string)[0]
print(f_len('word'))
print(f_split('hola, mundo', ','))
print(f_join(['hola', 'mundo'], '-'))
print(f_sum([1, 2, 3]))
print(f_max([3, 5, 1, 2]))
print(f_min([3, 5, 1, 2]))
|
4e4cc4cd2eba56f4571a6a863d1ac182dee2b6e8 | jaredStevens/python-exercises | /Python1/guess_the_number2.py | 387 | 3.984375 | 4 | secret_number = 5
print('I am thinking of a number between 1 and 10.')
while True:
guess = int(input("What's the number? "))
if guess == secret_number:
print('Yes! You win!')
break
elif guess > secret_number:
print('Too high. Try again.')
elif guess < secret_number:
print('Too low. Try again.')
else:
print('Nope, try again.') |
b43caedc24f8451afa6473a2eb66b1e17a1b7121 | kesihain/python-challenges | /error_fixing.py | 1,822 | 4.28125 | 4 | # Run the code. Read the error message.
# Fix it
# def mean(numbers):
# print(type(numbers))
# total = sum(numbers)
# return total / len(numbers)
# print(mean([5, 3, 6, 10]))
# Define a method called user_details that takes in two arguments
# def user_details(name, occupation):
# return f"Hi! My name is {name} and I am a {occupation}."
# ######
# # Call the method
# user_name = "Glo"
# user_occupation = "Lecturer"
# print(user_details(user_name, user_occupation))
# # 1. Write the error message here:
# # 2. Fix the code so that it works.
# Define a method called apple_price which takes in one argument
# def apple_price(num_of_apples):
# return num_of_apples * 1.00
# ###############
# # Call the method
# # What's wrong with the following code?
# print(apple_price(10))
# # 1. Write down the error message here
# # 2. Fix the code so that it works.
# Define a method called "run" that does not take in any arguments
# but prints out "This is the method 'run' and it did not take in any arguments!"
# def run():
# return f"This is the method 'run' and it did not take in any arguments!"
# ############################
# # Call the method
# print(run())
# Step 1: Determine the number of male adults to determine the number of couples
# couples equal 0.4*pop
# Number of male adults equals to number of couples
def adult_male_population(n):
return n * 4/10
# Each couples will have 10 babies
def total_babies(n):
return adult_male_population(n) * 10
# Step 2: Determine the number of adult females and baby females and add them up
def adult_female_population(n):
return n * 6/10
def total_female(n):
female_adults = adult_female_population(n)
female_babies = total_babies(n) * 6/10
return (female_adults + female_babies)
print(total_female(1600)) |
fee1b7356114c8a9b20a76f03f9894d4269ae52f | gabrodhic/MOOCdb | /modeling_ps/analytics/generate_attempt_resource_use.py | 8,863 | 3.578125 | 4 | """
Created on: 2/1/2014
Author: Elaine Han (skewlight@gmail.com)
From problem csv files, generate resource distribution
after each answer attempt (first, second ...) for all users
1. list top resource consulted after each attempt ordered by count/percentatge
2. plot/save historgram of the distribution with
a) normal or log scale count
b) ordered by resource_id or count
"""
import csv
import os
import pylab as pl
import math
#CSV_FOLDER_PATH = "problem_csv_ORIGINAL_sample/" #old csv files
CSV_FOLDER_PATH = "problem_csv_v2/" #new csv files
# change the constants accordingly for different csv formats
USER_INDEX = 0
ANSWER_INDEX = -1
RESOURCE_INDEX = 2
FILE_NAME = "problem_%i_v2.csv"
EMPTY_ANSWER = 0
CORRECT_ANSWER = 1
def correct_attempt_stats_from_csv(problem_id,attempt_limit=5):
####################################
######### from csv files ###########
####################################
filename = os.path.join(CSV_FOLDER_PATH, FILE_NAME%problem_id)
with open(filename,'r') as csvfile:
reader = csv.reader(csvfile)
user_count = 0 #total user count for this problem
user_id = None #user id we looking at
attempt_number = 0 #which attempt we are on
user_correct = 0 # 0=incorrect, 1=correct, 2=correct to incorrect for current user
attempt_dict = {} #store correct attempt stats
correct_to_in = 0 #incorrect after correct
correct_after_c = 0 # correct after correct
resource_use_list = [{} for i in range(attempt_limit)] #list of dictionary counting resource use
# for each attempt
unique_resources = []
for row in reader:
if float(row[ANSWER_INDEX]) != EMPTY_ANSWER: # is a submission event
row_user_id = int(row[USER_INDEX])
#re-initialize for every new user
if user_id != row_user_id:
user_id = row_user_id
attempt_number = 0
user_correct = 0
user_count += 1
attempt_number += 1
# first correct attempt
if float(row[ANSWER_INDEX]) == CORRECT_ANSWER and user_correct == 0 :
if attempt_number in attempt_dict:
attempt_dict[attempt_number] += 1
else:
attempt_dict[attempt_number] = 1
user_correct = 1
# user submitting incorrect attempt(s) after correct, count once for same user
elif float(row[ANSWER_INDEX]) != CORRECT_ANSWER and user_correct == 1:
correct_to_in += 1
user_correct = 2
# user submitting correct attempt(s) after correct, count once for same user
elif float(row[ANSWER_INDEX]) == CORRECT_ANSWER and user_correct == 1:
correct_after_c += 1
else: #resource event
#should not have user change or attempt change
resource_id = int(row[RESOURCE_INDEX])
#keep track a unique list of resources
if resource_id not in unique_resources:
unique_resources.append(resource_id)
if attempt_number <= attempt_limit:
if resource_id not in resource_use_list[attempt_number-1]:
resource_use_list[attempt_number-1][resource_id] = 1
else:
resource_use_list[attempt_number-1][resource_id] += 1
unique_resources.sort()
return (attempt_dict,correct_to_in,correct_after_c,user_count,resource_use_list,unique_resources)
def topValue(d,top=10,percentage=True,time=False):
"""
Sorting a dictionary by key and print out top values in readable format
"""
resList = []
countList = []
total = sum(d.values())
if time:
total /= 3600.0
l=[(v,k) for k,v in d.iteritems() ]
l.sort(reverse=True)
print "Unique resources %6i, total visits %6i"%(len(l),total)
idList = []
valueList = []
#print the results in formatted string
res = 0
top = min(top,len(l))
while res < top:
idString = "" #resource id
cString = "" #count or percentage
for i in range(10):
#string += "%s |"%l[ans][1]
idList.append(l[res][1])
idString += "%6i |"%(l[res][1])
if percentage:
cString += "%5.2f%% |"%(l[res][0]/float(total)*100)
valueList.append("%5.2f%% |"%(l[res][0]/float(total)*100))
else:
cString += "%6i |"%(l[res][0])
valueList.append("%6i |"%(l[res][0]))
res += 1
if res == top:
print idString
print cString
print ""
return idList,valueList
print idString
print cString
print ""
def create_bins(use,unique,log=False,ordered=False):
"""
from count dictionary, create bins used for plotting histograms
"""
# use = resource_use dictionaries, key: resource_id, value : count
# unique = list of unique resources, not all might have appeared in use
if ordered:
bins = []
labels = []
l=[(v,k) for k,v in use.iteritems()]
l.sort(reverse=True)
for (v,k) in l:
if log:
bins.append(math.log(v))
else:
bins.append(v)
labels.append(k)
for k in unique:
if k not in labels:
bins.append(0)
labels.append(k)
return bins,labels
else:
bins = [0]*len(unique)
for i in range(len(unique)):
if unique[i] in use:
if log:
bins[i] = math.log(use[unique[i]])
else:
bins[i] = use[unique[i]]
return bins,unique
if __name__ == "__main__":
problem_list = [330]
attempt_limit = 8
show_resource = 10
log = True
ordered = True
saveToFig = False
for problem in problem_list:
print "Problem ID: %i\n"%problem
(attempt_dict,correct_to_in,correct_after_c,user_count,resource_use,unique_resources) = correct_attempt_stats_from_csv(problem,attempt_limit)
#print "Total student count: %i, Incorrect after correct: %i, Correct after correct: %i"%(user_count,correct_to_in,correct_after_c)
for i in range(1,attempt_limit+1):
print "Attempt %3i, number of students: %i, %.2f%% out of total"%(i,attempt_dict[i],100*attempt_dict[i]/float(user_count)) #including incorrect
topValue(resource_use[i-1],show_resource)
## ###### print (resource id: count) in order for current attempt #######
## ####################################################################
## d=resource_use[i-1]
## l=[(v,k) for k,v in d.iteritems() ]
## l.sort(reverse=True)
## print "Attempt %i"%i
## for (v,k) in l:
## print "Resource ID %4i, count: %5i"%(k,v)
## ####################################################################
print "Incorrect: %.2f%%"%(100*(1-(sum(attempt_dict.values())/float(user_count))))
for i in range(1,attempt_limit+1):
[bins,labels] = create_bins(resource_use[i-1],unique_resources,log,ordered)
fig = pl.figure()
if log:
fig.suptitle("Log resource count Problem %i resources after attempt %i"%(problem,i))
else:
fig.suptitle("Problem %i resources after attempt %i"%(problem,i))
ax=pl.subplot(111)
ax.bar(range(1,len(bins)+1),bins)
ax.set_xticks(range(0,len(bins),5))
ax.set_xticklabels(labels[0:len(bins):5], rotation=75)
pl.xlim([0,len(bins)+1])
if log:
pl.ylim([0,11])
pl.show()
## save figure to .png
if saveToFig:
name = "Problem_%i_log_attempt_%i"%(problem,i)
if log:
name += "_log"
if ordered:
name += "_ordered"
name += ".png"
fig.savefig(name)
|
57569e62fa029136f3d9d817f5477e2a500ae6bb | doragon/aribon | /p42/coin.py | 937 | 3.609375 | 4 | """p42 problem"""
# coding: utf-8
# ---------------------------------------------------------
# 硬貨の問題
# ---------------------------------------------------------
def get_used_coin_list(C, A, key_list):
"""
使用したコインのリストを返す
"""
used_coin_list = []
for key in key_list:
for i in range(C[str(key)]):
if A - key == 0:
used_coin_list.append(key)
return used_coin_list
elif A - key < 0:
break
else:
used_coin_list.append(key)
A = A - key
return used_coin_list
if __name__ == '__main__':
C = {'1': 3, '5': 2, '10': 1, '50': 3, '100': 0, '500': 2}
A = 620
key_list = [500, 100, 50, 10, 5, 1]
used_coin_list = get_used_coin_list(C, A, key_list)
print(used_coin_list)
print(len(used_coin_list))
|
9f655f6206a724b9a37ab55828ccc869f859a372 | alysse24/finalproject | /main.py | 484 | 3.8125 | 4 | from data import get_data_frame, plot_graph
print('\n')
print('Retrieving data, please wait...')
df = get_data_frame('2009-1-1', '2017-12-1', 'BCHAIN/MKPRU', 'annual', 'bitcoin', 100, 100)
print('\n')
print('This table shows the value of bitcoin and the Reddit statistics for posts containing "bitcoin"')
print('\n')
print(df)
print('\n')
print('Press any key "Enter" to view the graph')
input()
plot_graph(df, 'Bitcoin worth in USD', 'Price of Bitcoin from 1/1/2009 to 12/1/2017') |
180309d829c2fc78cbe605e05e71749e8326c7c7 | FlyingBackdoor/Data-Structures-and-Algorithms | /Python/05 - Graphs.py | 1,367 | 3.75 | 4 | class Graph:
def __init__(self):
self.numberOfNodes = 0
self.adjecentList = {}
def addVertex(self, node):
self.adjecentList[node] = []
self.numberOfNodes += 1
def addEdge(self, node1, node2):
#undirected graph
try:
#for node1
currentConnection = self.adjecentList[node1]
currentConnection.append(node2)
#for node2
currentConnection = self.adjecentList[node2]
currentConnection.append(node1)
except KeyError:
print("Given node dosen't exist")
def showConnections(self):
allNodes = self.adjecentList.keys()
for node in allNodes:
nodeConnections = self.adjecentList[node]
connections = ""
for vertex in nodeConnections:
connections += vertex + " "
print(f"{node} --> {connections}")
myGraph = Graph()
myGraph.addVertex('0')
myGraph.addVertex('1')
myGraph.addVertex('2')
myGraph.addVertex('3')
myGraph.addVertex('4')
myGraph.addVertex('5')
myGraph.addVertex('6')
myGraph.addEdge('3', '1')
myGraph.addEdge('3', '4')
myGraph.addEdge('4', '2')
myGraph.addEdge('4', '5')
myGraph.addEdge('1', '2')
myGraph.addEdge('1', '0')
myGraph.addEdge('0', '2')
myGraph.addEdge('6', '5')
myGraph.showConnections()
#print(myGraph.adjecentList)
|
140a49dde3cf7d99cf837777daa203f4cdd4495c | elendmire/class0 | /functions.py | 339 | 3.890625 | 4 | def square(x):
return x*x
def main():
for i in range(10):
#f bilmemne yapmak yerine bu şekilde bağlama da yapabiliriz print olaylarında
print("{} squared is {}".format(i, square(i)))
#ayrıca python yukarıdan aşağıya kodu okur yani fonksiyonu yukarıda yazman lazım!
if __name__ == "__main__":
main() |
c76ee37abddf20128f1a8e43442a2b8d92d540e4 | DaBearsCodeMonkey/SchoolProjects | /PlayFair/Playfair.py | 9,336 | 3.53125 | 4 | import re
table = [['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*'],
['*', '*', '*', '*', '*']]
no_j = [0] * 50
no_x = [0] * 50
j = 0
r = 0
def playfair(secret, plaintext):
secret = input("Enter a keyword: ")
create_table(secret)
return encode(cleanup(plaintext))
def print_table():
for row in range(5):
for col in range(5):
print table[row][col],
print ""
def clear_table():
for row in range(5):
for col in range(5):
table[row][col] = "*"
def table_has_letter(letter):
for row in range(5):
for col in range(5):
if letter == table[row][column]:
return true
return false
def create_table(secret):
clear_table()
secret = secret.upper()
secret = secret.replace(" ", "")
keyword = ""
alpha = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
z = 0
for x in range(len(secret)):
if secret[x] == 'J':
secret = secret.replace('J', 'I')
if keyword.find(secret[x]) == -1:
keyword = keyword + secret[x]
x = 0
for x in range(len(alpha)):
if keyword.find(alpha[x]) == -1:
keyword = keyword + alpha[x]
x = 0
for row in range(5):
for col in range(5):
table[row][col] = keyword[x]
x=x+1
def find_letter(letter):
for x in range(5):
for y in range(5):
if table[x][y] == letter:
return x, y
def encode_pair(a, b):
for row in range(5):
for col in range(5):
if table[row][col] == a:
a_row = row
a_col = col
if a == b:
b_row = row
b_col = col
elif table[row][col] == b:
if a == b:
a_row = row
a_col = col
b_row = row
b_col = col
if a_row == b_row:
if a_col == 4:
a = table[a_row][0]
if b_col != 4:
b = table[b_row][b_col+1]
else:
b = table[b_row][0]
elif b_col == 4:
b = table[b_row][0]
if a_col != 4:
a = table[a_row][a_col+1]
else:
a = table[a_row][0]
else:
a = table[a_row][a_col+1]
b = table[b_row][b_col+1]
elif a_col == b_col:
if a_row == 4:
a = table[0][a_col]
if b_row != 4:
b = table[b_row+1][b_col]
else:
b = table[0][b_col]
elif b_row == 4:
b = table[0][b_col]
if a_row != 4:
a = table[a_row+1][a_col]
else:
a = table[0][a_col]
else:
if a_row == 4:
a = table[0][a_col]
else:
a = table[a_row+1][a_col]
if b_row == 4:
b = table[0][b_col]
else:
b = table[b_row+1][b_col]
else:
a = table[a_row][b_col]
b = table[b_row][a_col]
return a+b
def cleanup(plaintext):
plaintext = plaintext.replace(' ', '')
plaintext = plaintext.upper()
plaintext = plaintext.replace('J', 'I')
plaintext = fix_one_problem(plaintext)
return plaintext
def encode(plaintext):
ciphertext = ""
for x in range(0, len(plaintext), 2):
ciphertext = ciphertext + encode_pair(plaintext[x], plaintext[x+1])
return ciphertext
def fix_one_problem(plaintext):
problem = 0
restart = True
while restart:
restart = False
new = ""
if len(plaintext) % 2 == 1:
for x in range(len(plaintext)):
if x % 2 == 0 and x + 1 < len(plaintext):
new = new + plaintext[x]
if plaintext[x] == plaintext[x+1] and plaintext[x] != 'X':
new = new + 'X'
new = new + plaintext[x+1]
problem = problem + 1
elif plaintext[x] == plaintext[x+1] and plaintext[x] == 'X':
new = new + 'Q'
new = new + plaintext[x+1]
problem = problem + 1
else:
new = new + plaintext[x+1]
elif x % 2 == 0 and x + 1 == len(plaintext):
if plaintext[-1] == plaintext[-2] and len(plaintext) > 1:
new = new + 'X'
new = new + plaintext[-1]
else:
new = new + plaintext[-1]
else:
for x in range(0, len(plaintext), 2):
new = new + plaintext[x]
if plaintext[x] == plaintext[x+1] and plaintext[x] != 'X':
new = new + 'X'
new = new + plaintext[x+1]
problem = problem + 1
elif plaintext[x] == plaintext[x+1] and plaintext[x] == 'X':
new = new + 'Q'
new = new + plaintext[x+1]
problem = problem + 1
else:
new = new + plaintext[x+1]
x = 0
if len(plaintext) % 2 == 0:
if plaintext[x] == plaintext[x+1]:
plaintext = new
restart = True
if len(new) % 2 == 1 and plaintext[-1] != 'Z':
new = new + 'Z'
problem = problem + 1
elif len(new) % 2 == 1 and plaintext[-1] == 'Z':
new = new + 'Q'
problem = problem + 1
if problem > 0:
return new
return plaintext
def playfair(secret, plaintext):
create_table(secret)
print print_table()
return encode(cleanup(plaintext))
def decode_pair(a,b):
for row in range(5):
for col in range(5):
if table[row][col] == a:
a_row = row
a_col = col
if a == b:
b_row = row
b_col = col
elif table[row][col] == b:
if a == b:
a_row = row
a_col = col
b_row = row
b_col = col
if a_row == b_row:
if a_col == 0:
a = table[a_row][4]
if b_col != 0:
b = table[b_row][b_col-1]
else:
b = table[b_row][4]
elif b_col == 0:
b = table[b_row][4]
if a_col != 0:
a = table[a_row][a_col-1]
else:
a = table[a_row][4]
else:
a = table[a_row][a_col-1]
b = table[b_row][b_col-1]
elif a_col == b_col:
if a_col == 0:
a = table[4][a_col]
if b_col != 0:
b = table[b_row-1][b_col]
else:
b = table[4][b_col]
elif b_col == 0:
b = table[4][b_col]
if a_col != 0:
a = table[a_row-1][a_col]
else:
a = table[4][a_col]
else:
if a_row == 0:
a = table[4][a_col]
else:
a = table[a_row-1][a_col]
if b_row == 0:
b = table[4][b_col]
else:
b = table[b_row-1][b_col]
else:
a = table[a_row][b_col]
b = table[b_row][a_col]
return a+b
def playfair_decode(secret, ciphertext, count, maximum):
plaintext = ""
check = False
for x in range(0, len(ciphertext), 2):
plaintext = plaintext + decode_pair(ciphertext[x], ciphertext[x+1])
if plaintext[-1] == 'Z' or plaintext[-1] == 'Q':
plaintext = plaintext.replace(plaintext[-1], '')
x = 0
new = ""
i = 0
if r == 0:
plaintext = plaintext.replace('X', '')
for x in range(len(plaintext)):
if x == count[i] and i < maximum:
new = new + ' '
i = i + 1
new = new + plaintext[x]
x = 0
temp = ""
if j > 0:
new = new.replace('I', 'J')
temp2 = ""
if r > 0:
temp = new.split('X')
b = 0
for i in temp:
temp2 = temp2 + temp[b]
b = b+1
if len(temp2) == no_x[x]:
check = True
temp2 = temp2 + 'X'
x = x+1
if check == True:
return temp2
return new
if __name__ == "__main__":
s = raw_input("Enter the secret key: ")
p = raw_input("Enter the plaintext: ")
count = [0] * 50
i = 0
t = 0
for x in range(len(p)):
if p[x] == ' ':
count[i] = x - t
i = i+1
t = t+1
if p[x] == 'J' or p[x] == 'j':
no_j[j] = x
j = j + 1
if p[x] == 'X' or p[x] == 'x':
no_x[r] = x
r = r + 1
c = playfair(s, p)
print "Ciphertext: ", c
print "Decoded text: ", playfair_decode(s, c, count, i) |
b90b067299dbd0f243cb97968bcb4a105a2d0a22 | oceanbei333/leetcode | /897.递增顺序查找树.py | 1,250 | 3.59375 | 4 | #
# @lc app=leetcode.cn id=897 lang=python3
#
# [897] 递增顺序查找树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
if not root:
return
alist = []
def dfs(root:TreeNode):
if not root:
return
dfs(root.left)
alist.append(root)
dfs(root.right)
dfs(root)
for index in range(len(alist)-1):
alist[index].left = None
alist[index].right =alist[index+1]
return alist[0]
def increasingBST(self, root: TreeNode) -> TreeNode:
self.head = None
self.node = None
def dfs(root:TreeNode):
if not root:
return
dfs(root.left)
if not self.node:
self.node = root
self.head = root
else:
self.node.left = None
self.node.right = root
self.node = root
dfs(root.right)
dfs(root)
return self.head
# @lc code=end
|
b2824c1b3092948b81450eb80e4739e3e5393e69 | aAlejandroz/Airport-IATA-Service | /test/airport_test.py | 3,528 | 3.59375 | 4 | import unittest
from src.Airport import (Airport)
from src.airport_status import (AirportStatus)
class AirportStatusTest(unittest.TestCase):
def setUp(self):
self.airport_status = AirportStatus()
self.iah = Airport("George Bush Intercontinental/houston", 'IAH',None,None,None,None)
self.iad = Airport("Dulles Airport", 'IAD',None,None,None,None)
self.ord = Airport("Chicago Airport", 'ORD',None,None,None,None)
def test_canary(self):
self.assertTrue(True)
def test_sort_list_with_no_airports(self):
self.assertEqual(self.airport_status.sort_airports([]), [])
def test_sort_list_with_one_airport(self):
self.assertEqual(
self.airport_status.sort_airports([self.iah]), [self.iah])
def test_sort_list_with_two_airports_in_non_sorted_order(self):
self.assertEqual(
self.airport_status.sort_airports([self.iah, self.iad]),
[self.iad, self.iah])
def test_sort_list_with_two_airports_appended_in_sorted_order(self):
self.assertEqual(
self.airport_status.sort_airports([self.iah, self.iad]),
[self.iad, self.iah])
def test_sort_list_of_three_airports(self):
self.assertEqual(
self.airport_status.sort_airports([self.iah, self.iad, self.ord]),
[self.ord, self.iad, self.iah])
def test_pass_empty_list_return_empty_name_list(self):
self.assertEqual(
self.airport_status.get_airports_status([], None), ([], []))
def test_pass_list_of_one_airport_code_return_its_respective_name(self):
service = lambda code: {'IAH': self.iah}[code]
self.assertEqual(
self.airport_status.get_airports_status(['IAH'], service), ([self.iah], []))
def test_pass_list_of_two_airports_code_return_their_respective_names(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad}[code]
self.assertEqual(
self.airport_status.get_airports_status(['IAD', 'IAH'], service),
([self.iad, self.iah],[]))
def test_pass_list_of_two_airports_code_return_their_respective_names_sorted(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad}[code]
self.assertEqual(
self.airport_status.get_airports_status(['IAH', 'IAD'], service),
([self.iad, self.iah],[]))
def test_pass_list_of_three_airports_code_return_their_respective_names_sorted(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad, 'ORD': self.ord}[code]
self.assertEqual(
([self.ord, self.iad, self.iah],[]),
self.airport_status.get_airports_status(['IAH', 'IAD','ORD'], service))
def test_one_airport_code_is_invalid(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad, 'ORD': self.ord}[code]
self.assertEqual(self.airport_status.get_airports_status(['IA'],service),
([], ['IA']))
def test_two_airport_codes_are_given_second_invalid(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad, 'ORD': self.ord}[code]
self.assertEqual(self.airport_status.get_airports_status(['IAH','OR'], service), ([self.iah],['OR']))
def test_three_airport_codes_are_given_second_invalid(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad, 'ORD': self.ord}[code]
self.assertEqual(self.airport_status.get_airports_status(['IAH', 'OR', 'IAD'], service), ([self.iad,self.iah],['OR']))
def test_three_airport_codes_are_given_first_invalid_third_network_error(self):
service = lambda code: {'IAH': self.iah, 'IAD': self.iad, 'ORD': self.ord}[code]
self.assertEqual(([self.ord],['IA','']), self.airport_status.get_airports_status(['IA', 'ORD', ''], service))
if __name__ == '__main__':
unittest.main()
|
e031831f9070f995242589eea35d6e45bfcaaafb | mike006322/ProjectEuler | /Solutions/PE010_summation_of_primes/python/summation_of_primes.py | 984 | 3.515625 | 4 | #!/bin/python3
# https://www.hackerrank.com/contests/projecteuler/challenges/euler010
# This solution is correct but not fast enough
# Number of test cases can be up to 10^4
# Better solution is to build the sieve once up to 10^6, then construct table with the sums
# See fast_summation.py for that implementation
def Sieve_of_Eratosthenes(n):
"""
Return list of primes less than n
"""
res = [2]
i = 3
marked = set()
while i <= n**.5:
if i not in marked:
res.append(i)
j = 0
while j <= n/i:
marked.add(i + j*i)
j += 1
i += 2
while i <= n:
if i not in marked:
res.append(i)
i += 2
return res
def summation_of_primes(n):
primes = Sieve_of_Eratosthenes(n)
return sum(primes)
if __name__ == '__main__':
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(summation_of_primes(n))
|
f8e4f120403b10aa42b88154944e048e44642b9d | ctc316/algorithm-python | /Lintcode/Ladder_37_BB/medium/1357. Path Sum II.py | 790 | 3.75 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a binary tree
@param sum: the sum
@return: the scheme
"""
def pathSum(self, root, sum):
results = []
self.dfs(root, [], sum, results)
return results
def dfs(self, root, path, remain, results):
if not root or remain < 0 :
return
remain -= root.val
path.append(root.val)
if not root.left and not root.right and remain == 0:
results.append([p for p in path])
else:
self.dfs(root.left, path, remain, results)
self.dfs(root.right, path, remain, results)
path.pop()
|
6a790093564e6b455a4bc60041f9cc5e76c620ba | djaychela/playground | /codefights/arcade/diving_deeper/array_max_consecutive_sum.py | 297 | 3.59375 | 4 | def arrayMaxConsecutiveSum(inputArray, k):
highest = 0
for i in range(len(inputArray)-k+1):
current = sum(inputArray[i:i+k])
print(i, current)
if current > highest:
highest = current
return highest
print(arrayMaxConsecutiveSum([2, 3, 5, 1, 6], 2)) |
9861f9d1daebf99dcf394425e3c9071b765c47f9 | redgyuf/guessthenumber | /numcheck.py | 606 | 4.09375 | 4 | import math
def checkEven(randomNumber):
if((randomNumber % 2) == 0):
print("It is even!") # its even
else:
print("It is odd!") # its odd
def checkDivisible(input, randomNumber):
if((randomNumber) % input == 0):
print("It is divisible by {}.\n" .format(input))
else:
print("It is not divisible by {}.\n" .format(input))
def checkPrime(randomNumber):
for i in range(2, int(math.sqrt(randomNumber))):
if randomNumber % i == 0:
print('Not a prime number.')
break
else:
print('Yes, it is a prime number.')
|
9f9e2bb33d0f5ec52c0f38169fb923bcd2614386 | Aabid-Hussain/PythonLearningProg | /Basics/func_inside_func4.py | 1,502 | 4.3125 | 4 | #Decorator - it is function that takes another function as it's argument.
# and add some kind of functionality and return a function without
# altering the original source code function which is passed in
'''
meaning of @decorator_functions
display = decorator_functions(display)
TypeError: wrapper_function() takes 0 positional arguments but 2 were given
positional argument is defined using = *var
Keyword argument is defined using = **var
General practice [positional] arg = *args; [keyword] arg = **kwargs
'''
def decorator_functions(func):
def wrapper():
print("{} function executed before {} function".format(
wrapper.__name__, func.__name__))
return func()
return wrapper
def decorator_func(func):
def wrapper(*args, **kwargs):
print("{} function executed before {} function".format(
wrapper.__name__, func.__name__))
return func(*args, **kwargs)
return wrapper
#class used as decorator
class decorators:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("call method executed before {} functions".format(
self.func.__name__))
return self.func(*args, **kwargs)
@decorator_functions
def display():
print('display function ran')
print()
display()
@decorators
def display_info(name, age):
print('display_info ran with arguments ({},{})'.format(name, age))
print()
display_info('Aabid', 25)
|
9f2833c6eecb0e349128b16a37c0efc042fa7571 | keriwheatley/projectGrandmaGame | /main/fac.py | 516 | 4.5 | 4 | """Write a script to compute how many unique prime factors an integer has.
For example, 12 = 2 x 2 x 3, so has two unique prime factors, 2 and 3.
Use your script to compute the number of unique prime factors of 1234567890."""
def fac(i):
factors = []
print "Starting number is ", i
f = 2
while i <> 1:
while i % f == 0:
i /= f
factors.append(f)
print "adding factor ", f, ", new number ", i
f += 1
factors.sort()
print "Here are the factors: ", factors
fac(1234567890)
|
375db9e6f18c343d9ddf2c43cf26c5ad9310f6aa | JasmineRain/Algorithm | /Python/Others/56_Medium_合并区间.py | 652 | 3.71875 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
ans = []
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
ans.append(intervals[0])
for i in range(1, len(intervals)):
if intervals[i][0] <= ans[-1][1]:
ans[-1] = [ans[-1][0], max(intervals[i][1], ans[-1][1])]
else:
ans.append(intervals[i])
return ans
if __name__ == "__main__":
S = Solution()
print(S.merge(intervals=[[1, 3], [2, 6], [8, 10], [15, 18]]))
print(S.merge(intervals=[[1, 4], [4, 5]]))
|
81205b153533fee07ed2daf85ae419b9ab2cb545 | krzkrusz/untitled | /hello.py | 440 | 3.96875 | 4 | import os
my_str = "Hello Academy"
str2 = "Hi"
age = 24
name = "Krzysztof"
output=my_str + str2 + " " +str2
str_template = "my name is {}.I am {} years old."
print(str_template.format(name,age))
def add_vegetable(vegetable='carrot', list_of_vegetables=[]):
list_of_vegetables.append(vegetable)
return list_of_vegetables
first_list = add_vegetable()
second_list = add_vegetable('banana')
print(first_list)
print(second_list)
|
d4e4203069eb8881480a27e04fef0c20a644a189 | Katuri31/PSP | /python/functions.py | 910 | 4.09375 | 4 | '''
#a function is a piece of code which runs when it is refered.
#it is used to utilize the code in more than one place in a program, in-built functions,user defined functions print(),input().
def add(x,y):
return(x+y)
x=3
y=4
z=add(x,y)
print("z=",z)
#or else we can directly write-
#print(add(x,y)) or
print(add(30,40))
def square(x):
return x*x
print(square(20))
'''
#Lambda function: It is an anonymous function or a function having no name.It is a small and restricted function
#having no more than one line
#lambda p1,p2:expression
'''adder=lambda x,y:x+y
print(adder(1,2))
import math
distance=lambda x,y:math.sqrt((x**2)+(y**2))
print(distance(4,5))'''
#map function-----> it is used to apply a particular operatin to every element in a sequece.
'''even_list=[2,4,6,8,10]
squared_even_list=map(lambda x:x*x,even_list )
print(list(squared_even_list))'''
|
a1aacca990bdabc1150b4c5e1fb40bbc7026c4d2 | syurskyi/Python_3_Deep_Dive_Part_2 | /Section 8 Iteration Tools/87. Grouping - Coding.py | 7,386 | 4.125 | 4 | print('#' * 52 + ' ### Grouping')
import itertools
with open('cars_2014.csv') as f:
for row in itertools.islice(f, 0, 20):
print(row, end='')
print('#' * 52 + ' Trivial to do with SQL, but a little more work with Python.')
from collections import defaultdict
makes = defaultdict(int)
with open('cars_2014.csv') as f:
next(f) # skip header row
for row in f:
make, _ = row.strip('\n').split(',')
makes[make] += 1
for key, value in makes.items():
print(f'{key}: {value}')
print('#' * 52 + ' Instead of doing all this, we could use the `groupby` function in `itertools`.')
print('#' * 52 + ' Again, it is a lazy iterator, so we will use lists to see whats happening -'
' but lets use a slightly smaller data set as an example first:')
data = (1, 1, 2, 2, 3)
print(list(itertools.groupby(data)))
print('#' * 52 + ' As you can see, we ended up with an iterable of tuples.')
print('#' * 52 + ' The tuple was the groups of numbers in data, so `1`, `2`, and `3`')
print('#' * 52 + ' But what is in the second element of the tuple? Well its an iterator, but what does it contain?')
it = itertools.groupby(data)
for group in it:
print(group[0], list(group[1]))
print('#' * 52 + ' Basically it just contained the grouped elements themselves.')
print('#' * 52 + ' This might seem a bit confusing at first - so lets look at the second optional'
' argument of group by - it is a key.')
print('#' * 52 + ' Basically the idea behind that key is the same as the sort keys,'
' or filter keys we have worked with in the past.')
print('#' * 52 + ' It is a **function** that returns a grouping key.')
data = (
(1, 'abc'),
(1, 'bcd'),
(2, 'pyt'),
(2, 'yth'),
(2, 'tho'),
(3, 'hon')
)
groups = list(itertools.groupby(data, key=lambda x: x[0]))
print(groups)
print('#' * 52 + ' Once again you will notice that we have the group keys, and some iterable.')
print('#' * 52 + ' Lets see what those contain:')
groups = itertools.groupby(data, key=lambda x: x[0])
for group in groups:
print(group[0], list(group[1]))
print('#' * 52 + ' So now lets go back to our car make example.')
print('#' * 52 + ' We want to get all the makes and how many models are in each make.')
with open('cars_2014.csv') as f:
make_groups = itertools.groupby(f, key=lambda x: x.split(',')[0])
# list(itertools.islice(make_groups, 5)) # ValueError: I/O operation on closed file.
print('#' * 52 + ' Whats going on?')
print('#' * 52 + ' Remember that `groupby` is a **lazy** iterator. '
' This means it did not actually do any work when we called it apart from setting up the iterator.')
print('#' * 52 + ' When we called `list()` on that iterator, **then** it went ahead and try to do the iteration.')
print('#' * 52 + ' However, our `with` (context manager) closed the file by then!')
print('#' * 52 + ' So we will need to do our work inside the context manager.')
with open('cars_2014.csv') as f:
next(f) # skip header row
make_groups = itertools.groupby(f, key=lambda x: x.split(',')[0])
print(list(itertools.islice(make_groups, 5)))
print('#' * 52 + ' Next, we need to know how many items are in each `itertools._grouper` iterators.')
print('#' * 52 + ' How about using the `len()` property of the iterator?')
# with open('cars_2014.csv') as f:
# next(f) # skip header row
# make_groups = itertools.groupby(f, key=lambda x: x.split(',')[0])
# make_counts = ((key, len(models)) for key, models in make_groups)
# print(list(make_counts)) # TypeError: object of type 'itertools._grouper' has no len()
print('#' * 52 + ' Aww... Iterators dont necessarily implement a `__len__` method - and this one definitely does not.')
print('#' * 52 + ' Well, if we think about this, we could simply "replace" each element in the models, '
' with 1, and sum that up ')
with open('cars_2014.csv') as f:
next(f) # skip header row
make_groups = itertools.groupby(f, key=lambda x: x.split(',')[0])
make_counts = ((key, sum(1 for model in models))
for key, models in make_groups)
print(list(make_counts))
print('#' * 52 + ' #### Caveat')
groups = list(itertools.groupby(data, key=lambda x: x[0]))
for group in groups:
print(group[0], group[1])
print('#' * 52 + ' Ok, so this looks fine - we now have a list containing tuples - the first element is the group key'
' the second is an iterator - we can ceck that easily:')
it = groups[0][1]
print(iter(it) is it)
print('#' * 52 + ' So yes, this is an iterator - what is in it?')
print(list(it))
print('#' * 52 + ' Empty?? But we did not iterate through it - what happened?')
groups = list(itertools.groupby(data, key=lambda x: x[0]))
for group in groups:
print(group[0], list(group[1]))
print('#' * 52 + ' So, the 3rd element is OK, but looks like the first two got exhausted somehow...')
print('#' * 52 + ' Lets make sure they are indeed exhausted:')
groups = list(itertools.groupby(data, key=lambda x: x[0]))
# next(groups[0][1]) # StopIteration:
# next(groups[1][1]) # StopIteration:
print(next(groups[2][1]))
print('#' * 52 + ' So, yes, the first two were exhausted when we converted the groups to a list.')
print('#' * 52 + ' The solution here is actually in the Python docs')
print('#' * 52 + ' The key thing here is that the elements yielded from the different groups are using'
' the **same** undelying iterable over all the elements.')
print('#' * 52 + ' As the documentation states, when we advance to the next group, the previous ones iterator is'
' automatically exhausted - it basically iterates over all the elements'
' until it hits the next group key.')
groups = itertools.groupby(data, key=lambda x: x[0])
group1 = next(groups)
print(group1)
print('#' * 52 + ' And the iterator in the tuple is not exhausted:')
print(next(group1[1]))
print('#' * 52 + ' Now, lets try again, but this time we will advance to group2,'
' and see what is in `group1`s iterator:')
groups = itertools.groupby(data, key=lambda x: x[0])
group1 = next(groups)
group2 = next(groups)
print('#' * 52 + ' Now `group1`s iterator has been exhausted (because we moved to `group2`):')
# print(next(group1[1])) # StopIteration:
print('#' * 52 + ' But `group2` s iterator is still OK:')
print(next(group2[1]))
print('#' * 52 + ' We know that there are still two elements in `group2`, so lets advance to `group3`'
' and go back and see whats left in `group2` s iterator:')
group3 = next(groups)
# next(group2[1]) # StopIteration:
print('#' * 52 + ' But `group3` s iterator is just fine:')
print(next(group3[1]))
print('#' * 52 + ' So, just be careful here with the `groupby()` - if you want to save all the data into'
' a list you cannot first convert the groups into a list -'
' you **must** step through the groups iterator,')
print('#' * 52 + ' and retrieve each individual iterators elements into a list,'
' the way we did it in the first example, or simply using a comprehension:')
groups = itertools.groupby(data, key=lambda x: x[0])
groups_list = [(key, list(items)) for key, items in groups]
print(groups_list)
|
f1e446377f5448ffbbccf5595a85aff9b8318483 | vero11602/bmi | /bmi.py | 564 | 4.03125 | 4 | weigh = input('你體重多少:')
weigh = float (weigh)
heigh= input('你身高多少')
heigh = float (heigh) / 100
bmi = (weigh) / (heigh **2)
print ('您的bmi為:' , bmi )
if bmi < 18.5:
print ('您的' , bmi , '過輕')
elif bmi >=18.5 and bmi < 24 :
print ('您的' , bmi , '在正常值')
elif bmi >=24 and bmi < 27 :
print ('您的' , bmi , '過重')
elif bmi >=27 and bmi <30 :
print ('您的' , bmi , '輕度肥胖')
elif bmi >=30 and bmi <35 :
print ('您的' , bmi , '中度肥胖')
else:
print ('您的' , bmi , '重度肥胖')
|
d3ac720d3d5dfc94964b820c46c2da28d5c5dfba | rafaelperazzo/programacao-web | /moodledata/vpl_data/74/usersdata/230/39044/submittedfiles/lecker.py | 461 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import math
n1=float(input('Digite primeiro número: '))
n2=float(input('Digite segundo número: '))
n3=float(input('Digite terceiro número: '))
n4=float(input('Digite quarto número: '))
if n2>n1 and n2>n3 and n4>n3:
print('N')
elif n1>n2 and n4>n3:
print('N')
elif n3>n4 and n3>n2 and n1>n2:
print('N')
elif n2>n1 and n2<n3 or n3>n2 and n3>n4:
print('S')
elif n1>n2 and n4>n3:
print('S')
else:
print('N')
|
62fc43cfc8dd6e646357522489e49aefff4ca49d | GauthamAjayKannan/guvi | /onestep.py | 91 | 3.6875 | 4 | n=int(input())
while n!=0:
for i in range(n,0,-1):
print(1,end=" ")
n=n-1
print()
|
2f5be61f4e6d5de4e9aa1f817830d3c883eabb53 | ArunCSK/PythonWeek1 | /pythonbasics.py | 1,501 | 4.1875 | 4 | #print('hi')
from datetime import date
#reverse string
def name():
firstname = input('Enter First name')
lastname = input('Enter Last Name')
#print(firstname + ' ' + lastname)
txt = firstname + ' ' + lastname
reversetxt = reversestring(txt)
newtxt = ""
for t in reversetxt:
newtxt += " " + t
print(newtxt)
def reversestring(txt):
return txt[::-1]
#list and tuple
def listntuple():
inputstr = input("Sample data: ")
l = (inputstr.split(","))
t = tuple(l)
print("List: ",l)
print("Tuple: ", t)
#array to display first and last color
def color():
color_list = ["Red","Green","White" ,"Black"]
print("First:",color_list[0])
print("Last:",color_list[len(color_list)-1])
#print python syntax and desc
def printsyntax():
#import pydoc
func = input('Sample function:')
#print(func+".__doc__")
print(help(func))
#print calender of given month and year
def printcalender():
import calendar
print(calendar.month(2019,5))
#Calculate date diff
def CalculateDateDiff():
dates = input("Sample dates:")
print(dates)
#accept user input options
io = input("1.name 2.list 3.color 4.syntax 5.calender Enter values:")
#print(io)
if io == "name":
name()
elif io == "list":
listntuple()
elif io == "color":
color()
elif io == "syntax":
printsyntax()
elif io == "calender":
printcalender()
elif io == "date":
CalculateDateDiff()
else:
print('Execute Succes!!!')
|
380a24e8c7aef24c3d294839d8b1609f810f3c47 | GunnarDiestmann/MasterArbeit_CoopLaneChange_Git | /src/cost_and_evaluation_functions_python/Vehicle.py | 3,074 | 3.578125 | 4 | import numpy as np
import cost_function
class VehicleList(object):
veh_list = []
num_of_veh_tl = 0
num_of_veh_il = 0
class VehicleEnvelop(object):
"""
This class describes the outlines of a vehicle
"""
def __init__(self, veh_properties):
"""
:type veh_properties: VehicleProperties
:param veh_properties: dimensional properties of a vehicle
"""
self.alpha1 = np.arctan(-veh_properties.length_to_rear_bumper / (veh_properties.width / 2))
self.alpha2 = np.arctan((1. / (veh_properties.width / 2)))
self.a = -veh_properties.length_to_rear_bumper
self.b = (veh_properties.width / 2)
def value(self, alpha):
"""
:type alpha: double
:param alpha: angle at which the distance to the vehicle envelop needs to be determined
:return: distance from vehicle coordinate system to vehicle envelop
"""
return (self.a/(np.sin(alpha)+0.000001))*(alpha < self.alpha1) + \
(self.b/(np.cos(alpha) + 0.000001))*(alpha >= self.alpha1)*(alpha < self.alpha2) + \
(1. / (np.sin(alpha) + 0.000001)) * (alpha >= self.alpha2)
class VehicleProperties(object):
"""
This Class represents all properties of a vehicle
"""
def __init__(self, length, width):
"""
:param length: length of the vehicle
:param width: width of the vehicle
"""
self.length = length # length of the vehicle
self.width = width # width of the vehicle
self.length_to_front_bumper = 1. # position of the coordination system measured form the front bumper
self.length_to_rear_bumper = self.length - self.length_to_front_bumper
class Vehicle(object):
"""
This class represents vehicles. A vehicle is described by it length and width, the position of the coordinate system
and by a list of possible trajectories. When the trajectory is given this list will have just one object
"""
def __init__(self, veh_index, s_start, d_start, v_start, v_opt, v_max, dt, a_start=0., length=5., width=2.):
"""
:type veh_index: int
:param veh_index: index of the vehicle
:type s_start: float
:param s_start: starting position of the vehicle
:type v_start: float
:param v_start: speed at time t
:type a_start: float
:param a_start: acceleration at time t
:type length: float
:param length: length of the vehicle
:type width: float
:param width: vehicle width
"""
self.veh_index = veh_index
self.properties = VehicleProperties(length, width)
self.envelop = VehicleEnvelop(self.properties)
self.s_start = s_start
self.d_start = d_start
self.v_start = v_start
self.v_opt = v_opt
self.v_max = v_max
self.a_start = a_start
self.path = None
self.cost_func = cost_function.CostFunction(dt)
self.cost_func.v_opt = v_opt
self.cost_func.reset_eval_functions()
|
20d7992cb93bcfe1c5b229a761d3b2bfb4e541d8 | liu839/python_stu | /程序记录/类与对象/两点间距.py | 432 | 3.609375 | 4 | import math as m
class Point():
def __init__(self,x):
self.posion=[x[0],x[1]]
class Line():
def __init__(self,a,b):
self.length=0.0
self.point_a=Point(a)
self.point_b=Point(b)
def get_len(self):
self.length=m.sqrt(pow(self.point_a.posion[0]-self.point_b.posion[0],2)+pow(self.point_a.posion[1]-self.point_b.posion[1],2))
l_1=Line((1,3),(2,6))
l_1.get_len()
print(l_1.length)
|
71a1c49da511401df03ad52f294d3f8055208c41 | Axieof/DiceRoller | /diceroll.py | 1,380 | 4.0625 | 4 | #Program by Pritheev
#Dice Roller
import random
#Variable Initialization
Loop = True
DiceSet = False
def MainMenu():
print("========================")
print("[1] Choose Dice Size")
print("[2] Roll Dice")
print("[0] Exit")
print("========================")
def CoolDice(Number):
print("+++++")
print("+ {0} +".format(Number))
print("+++++")
print()
while(Loop):
MainMenu()
print()
Options = int(input("Enter option: "))
print()
if (Options == 0):
print("========================")
print("Exiting...")
print("========================")
Loop = False
break
elif (Options == 1):
print("========================")
print("Option [1] Selected")
print("========================")
print()
DiceSides = int(input("Enter number of sides for dice: "))
print()
DiceSet = True
elif (Options == 2):
print("========================")
print("Option [1] Selected")
print("========================")
print()
if (DiceSet):
randomNum = random.randint(1, DiceSides)
if (DiceSides < 10):
CoolDice(randomNum)
else:
print(randomNum)
print()
else:
print("Set a dice first!")
print() |
567bc248b9c440fe5d06ebe0282ea0db5c647f42 | ZarmeenLakhani/Python-Documentation | /Calendar.py | 541 | 4.15625 | 4 | import calendar
print (calendar.weekheader(3))
print("")
print(calendar.month(2020,3))
print(calendar.monthcalendar(2020, 2))
#this is in more scalar form. Here the 2 is basically
print(calendar.calendar(2020))
print("")
day_of_week=calendar.weekday(2020,9,21)
print(day_of_week)
#In python days start from monday and it is considered 0
leap_check=calendar.isleap(2020)
print(leap_check)
leap_days_count=calendar.leapdays(2000,2004)
print(leap_days_count)
#the lower limit that 2005 won't be inclusive.so make it n+1 o=in order to save it.
|
4462079897a0c890a48678ff23e70df32694e505 | bowie2k3/cos205 | /COS-205_assignment5b_AJmemoized.py | 873 | 4.625 | 5 |
# Write a function to compute the nth Fibonacci number. A Fibonacci sequence
# is a sequence of numbers where each successive number is the sum of the
# previous two. The classic Fibonacci sequence begins as 1, 1, 2, 3, 5, 8, 13, ...
import time
def fibo(n):
memo = {}
if n in memo:
return memo
if n <= 2:
f = 1
else:
f = fibo(n-1)+fibo(n-2)
memo[n] = f
return f
# Then write a main program that prompts the user to enter n and prints out
# the nth Fibonacci number. For example, if the user enters 6, then it should print out 8.
start_time = time.time()
def main():
start_time = time.time()
n = eval(input("Please enter the desired nth Fibonacci number: "))
number = fibo(n)
print("The Fibonacci number in position", n, "is:", number)
print("--- %s seconds ---" % (time.time() - start_time))
main() |
31253153bbc48e3c4884beaca2b3a1fa4a4b9375 | gavinmcguigan/gav_euler_challenge_100 | /Problem_24/LexicographicPermutations.py | 1,325 | 3.859375 | 4 | from globs import *
"""
A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits
1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
The lexicographic permutations of 0, 1 and 2 are:
012 021 102 120 201 210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
def part2(val, indx):
for mi in reversed(val):
indx2 = val.index(mi)
if not (mi <= val[indx - 1]):
val[indx - 1], val[indx2] = val[indx2], val[indx - 1]
val[indx:] = val[-1: indx - 1: -1]
return val
def part1(val):
for mi in reversed(val):
indx = val.index(mi)
if not (indx > 0 and val[indx - 1] >= val[indx]):
if indx != 0:
answer = part2(val, indx)
break
else:
return False
return answer
if __name__ == '__main__':
lex_perm = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
counter = 1
while lex_perm:
lex_perm = part1(lex_perm)
counter += 1
if counter == 1000000:
print(f"{counter:<3} Answer: {''.join([str(i) for i in lex_perm])} in {get_time_running():0.4f} secs")
break
|
94adbe8e68cb706ad9e841536c335bda11ed63a6 | CodingWD/course | /python/chenmingming/class/restaurant.py | 1,291 | 3.734375 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print('this restaurant\'name is '+ self.restaurant_name.title())
print('and it is a '+self.cuisine_type+' restaurant.')
def open_restaurant(self):
print(self.restaurant_name.title() + ' is opening.')
def get_served_number(self):
print('It had served '+ str(self.number_served) + ' peoples.')
def set_number_served(self, number_served):
if self.number_served <= number_served:
self.number_served = number_served
self.get_served_number()
else:
print('You can not roll back number!')
self.get_served_number()
def increment_number_served(self, incr_number):
if incr_number < 0:
print('You cannot cheat me ! number < 0')
else:
self.number_served += incr_number
self.get_served_number()
# restaurant = Restaurant('restaurant of lake & moonlight', 'chinese food')
# print(restaurant.restaurant_name)
# print(restaurant.cuisine_type)
# restaurant.describe_restaurant()
# restaurant.open_restaurant()
# restaurant.set_number_served(10)
# restaurant.set_number_served(5)
# restaurant.increment_number_served(-1)
# restaurant.increment_number_served(100)
|
d8bd47faca977c597b5c72ef899e9e984d1d9c93 | codefather91/100DaysOfPython | /Day-004-Randomization_Lists/RockPaperScissors.py | 2,107 | 4.28125 | 4 | # A simple game of rock paper scissors
# Simple rules:
# Rock beats scissors
# Scissors beats Paper
# Paper beats Rock
# import random module
import random
#initialise ASCII art for rock, paper & scissors
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
# Print welcome message
print("Welcome to the game of ROck, Paper & Scissors!")
player_choice = int(input("Take your pic!\n1. Rock\n2. Paper\n3. Scissors\n"))
print()
# Accept user input and display
if player_choice == 1:
print("You chose Rock!")
print(rock)
print()
elif player_choice == 2:
print("You chose Paper!")
print(paper)
print()
elif player_choice == 3:
print("You chose Scissors!")
print(scissors)
print()
else:
print("That's....not even an option.\nNo game for you!")
# Assign a random hand to the computer
comp_choice = random.randint(1,3)
if comp_choice == 1:
print("PC chose Rock!")
print(rock)
print()
elif comp_choice == 2:
print("PC chose Paper!")
print(paper)
print()
elif comp_choice == 3:
print("PC chose Scissors!")
print(scissors)
print()
# Implement the rules
# Rock beats scissors
# Scissors beats Paper
# Paper beats Rock
if player_choice == 1:
if comp_choice == 1:
print("Both chose Rock.\nIt's a draw!")
elif comp_choice == 2:
print("PC won!")
elif comp_choice == 3:
print("You win!")
elif player_choice == 2:
if comp_choice == 1:
print("You win!")
elif comp_choice == 2:
print("Both chose Paper.\nIt's a draw!")
elif comp_choice == 3:
print("PC won!")
elif player_choice == 3:
if comp_choice == 1:
print("PC won!")
elif comp_choice == 2:
print("You win!")
elif comp_choice == 3:
print("Both chose Scissors.\nIt's a draw!")
print("\nThanks for playing!")
#fin |
ccb29ce6948dd0d8c8b171adcf4a5f46d51a96a7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/chtpro001/question2.py | 280 | 4.03125 | 4 | z = input('Enter a message:\n')
def pairing(z):
if len(z)==0 or len(z)==1:
return 0
elif z[0]==z[1]:
return 1 + pairing(z[2:])
elif z[0]!=z[1]:
return pairing(z[1:])
print('Number of pairs:',pairing(z))
|
7ec15b2148bc965392f971dfd414552bebf89be9 | kugg/Recordsticker | /ui/terminalui/__init__.py | 2,785 | 3.5625 | 4 | """
Text User interface for searching on discogs.
"""
import curses
from curses.textpad import Textbox, rectangle
def enter_is_terminate(x):
"""This thing makes enter terminate the input."""
if x == 10:
return 7
else:
return x
def compact(input, maxlen=70):
"""Creates a compact string from a dict."""
output = ""
for item in input.items():
if (len(output.split("\n")[-1]) + len(item)) >= maxlen:
output += "\n"
output += "{} ".format(item)
return output
class ResultBox:
"""A box that shows results."""
border = 1
data = ""
def __init__(self, window, y, x, height=7, width=70):
self.width = width
self.height = height
rectangle(window, y, x, y + self.height, x + self.width)
self.x = x + 1
self.y = y + 1
self.window = window
def write(self, data):
"""Stream writer for entering input?"""
for row in data.split("\n"):
self.window.addstr(self.y + self.border, self.x + self.border, row)
self.y += 1
self.data = data
self.window.refresh()
return True
class SearchBar:
"""A text input object."""
l8n_search_label = "Search:"
input_width = 50
input_height = 1
border = 1
y = 0
x = 0
def __init__(self, window):
"""Draw searchbar. Return TextBox."""
window.addstr(self.border, self.x, self.l8n_search_label)
editwin = curses.newwin(1, self.input_width, 1, len(self.l8n_search_label) + 2)
rectangle(window,
self.y,
len(self.l8n_search_label) + self.border,
self.border + self.input_height,
len(self.l8n_search_label) + self.border + self.input_width + self.border)
self.box = Textbox(editwin)
class Browser:
def __init__(self, window):
"""Create a basic empty element"""
self.window = window
self.results = []
self.searchbox = SearchBar(window)
window.refresh()
self.result_x = 0
self.result_y = self.searchbox.input_height + self.searchbox.border
self.query = ""
def add_result(self, item):
"""Append a result item to the screen."""
rows = len(item.keys())
result_box = ResultBox(self.window, self.result_y, self.result_x, rows)
self.result_y = rows + 3
result_box.write(compact(item))
self.results.append(result_box)
def wait_for_input(self):
"""Gather input and return it."""
self.searchbox.box.edit(enter_is_terminate)
self.query = self.searchbox.box.gather()
return self.query
def refresh(self):
"""Refresh the window."""
self.window.refresh()
|
9838e831860754198a972d15649aa6d2ef8e93c4 | mnevadom/pythonhelp | /3_colecciones/diccionarios.py | 676 | 3.9375 | 4 | # desordenados. Con clave y valor
diccionario = {}
diccionario = {"azul" : "blue", "amarillo" : "yellow"}
print(diccionario)
print(diccionario["azul"])
# agregar. y esto es desordenado siempre
diccionario["verde"] = "green"
diccionario["azul"] = "Bluuue"
del(diccionario["verde"])
diccionario2 = {"Mario": [22, 1.85], "Maria" : [31, 1.50]}
# o con tuplas tb
diccionario3 = {10: "Dybala", 7:"CR"}
print(diccionario3[10])
# si lo pones entre corchetes y no existe peta!
print(diccionario3.get(11, "no existe jugador con ese dorsal"))
print(10 in diccionario3)
print(diccionario3.keys())
print(diccionario3.values())
print(diccionario3)
print(diccionario3.items())
|
0ed1e580de30341b6b75d990e9a62996d370418a | claraxuxu/Python_joy | /image_to_code.py | 1,212 | 3.5625 | 4 |
from PIL import Image # use the Pillow library, for download : sudo pip install Pillow
import os
IMG= 'pics/cat.jpg'
path = os.path.join(os.getcwd(), IMG)
img = Image.open(path)
WIDTH = int(round(img.size[0] /10)) #get current image's width
HEIGHT = int (round(img.size[1] / 18)) # get current image's height and reduce its height as the interspace between each line is wider than the one between each character
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
def get_char(r,g,b,alpha=256):
if alpha == 0:
return ' '
length = len(ascii_char)
gray = int(0.21 * r + 0.72 * g + 0.07 * b) # give a standard to grey part
unit = (256.0 + 1) / length
return ascii_char[int(gray / unit)] # different degree of grey has their different character from the ascii_char list
if __name__=='__main__':
im = Image.open(IMG)
im = im.resize((WIDTH, HEIGHT), Image.NEAREST)
txt = ""
for i in range(HEIGHT):
for j in range(WIDTH):
txt += get_char(*im.getpixel((j, i)))
txt += '\n'
print (txt)
with open("result/output.txt", 'w') as f: #write the result in this file
f.write(txt) |
95f5dc1188949d6379cefe90d445b6a07b7a1fab | Prayatna-To-Prabhutva/Learn_Code | /Typing Speed.py | 2,254 | 3.953125 | 4 | import time
import enchant
import re
from WordCount import Word_Count
Test_Phrase = """At three o’clock precisely I was at Baker Street, but Holmes had not
yet returned. The landlady informed me that he had left the house
shortly after eight o’clock in the morning. I sat down beside the
fire, however, with the intention of awaiting him, however long he
might be. I was already deeply interested in his inquiry, for, though
it was surrounded by none of the grim and strange features which
were associated with the two crimes which I have already recorded,
still, the nature of the case and the exalted station of his client
gave it a character of its own. Indeed, apart from the nature of the
investigation which my friend had on hand, there was something in his
masterly grasp of a situation, and his keen, incisive reasoning, which
made it a pleasure to me to study his system of work, and to follow the
quick, subtle methods by which he disentangled the most inextricable
mysteries. So accustomed was I to his invariable success that the very
possibility of his failing had ceased to enter into my head."""
print("Hello! This is a test of your typing speed.")
User_Response = input("Are you ready?")
if User_Response == "":
print("All right! Here we go!")
print("Type the following the text and press enter when you are done:")
print("******SAMPLE TEXT FOR TYPING SPEED TEXT*****")
print(Test_Phrase)
print("******SAMPLE TEXT FOR TYPING SPEED TEXT*****")
Time_Start = input("Your time will start when you press Enter....")
T_Start = time.time()
User_Phrase = input("Timer Started. Press Enter at any point to stop the timer.")
T_End = time.time()
print("Calculating...Hold Tight!")
T_Total = round((T_End - T_Start),1)
User_Char_Count = len(User_Phrase)
User_Typing_Speed = round(((User_Char_Count/5)/T_Total),1)*60
User_Words = Word_Count(User_Phrase)
ErrCheck = enchant.Dict("en_US")
Errs = 0
for word in User_Words:
WordCheck = ErrCheck.check(word)
if not WordCheck:
Errs += 1
User_Typing_Speed_Corrected = User_Typing_Speed - Errs
print(f'You typed at {User_Typing_Speed_Corrected} WPM (Words Per Minute).\nYou made {Errs} mistakes.')
|
6f0d74cd0371f412525a345ce85eb720c9137bc5 | thomas-holmes/Euler | /36/36-4.py | 282 | 3.6875 | 4 | #!/usr/bin/python2.7
def is_palindrome(n):
nstr = str(n)
if nstr != str(nstr)[::-1]:
return False
b = str(bin(n))[2:]
return b == b[::-1]
if __name__ == "__main__":
total = 0
for x in range(1,1000000):
if is_palindrome(x):
total += x
print(total)
|
b0f98e6b2b3d66ecd40c796842559a2da99a88ad | rdiaz21129/python3_for_network_engineers | /dev/cisco_devices/dev_test.py | 683 | 3.71875 | 4 |
#https://stackoverflow.com/questions/8583615/how-to-check-if-a-line-has-one-of-the-strings-in-a-list
#https://stackoverflow.com/questions/29106881/check-if-any-of-the-items-of-a-list-is-in-a-line-of-a-file-if-not-then-write-t
# OPen and close file
f = open('serial_numbers.txt', 'r')
f_output = f.readlines()
f.close()
# Create lists that will be used in for loops
x = ['pizza', 'tacos', 'beer']
# For variable in f_output
for line in f_output:
line = line.strip() # remove blank lines
if any(newvar in line for newvar in x):
print (line)
'''
food = ("pizza")
f = open("createdFile.txt", "w")
f.write("hello,\nopening file and closing it\n")
f.close()
'''
|
45beddcca3ec5081f0c4009df741238717591e8f | Eacaen/diff_Code_Learn | /python/源代码/第八章/8_1.py | 410 | 3.6875 | 4 | # 类的创建
class Fruit::
def __init__(self): # __init__为类的构造函数,后面会详细介绍
self.name = name
self.color = color
def grow(self): # 定义grow函数,类中的函数称为方法
print "Fruit grow ..."
if __name__ == "__main__":
fruit = Fruit() # 实例化
fruit.grow() # 调用grow()方法
|
cc9ab0aa49aa2e30dd6432a59f8b976cf0220334 | yuenliou/leetcode | /141-linked-list-cycle.py | 2,755 | 4 | 4 | #!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
from datatype.list_node import ListNode
def hasCycle(head: ListNode) -> bool:
"""
头尾相接的循环链表:p->next == head
6型循环链表:内外遍历 > has表(集合/删除) > 双指针(快慢指针)
双指针问题:翻转链表(前后指针),获取倒数第k个元素(k间距指针),获取中间位置的元素(快慢指针),判断链表是否存在环(快慢指针),判断环的长度(第二次相遇的移动次数)
"""
fast = slow = head
# 不同:为什么我们要规定初始时慢指针在位置 head,快指针在位置 head.next,而不是两个指针都在位置 head(即与「乌龟」和「兔子」中的叙述相同)?
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast: return True
return False
def hasCycle_hash(head: ListNode) -> bool:
# hash表 比内外循环效率高点
seen = set()
while head:
if head in seen:
return True
seen.add(head)
head = head.next
return False
def main():
node1 = ListNode(3)
node2 = ListNode(2)
node1.next = node2
node3 = ListNode(0)
node2.next = node3
node4 = ListNode(-4)
node3.next = node4
# node5 = ListNode(2)
# node4.next = node5
node4.next = node2
ret = hasCycle(node1)
print(ret)
'''141. 环形链表
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
示例 1:
输入:head = [3,2,0,-4,2], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2,1], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
提示:
链表中节点的数目范围是 [0, 104]
-105 <= Node.val <= 105
pos 为 -1 或者链表中的一个 有效索引 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
if __name__ == '__main__':
main()
|
acf94f0e560a9a33bb2945aa31ee529481bf6f1e | seniortesting/cheatsheet-startup-parent | /cheatsheet-startup-python/example-basic/builtin/types-fun.py | 353 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import types
def test():
print('test')
if __name__ == '__main__':
isfun=type(test)==types.FunctionType
print('isfun: ',isfun)
isbuiltin=type(abs)==types.BuiltinFunctionType
print(isbuiltin)
islamba=type(lambda x:x+3)==types.LambdaType
print(islamba)
# 动态设置方法
|
85b6caf8616a4868b52dd1ee7076b93ab18a226b | Shadat-tonmoy/DeepLearningNanoDegreeUdacity | /NeuralNetworks/projects/SentimentAnalysis/NLTK/03.Stemming.py | 1,050 | 4.15625 | 4 | from nltk.stem import PorterStemmer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
'''
Stemming is the process of cut off sufix like ing, ed, s, es etc from words and get back the root word
For example, Write, Writing, Written, Writes will be stemmed to the root same word Write
NLTK use PorterStemmer to perform this stemming operation
'''
porter_stemmer = PorterStemmer()
example_words = ["Write", "Writing", "Written", "Writes", "Writer"]
for word in example_words:
print(porter_stemmer.stem(word))
example_sentence = "It is very important to be pythonly while you are pythoning with python. All pythoners have pythoned poorly at least once"
stop_words = set(stopwords.words())
words = word_tokenize(example_sentence)
print("Original Words\n",words)
filtered_words = [word for word in words if word not in stop_words]
print("Filtered Words\n",filtered_words)
stemmed_words = []
for word in filtered_words:
stemmed_words.append(porter_stemmer.stem(word))
print("Stemmed Words\n",stemmed_words)
|
511c1098457bf1728453b0d5243e2fc183a7bb1b | samescolas/web-scraping | /src/setup.py | 1,148 | 3.6875 | 4 | import sys
import os
import pickle
def prompt(q):
return input("{}\n>> ".format(q))
try:
config = pickle.load( open("config.pickle", 'rb') )
except:
config = {
'image_dir': '',
'data_dir': ''
}
image_dir = prompt('Where would you like the images saved?')
while not os.path.isdir(image_dir):
yes = prompt("Directory {} does not exist. Would you like to create it now? [Y/N]".format(image_dir))
if yes == 'Y' or yes == 'y':
os.mkdir("./{}".format(image_dir))
break
else:
image_dir = prompt('Where would you like the images saved? Please indicate a directory.')
print('Thank you.')
config['image_dir'] = image_dir
data_dir = prompt('Where would you like the data saved?')
while not os.path.isdir(data_dir):
yes = prompt("Directory {} does not exist. Would you like to create it now? [Y/N]".format(data_dir))
if yes == 'Y' or yes == 'y':
os.mkdir("./{}".format(data_dir))
break
else:
data_dir = prompt('Where would you like the data saved? Please indicate a directory.')
print('Thank you.')
config['data_dir'] = data_dir
with open("config.pickle", 'wb') as fd:
pickle.dump(config, fd, protocol=pickle.HIGHEST_PROTOCOL)
|
e95f209bae96867f64dcd72b62cd61edf2587522 | CalumDoughtyYear3/Functions | /exercise2.8.py | 4,903 | 4 | 4 | import math
### ADD
def add():
first = int(input("Please input first number: "))
second = int(input("Please input second number: "))
answer = first + second
print("Answer = " + str(answer))
### SUBTRACT
def subtract():
first = int(input("Please input first number: "))
second = int(input("Please input second number: "))
answer = first - second
print("Answer = " + str(answer))
### MULTIPLY
def multiply():
first = int(input("Please input first number: "))
second = int(input("Please input second number: "))
answer = first * second
print("Answer = " + str(answer))
### DIVIDE
def divide():
first = int(input("Please input first number: "))
second = int(input("Please input second number: "))
answer = first / second
print("Answer = " + str(answer))
### SQUAREROOT
def squareroot():
first = int(input("Please input a number: "))
answer = math.sqrt(first) # gets the square root
print("Answer = " + str(answer))
### VOLUME
def volume():
radius = int(input("Please input the RADIUS in metres: "))
height = int(input("Please input the HEIGHT in metres: "))
answer = math.pi * ((radius*radius) * height)
print("Answer = " + str(answer) + "m^3")
### WALLPAPER PROBLEM
def wallpaper():
print("ROOM")
height = int(input("Please input the HEIGHT in metres: "))
length = int(input("Please input the LENGTH in metres: "))
width = int(input("Please input the WIDTH in metres: "))
opp1 = 2 * (height * length) #finds the metres squared of 2 opposite walls
opp2 = 2 * (height * width) #finds the metres squared of the other walls
total = opp1 + opp2
print("DOORS/WINDOWS")
numbers = int(input("How many doors/windows do you have in this room?: "))
j = 0
for i in range(numbers):
j += 1
print("area" + str(j))
heighty = int(input("Please input the HEIGHT in metres: "))
widthy = int(input("Please input the WIDTH in metres: "))
gaps = heighty * widthy
total -= gaps
print("\n")
print("Surface area to cover = " + str(total) + "m^2")
paper = math.ceil(total / 5)
print("Wallpaper needed = " + str(paper) + " rolls")
### COMPOUND
#https://www.thecalculatorsite.com/articles/finance/compound-interest-formula.php
#https://www.geeksforgeeks.org/python-program-for-compound-interest/
def compound():
principal = float(input("Initial investment sum: "))
term = float(input("Term time (in yrs): "))
interestRate = float(input("Interest rate: "))
#temp = (1 + (interestRate/1))**term
finalAmount = principal * (pow((1 + interestRate/100), term))
print("Principal sum = " + str(round(principal, 2)))
compoundInterest = finalAmount - principal
print("Interest accumulated = " + str(round(compoundInterest, 2)))
print("Balance Total = " + str(round(finalAmount, 2)))
############################# MENU
checker = 0
while checker == 0:
checker = 0
print("Arithmetic Demo")
print("================")
print("1. Add two numbers")
print("2. Subtract one number from another")
print("3. Multiply two numbers together")
print("4. Divide one number by another")
print("5. Find the square root of a number")
print("6. Exit")
print("7. Calculate volume of cylindrical fuel tank")
print("8. Wallpaper problem")
print("9. Compound interest")
print("\n")
print("Please make your choice:")
choice = int(input(">>> "))
if choice == 1:
#checker = 1
add()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 2:
#checker = 1
subtract()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 3:
#checker = 1
multiply()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 4:
#checker = 1
divide()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 5:
#checker = 1
squareroot()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 6:
quit()
elif choice == 7:
#checker = 1
volume()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 8:
#checker = 1
wallpaper()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
elif choice == 9:
#checker = 1
compound()
print("\n")
input("Press Enter to continue...")
print("\n")
continue
else:
print("Please choose a valid menu option")
print("\n") |
dac3554d44d3fc5585e59f8f2e1cb25efdca3763 | stephen1776/Data-Structures-and-Algorithms | /02 - Data Structures/01 - Basic Data Structures/check_brackets.py | 1,688 | 3.796875 | 4 | # python3
'''
Input Format. Input contains one string 𝑆 which consists of big and small latin letters, digits, punctuation
marks and brackets from the set []{}().
Output Format. If the code in 𝑆 uses brackets correctly, output “Success" (without the quotes). Otherwise,
output the 1-based index of the first unmatched closing bracket, and if there are no unmatched closing
brackets, output the 1-based index of the first unmatched opening bracket.
'''
import sys
class Bracket:
def __init__(self, bracket_type, position):
self.bracket_type = bracket_type
self.position = position
def Match(self, c):
if self.bracket_type == '[' and c == ']':
return True
if self.bracket_type == '{' and c == '}':
return True
if self.bracket_type == '(' and c == ')':
return True
return False
if __name__ == "__main__":
text = sys.stdin.read()
opening_brackets_stack = []
for i, next in enumerate(text):
if next == '(' or next == '[' or next == '{':
# Process opening bracket
opening_brackets_stack.append(Bracket(next, i))
elif next == ')' or next == ']' or next == '}':
# Process closing bracket
if len(opening_brackets_stack) == 0:
opening_brackets_stack.append(Bracket(next, i))
break
top = opening_brackets_stack.pop()
if not top.Match(next):
opening_brackets_stack.append(Bracket(next, i))
break
if len(opening_brackets_stack) == 0:
print("Success")
else:
print(opening_brackets_stack.pop().position + 1) |
e0bc5ada09bbb906622c181c757a297733283cb2 | koking0/Algorithm | /LeetCode/Problems/139. Word Break/139. Word Break.py | 842 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-H -*-
# @Time : 2020/6/25 7:59
# @File : 139. Word Break.py
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Alex 007
# >>> QQ : 2426671397
# >>> Mail : alex18812649207@gmail.com
# >>> Github : https://github.com/koking0
# >>> Blog : https://alex007.blog.csdn.net/
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
length = len(s)
if not wordDict:
return not s
dp = [False] * (length + 1)
dp[0] = True
for i in range(1, length + 1):
for j in range(i - 1, -1, -1):
if dp[j] and s[j: i] in wordDict:
dp[i] = True
break
return dp[-1]
|
63882823dd751b08e3edf3322965ddb3feeec518 | willianjeff/estrutura_sequencial | /Aula 1 - Tarefa_5.py | 121 | 3.765625 | 4 | metros = 0
metros = int(input('Informe a quantidade de metros: '))
print ('O valor em centimetros é = ', metros * 100) |
65dc974fbbebd9fe50bc98f4f9c00cd568ddef75 | mgermaine93/python-playground | /python-coding-bat/list-1/sum2/test_module.py | 1,679 | 3.890625 | 4 | import unittest
from sum2 import sum2
class UnitTests(unittest.TestCase):
def test_1_2_3_returns_3(self):
actual = sum2([1, 2, 3])
expected = 3
self.assertEqual(
actual, expected, 'Expected calling sum2() with [1, 2, 3] to return 3')
def test_1_1_returns_2(self):
actual = sum2([1, 1])
expected = 2
self.assertEqual(
actual, expected, 'Expected calling sum2() with [1, 1] to return 2')
def test_1_1_1_1_returns_2(self):
actual = sum2([1, 1, 1, 1])
expected = 2
self.assertEqual(
actual, expected, 'Expected calling sum2() with [1, 1, 1, 1] to return 2')
def test_1_2_returns_3(self):
actual = sum2([1, 2])
expected = 3
self.assertEqual(
actual, expected, 'Expected calling sum2() with [1, 2] to return 3')
def test_1_returns_1(self):
actual = sum2([1])
expected = 1
self.assertEqual(
actual, expected, 'Expected calling sum2() with [1] to return 1')
def test_blank_returns_0(self):
actual = sum2([])
expected = 0
self.assertEqual(
actual, expected, 'Expected calling sum2() with [] to return 0')
def test_4_5_6_returns_9(self):
actual = sum2([4, 5, 6])
expected = 9
self.assertEqual(
actual, expected, 'Expected calling sum2() with [4, 5, 6] to return 9')
def test_4_returns_4(self):
actual = sum2([4])
expected = 4
self.assertEqual(
actual, expected, 'Expected calling sum2() with [4] to return 4')
if __name__ == "__main__":
unittest.main()
|
1530d904b2e4708da3fc107c25bc54b4431de429 | reinderien/advent | /2017/03/03.py | 1,737 | 3.65625 | 4 | #!/usr/bin/env python3
from math import sqrt
i = 325489
def p1():
def coords(i):
"""
This uses analytical expressions for the size of interior square of the spiral and the
coordinates of the current cell based only on the current index. The expressions are heavily
piecewise but this piecewise behaviour can be entirely derived from min/max/abs.
This is O(1), yaaay
"""
w = ((sqrt(i-1)-1)//2)*2 + 1 # Width of inner square
edge = (w+1)//2 # Max displacement from centre
x = abs(w**2 + 2.5*w + 2.5 - i) - w - 1
y = w + 1 - abs(w**2 + 1.5*w + 1.5 - i)
x = min(edge, max(-edge, x))
y = min(edge, max(-edge, y))
return int(x), int(y)
def taxi(x, y):
return abs(x) + abs(y)
assert(taxi(*coords(1)) == 0)
assert(taxi(*coords(12)) == 3)
assert(taxi(*coords(23)) == 2)
assert(taxi(*coords(1024)) == 31)
c = coords(i)
d = taxi(*c) # 552
print('Part 1:')
print('i=%d x,y=(%d,%d) d=%d' % (i, *c, d))
p1()
def p2():
"""
Part 2: Meh. Do the slow thing
The infinite 2D space does not need to be represented in memory; only the previous and current
edges of the spiral.
"""
edges = [[1], [1], [1], [1,1]]
edge_c = [1]
i_edge = 0
while True:
edge_p = edges[i_edge]
edge_c = edge_c[-1:]
edges[i_edge] = edge_c
for p in range(len(edge_p)):
total = sum((edge_c[-1], *edge_p[p:p+3]))
if total > i:
print('Part 2:', total) # 330785
return
edge_c.append(total)
i_edge = (i_edge+1) % 4
edges[i_edge].insert(0, edge_c[-2])
p2()
|
667f5431676171ec885a009196dcff8c6e241e92 | sunzhongyuan/learnPython | /first.py | 237 | 3.859375 | 4 | print("--------------------游戏??-------------------")
temp = input("请在心里猜一个数字:")
guess = int(temp)
if guess == 8:
print("猜中了!!")
print("是8")
else:
print("猜错了")
print("游戏结束")
|
5a0e5b5a87a087de246b1dd4f72e60d16ca6427a | Code-Wen/LeetCode_Notes | /996.number-of-squareful-arrays.py | 1,303 | 3.5625 | 4 | #
# @lc app=leetcode id=996 lang=python3
#
# [996] Number of Squareful Arrays
#
# https://leetcode.com/problems/number-of-squareful-arrays/description/
#
# algorithms
# Hard (47.61%)
# Likes: 277
# Dislikes: 19
# Total Accepted: 11.5K
# Total Submissions: 24.2K
# Testcase Example: '[1,17,8]'
#
# Given an array A of non-negative integers, the array is squareful if for
# every pair of adjacent elements, their sum is a perfect square.
#
# Return the number of permutations of A that are squareful. Two permutations
# A1 and A2 differ if and only if there is some index i such that A1[i] !=
# A2[i].
#
#
#
# Example 1:
#
#
# Input: [1,17,8]
# Output: 2
# Explanation:
# [1,8,17] and [17,8,1] are the valid permutations.
#
#
# Example 2:
#
#
# Input: [2,2,2]
# Output: 1
#
#
#
#
# Note:
#
#
# 1 <= A.length <= 12
# 0 <= A[i] <= 1e9
#
#
# @lc code=start
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
c = collections.Counter(A)
cand = {i: {j for j in c if int((i + j)**0.5) ** 2 == i + j} for i in c}
def dfs(x, left=len(A) - 1):
c[x] -= 1
count = sum(dfs(y, left - 1) for y in cand[x] if c[y]) if left else 1
c[x] += 1
return count
return sum(map(dfs, c))
# @lc code=end
|
bba08e55984af20a9311113564f852161ea883fe | cnin/python-leetcode | /solutions/solution2.py | 918 | 3.75 | 4 | #encoding=utf8
"""
请实现一个函数,将一个字符串中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.经过替换之后的字符串为We%20Are%20Happy。
时间限制:1秒 空间限制:32768K
"""
class Solution2(object):
def replace_space(self, s):
return s.replace(' ','%20')
def replace_space_alter(self, s):
str_ = ''
for char in s:
str_ = str_ + '%20' if char == ' ' else str_ + char
return str_
#根据python代码规范
#应当尽可能少的使用+=来组合字符串
#规范推荐使用join list方法
#http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/#id12
def replace_space_alter_2(self, s):
str_list = []
for char in s:
str_list.append('%20' if char == ' ' else char)
return ''.join(str_list) |
75c174f174668f75a0ee6cb0f8458070042b13f2 | JoanChirinos/AdventOfCode | /2019/day1_1.py | 228 | 3.875 | 4 | def calculate(mass):
return mass // 3 - 2
def go():
with open('day1_INPUT.txt') as f:
nums = f.read()
total = 0
for num in nums.split():
total += calculate(int(num))
print(total)
|
93e020bba6b216ad0b3342254e197a6eec1e96fc | jgam/hackerrank | /arrays/newchaos.py | 739 | 3.609375 | 4 | #this is to use bubble sort
def minimumBribes(queue):
lastIndex = len(queue) - 1
swaps = 0
swaped = False
# check if the queue is too chaotic
for i, v in enumerate(queue):
#finding chaotic here with index pointer moving 2 ahead
if (v - 1) - i > 2:
return "Too chaotic"
# bubble sort
for i in range(0, lastIndex):
for j in range(0, lastIndex):
#comps += 1
if queue[j] > queue[j+1]:
temp = queue[j]
queue[j] = queue[j+1]
queue[j+1] = temp
swaps += 1
swaped = True
if swaped:
swaped = False
else:
break
return swaps
|
bd109475043269f02ef0956f2a443caabae42765 | theoctober19th/ds-algorithms | /examples/doubly_linked_list.py | 844 | 4.1875 | 4 | from data_structures.doubly_linked_list import DoublyLinkedList
# creating a doubly linked list
animals = DoublyLinkedList()
print('Adding a few elements on the front...')
animals.insert_front('Cow')
animals.insert_front('Tiger')
animals.display()
print('\nAdding a few elements on the back...')
animals.insert_back('Lion')
animals.insert_back('Wolf')
animals.display()
print('\nAdding an item after Lion')
animals.insert_after('Lion', 'Lioness')
animals.display()
print('\nRemoving a few items from beginning..')
animals.remove_front()
animals.remove_front()
animals.display()
print('\nRemoving Lioness from the list')
animals.remove('Lioness')
animals.display()
print('\nRemoving a few items from the back')
animals.remove_back()
animals.remove_back()
animals.display()
print('\nThere are {} items on the list.'.format(animals.size))
|
d7271e903e70a36e34cdad99719577af07d2035f | ymirthor/T-201-GSKI | /Midterms/Æfing fyrir hlutapórf 2/Arraydeque.py | 2,144 | 3.53125 | 4 | class Arraydeque:
def __init__(self):
self.capacity = 4
self.array = [0] * self.capacity
self.size = 0
self.start = 0
self.end = 0
def __str__(self):
ret_str = ""
walk = self.start
for i in range(self.size):
ret_str += str(self.array[walk]) + " "
walk = (walk + 1) % (self.capacity)
return ret_str
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == self.capacity
def get_end(self):
self.end = ((self.start + self.size) % self.capacity) - 1
def get_size(self):
return self.size
def push_back(self, value):
if self.size == self.capacity:
self.resize(False)
self.size += 1
self.array[self.get_end()] = value
def push_front(self, value):
if self.size == self.capacity:
self.resize(True)
else:
self.start = (self.start - 1) % self.capacity
self.size += 1
self.array[self.start] = value
def pop_back(self):
if self.is_empty():
return
ret_val = self.array[self.get_end()]
self.array[self.get_end()] = 0
self.size -= 1
return ret_val
def pop_front(self):
pass
def get_size(self):
pass
def resize(self, pushFront = False):
self.capacity *= 2
new_arr = [0] * self.capacity
if not pushFront:
start = 0
else:
start = 1
end = self.size if not pushFront else self.size + 1
walk = self.start
for i in range(start, end):
new_arr[i] = self.array[walk]
walk = (walk + 1) % self.size
self.array = new_arr
self.start = 0
if __name__ == "__main__":
lol = Arraydeque()
lol.push_front("REND")
lol.push_front("ANAL")
lol.push_front("ANAL")
lol.push_front("ANAL")
lol.push_front("ANAL")
lol.push_front("ANAL")
lol.push_front("ANAL")
lol.push_front("ANAL")
lol.push_front("ANAL")
print(lol) |
af1228eea2280b0896d6a693e16213885743425f | mniju/Datastructures | /EPI book/9.2 is_tree_symmetric.py | 1,380 | 4.3125 | 4 |
class BinaryTreeNode:
# Utility function to create new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_symmetric(tree:BinaryTreeNode)->bool:
def check_symmetric(subtree_0,subtree_1):
if not subtree_0 and not subtree_1:
return True
elif subtree_0 and subtree_1:
return(subtree_0.data == subtree_1.data
and check_symmetric(subtree_0.left,subtree_1.right)
and check_symmetric(subtree_0.right,subtree_1.left))
return False
return not tree or check_symmetric(tree.left,tree.right)
# Drivercode
#https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/
"""
Symmetric Tree
1
/ \
2 2
/ \ / \
3 4 4 3
"""
root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(2)
root.left.left = BinaryTreeNode(3)
root.left.right = BinaryTreeNode(4)
root.right.left = BinaryTreeNode(4)
root.right.right = BinaryTreeNode(3)
print(f' Is Binary tree symmetric:{is_symmetric(root)}')
"""
Non Symmetric Tree
1
/ \
2 2
\ \
3 3
"""
root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(2)
root.left.right = BinaryTreeNode(3)
root.right.right = BinaryTreeNode(3)
print(f' Is Binary tree symmetric:{is_symmetric(root)}') |
2b3fcfa43684186f07597d964b0546e18c38a0b4 | RamonCris222/Ramon-Cristian | /questao_12_listas.py | 411 | 3.71875 | 4 | a = []
b = []
c = []
print("Digite os valores da primeira lista: ")
for i in range(10):
a.append(float(input()))
print("Digite os valores da segunda lista: ")
for i in range(10):
b.append(float(input()))
print("Digite os valores da terceira lista: ")
for i in range(10):
c.append(float(input()))
d = []
for x in range(10):
d += [a[x]]
d += [b[x]]
d += [c[x]]
|
88cd3bb80fcae3d0b2630154be9887310cbe9ea9 | wiktoriamroczko/pp1 | /02-ControlStructures/zadanie49.py | 471 | 3.921875 | 4 | print ('| PN | WT | SR | CZ | PT | SB | ND |')
nrDniaTygodnia =3
print ('| '*nrDniaTygodnia, end='')
for i in range(1, 31):
if i < 10:
print ('|', i, end=' ')
elif i >=10:
print ('|', i, end=' ')
if i == 7-nrDniaTygodnia:
print ('|')
if i == 14-nrDniaTygodnia:
print ('|')
if i == 21-nrDniaTygodnia:
print ('|')
if i == 28-nrDniaTygodnia:
print ('|')
if i==30:
print ('|')
|
d7b81a5a8f0df17fc3106e7899a588f0bbe5447e | JiungChoi/Baekjoon | /baekjoon_10809_other.py | 150 | 3.703125 | 4 | ary = list(input())
for i in range(97,123):
if chr(i) in ary:
print(ary.index(chr(i)), end=' ')
else : print(-1, end=' ')
|
2c13e487abd8f6ebb73386de7b707853761519a2 | lukaszsi/Automate-the-Boring-Stuff---practical-tasks | /Chapter 8/CH08_mad_libs.py | 792 | 4.1875 | 4 | #! Python3
'''Script that finds words like ADJECTIVE, NOUN, ADVERB, VERB
in a given text and enables to override them. '''
import re
# opens .txt file
textFile = open(input('Name of the file? '))
newTextFile = textFile.read()
textFile.close()
# regexes and changing of the text
words = ['ADJECTIVE', 'NOUN', 'ADVERB', 'VERB']
while True:
checkFile = newTextFile
for i in words:
if re.compile(i).search(newTextFile) != None:
change = input('please enter '+ i.lower())
newTextFile = re.compile(i).sub(change, newTextFile, count=1)
if checkFile == newTextFile:
break
# Prints changed text and saves it as 'newfile.txt'.
print(newTextFile)
newFile = open('newfile.txt', 'w')
newFile.write(newTextFile)
newFile.close()
|
ac073bbfd0591d73787ef7d0a6e5ead2b4ce6f1e | ozcayci/python_examples | /examples_two/quest_03.py | 323 | 3.96875 | 4 | def isIntAndPositive(val):
if val.isdigit():
return True
number = input("Please a give number: ")
if isIntAndPositive(number):
number = int(number)
total = 0
for i in range(0, 3):
total += number * int("1" * (i + 1))
print(total)
else:
print("Invalid value")
|
fa23fb8a8de28c3e6eb8e5f91526c022191c7b49 | cadelau/NN_EECS_445 | /visualize_cnn.py | 2,012 | 3.546875 | 4 | """
EECS 445 - Introduction to Machine Learning
Winter 2019 - Project 2
Visualize CNN
This will produce visualizations of the activations of the
first convolutional layer and save them to file.
Usage: python visualize_cnn.py
"""
import torch
import torch.nn.functional as F
import numpy as np
import utils
from dataset import get_train_val_test_loaders
from model.cnn import CNN
from train_common import *
from utils import config
from scipy.misc import imread
import utils
import copy
import math
import pandas as pd
from matplotlib import pyplot as plt
def visualize_layer1_activations(i):
xi, yi = tr_loader.dataset[i]
xi = xi.view((1,3,config('image_dim'),config('image_dim')))
zi = F.relu(model.conv1(xi))
zi = zi.detach().numpy()[0]
sort_mask = np.argsort(model.conv1.weight.detach().numpy().mean(axis=(1,2,3)))
zi = zi[sort_mask]
fig, axes = plt.subplots(4, 4, figsize=(10,10))
for i, ax in enumerate(axes.ravel()):
ax.axis('off')
im = ax.imshow(zi[i], cmap='gray')
fig.suptitle('Layer 1 activations, y={}'.format(yi))
fig.savefig('CNN_viz1_{}.png'.format(yi), dpi=200, bbox_inches='tight')
if __name__ == '__main__':
# Attempts to restore from checkpoint
print('Loading cnn...')
model = CNN()
model, start_epoch, _ = restore_checkpoint(model, config('cnn.checkpoint'),
force=True)
tr_loader, _, _, _ = get_train_val_test_loaders(
num_classes=config('cnn.num_classes'))
# Saving input images in original resolution
metadata = pd.read_csv(config('csv_file'))
for idx in [20, 13, 14]:
filename = os.path.join(
config('image_path'), metadata.loc[idx, 'filename'])
plt.imshow(imread(filename))
plt.axis('off')
plt.savefig('CNN_viz0_{}.png'.format(int(
metadata.loc[idx, 'numeric_label'])),
dpi=200, bbox_inches='tight')
# Saving layer activations
for i in [8, 9, 10]:
visualize_layer1_activations(i)
|
ebe65aff36fa0cb5dd914b65f795309baa7bd75d | JaeHeee/algorithm | /baekjoon_python/10866.py | 952 | 3.765625 | 4 | #10866 Deque
count = int(input(''))
deque = []
for i in range(0,count):
command= str(input(''))
if "push_front" in command:
number = int(command[10:])
deque.insert(0,number)
elif "push_back" in command:
number = int(command[10:])
deque.append(number)
elif command == "pop_front":
if len(deque)==0:
print(-1)
else:
print(deque.pop(0))
elif command == "pop_back":
if len(deque)==0:
print(-1)
else:
print(deque.pop())
elif command == "size":
print(len(deque))
elif command == "empty":
if len(deque)==0:
print(1)
else:
print(0)
elif command == "front":
if len(deque)==0:
print(-1)
else:
print(deque[0])
elif command == "back":
if len(deque)==0:
print(-1)
else:
print(deque[-1])
|
b0204c0deab0e0e25166fb57e311627870c911c8 | Amirreza5/Class | /example_string02.py | 584 | 3.984375 | 4 | x = 'maryam is a student'
name = 'Samira'
list_name = ['Amire', 'Lena', 'Amirh', 'moein']
#1)length01 = len(x)
#print(length01)
#for character in x:
#if character == 'm':
#print(character)
#2)print('maryam' in x)
#3)print(x[0:6])
#4)print(x.capitalize())
#5)print(x.upper())
#6)print(x.casefold())
#7)print(x.lower())
#8)print(name.center(100))
#9)print(name.count('a'))
#10)out = name.endswith('a')
#print(out)
#11)c = name.index('is')
#print(c)
#12)c = name.find('is')
#print(c)
#13)c = '*'.join(list_name)
#print(c)
#14)c = x.split()
#print(c) |
c9693b4cf2204956cefd5b394b5397aa821db320 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2706/60781/280206.py | 274 | 3.90625 | 4 | str1=input()
pan=0
if(str1=='[["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]'):
print([["John", 'johnsmith@mail.com', 'john00@mail.com', 'john_newyork@mail.com'], ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]])
pan=1
if(pan==0):
print(str1) |
a89a60b286af90a01447471f18579f1512a3c20b | blhwong/algos_py | /leet/merge_two_sorted_lists/main.py | 1,048 | 3.875 | 4 | from data_structures.list_node import ListNode
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
curr1 = l1
curr2 = l2
head = None
tail = None
def add_to_tail(val):
nonlocal head
nonlocal tail
if not head:
head = ListNode(val)
tail = head
else:
if not head.next:
head.next = tail
tail.next = ListNode(val)
tail = tail.next
while curr1 and curr2:
if curr1.val < curr2.val:
add_to_tail(curr1.val)
curr1 = curr1.next
else:
add_to_tail(curr2.val)
curr2 = curr2.next
if curr1:
if tail:
tail.next = curr1
else:
return curr1
elif curr2:
if tail:
tail.next = curr2
else:
return curr2
return head
|
fa86c6e6bee5af05880acb2b8bee828fa1372fc9 | JasonTLM/multiprocess_spider | /queue_get_put.py | 923 | 3.59375 | 4 | # coding=utf-8
"""
queue中,put和get的参数里默认拥有一个block参数,默认为True,即为在插入队列为满或者取出为空时
默认为阻塞状态,等待取出取出或者插入数据。
"""
from queue import Queue
import time
import threading
def put_value(q):
index = 0
# another = 1
while True:
q.put(index)
# q.put(another)
index += 1
# another += 1
time.sleep(2)
def another_put_value(q):
another = 2
while True:
q.put(another)
another += 2
time.sleep(1)
def get_value(q):
while True:
print(q.get())
def main():
q = Queue(5)
p = threading.Thread(target=get_value, args=(q, ))
a_p = threading.Thread(target=another_put_value, args=(q, ))
g = threading.Thread(target=put_value, args=(q, ))
p.start()
a_p.start()
g.start()
if __name__ == '__main__':
main() |
b0ea78999e4b9c95ac84162c46aba65e692a93a6 | drcyfai/Computer-Vision | /5thCV_ClassicCV_Project1_ImageStitching_by_ChenYaofeng.py | 5,983 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### AI 第五期 CV 课 Classic CV project 1: Image Stitching
# #### Student: Chen Yaofeng
# In[ ]:
"""
The image stitching algorithm consists of four steps:
Step #1: Detect keypoints (DoG, Harris, etc.) and extract local invariant descriptors (SIFT, SURF, etc.) from the two input images.
Step #2: Match the descriptors between the two images.
Step #3: Use the RANSAC algorithm to estimate a homography matrix using our matched feature vectors.
Step #4: Apply a warping transformation using the homography matrix obtained from Step #3.
"""
# In[1]:
import numpy as np
import cv2
# In[33]:
from matplotlib import pyplot as plt
import random
# In[13]:
def is_CV_correct(major):
openCV_majorVersion = int(cv2.__version__.split(".")[0])
if openCV_majorVersion == major:
print('This program need to use OpenCV3.')
print('Your OpenCV is OpenCV3.')
else:
print('This program need to use OpenCV3.')
print('Your OpenCV is not OpenCV3. Sorry.')
print('cv2.__version__ is:', cv2.__version__)
return
# In[14]:
is_CV_correct(3)
# In[15]:
# read two images for stitching
img_ = cv2.imread('original_image_right.jpg')
# img_ = cv2.resize(img_, (0,0), fx=1, fy=1)
img1 = cv2.cvtColor(img_,cv2.COLOR_BGR2GRAY)
img = cv2.imread('original_image_left.jpg')
# img = cv2.resize(img, (0,0), fx=1, fy=1)
img2 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# In[16]:
cv2.imshow('Left Image',img)
cv2.imshow('Right Image',img_)
key = cv2.waitKey()
if key == 27:
cv2.destroyAllWindows()
# In[17]:
"""
Step #1: Detect keypoints (DoG, Harris, etc.) and extract local invariant descriptors (SIFT, SURF, etc.)
from the two input images
"""
## 1. 对两幅图像分别进行关键点检测,比如用SIFT. 【大家完全可以尝试别的关键点】
## find SIFT Keypoints and Descriptors
## https://docs.opencv.org/3.1.0/da/df5/tutorial_py_sift_intro.html
sift = cv2.xfeatures2d.SIFT_create()
# find the key points and descriptors with SIFT
# Here kp will be a list of keypoints and des is a numpy array of shape Number_of_Keypoints×128.
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
# In[18]:
## """
## show the keypoints on the two images
img_sift_right = cv2.drawKeypoints(img_, kp1, outImage=np.array([]), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
img_sift_left = cv2.drawKeypoints(img, kp2, outImage=np.array([]), flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
cv2.imshow('left image',img_sift_left)
cv2.imshow('right image',img_sift_right)
key = cv2.waitKey()
if key == 27:
cv2.destroyAllWindows()
### """
# In[26]:
"""
Step #2: Match the descriptors between the two images.
"""
FLANN_INDEX_KDTREE = 1 ## FLANN_INDEX_KDTREE = 0 0 or 1 does not change the results.
### FLANN_INDEX_KDTREE:
### (The upper case should have been a hint that these are meant as descriptive labels of fixed integer values.)
### https://stackoverflow.com/questions/42397009/what-values-does-the-algorithm-parametre-take-in-opencvs-flannbasedmatcher-cons
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
match = cv2.FlannBasedMatcher(index_params, search_params)
matches = match.knnMatch(des1,des2,k=2)
## Select the top best matches for each descriptor of an image.
## filter out through all the matches to obtain the best ones by applying ratio test using the top 2 matches obtained above.
good = []
for m,n in matches:
if m.distance < 0.03*n.distance:
good.append(m)
# In[27]:
"""
Step #3: Use the RANSAC algorithm to estimate a homography matrix using our matched feature vectors.
"""
"""
Now we set a condition that atleast 10 matches (defined by MIN_MATCH_COUNT) are to be there to find the object.
Otherwise simply show a message saying not enough matches are present.
If enough matches are found, we extract the locations of matched keypoints in both the images.
They are passed to find the perpective transformation. Once we get this 3x3 transformation matrix,
we use it to transform the corners of queryImage to corresponding points in trainImage.
"""
MIN_MATCH_COUNT = 10
if len(good) > MIN_MATCH_COUNT:
src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
h,w = img1.shape
pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
dst = cv2.perspectiveTransform(pts,M)
img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)
cv2.imshow("original_image_overlapping.jpg", img2)
key = cv2.waitKey()
if key == 27:
cv2.destroyAllWindows()
else:
print ("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))
# In[28]:
"""
Step #4: Apply a warping transformation using the homography matrix obtained from Step #3.
"""
dst = cv2.warpPerspective(img_,M,(img.shape[1] + img_.shape[1], img.shape[0]))
cv2.imshow("dst", dst)
dst[0:img.shape[0], 0:img.shape[1]] = img
cv2.imshow("original_image_stitched.jpg", dst)
key = cv2.waitKey()
if key == 27:
cv2.destroyAllWindows()
# In[29]:
"""
Step #5: trim the stitched image and output the final image.
"""
def trim(frame):
#crop top
if not np.sum(frame[0]):
return trim(frame[1:])
#crop top
if not np.sum(frame[-1]):
return trim(frame[:-2])
#crop top
if not np.sum(frame[:,0]):
return trim(frame[:,1:])
#crop top
if not np.sum(frame[:,-1]):
return trim(frame[:,:-2])
return frame
# In[32]:
## Save the image
trimed_output = trim(dst)
cv2.imwrite("output_stitched.jpg", trimed_output)
# In[31]:
## Display the output image
cv2.imshow("original_image_stitched_crop.jpg", trimed_output)
key = cv2.waitKey()
if key == 27:
cv2.destroyAllWindows()
# In[ ]:
|
c4fd22f5eed45b43457dd5b3fed8ddb74c147627 | ChrisLiu95/Leetcode | /leetcode/array_partition.py | 1,429 | 3.875 | 4 | """
Given an array of 2n integers, your task is to group these integers into n pairs of integer,
say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Example 1:
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Assume in each pair i, bi >= ai.
Denote Sm = min(a1, b1) + min(a2, b2) + ... + min(an, bn). The biggest Sm is the answer of this problem. Given 1, Sm = a1 + a2 + ... + an.
Denote Sa = a1 + b1 + a2 + b2 + ... + an + bn. Sa is constant for a given input.
Denote di = |ai - bi|. Given 1, di = bi - ai. Denote Sd = d1 + d2 + ... + dn.
So Sa = a1 + a1 + d1 + a2 + a2 + d2 + ... + an + an + dn = 2Sm + Sd => Sm = (Sa - Sd) / 2. To get the max Sm, given Sa is constant, we need to make Sd as small as possible.
So this problem becomes finding pairs in an array that makes sum of di (distance between ai and bi) as small as possible. Apparently, sum of these distances of adjacent elements is the smallest. If that’s not intuitive enough, see attached picture. Case 1 has the smallest Sd.
"""
class Solution(object):
def maximum_pairs(self, given_array):
n = len(given_array)
result = 0
given_array.sort()
for i in range(0, n, 2):
result = result+given_array[i]
return result
test = Solution()
print(test.maximum_pairs([1, 2, 3, 4, 5, 6]))
|
d2741915cf265207e3918cd8e87c6b4b9f65ccd4 | lhserafim/python-100-days-of-code-monorepo | /day-4/treasure-map/main.py | 704 | 4.0625 | 4 | # 🚨 Don't change the code below 👇
# I'm using emojis
row1 = ["⬜️","⬜️","⬜️"]
row2 = ["⬜️","⬜️","⬜️"]
row3 = ["⬜️","⬜️","⬜️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
#split position = position.split(",")
position_y = int(position[0])
position_x = int(position[1])
# O -1 é para evitar que saia do index da lista, uma vez que a lista começa com 0
map[position_x - 1][position_y - 1] = "✖️"
#Write your code above this row 👆
# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}") |
4dbcee2267ffb4b83aa965a1ffd4a8b276fee08e | juliagimbernat/nlp | /percentages.py | 160 | 3.765625 | 4 | import re
import pandas as pd
#x = "This is a percentage 12-16%"
#result = re.findall(r'[0-9]*\-?[0-9]+\%', x)
#print(result)
x = "low controls"
result = |
ca61253cdbfb3ea4cc27622c97f2194c86bc61d9 | Tharsisboamorte/BLASTOFF | /Blastoff questão 6.py | 887 | 4.09375 | 4 | #Nas 13 primeiras linhas eu utilizo da conversão de horas para segundos e de minutos para segundos para fazer o calulor da diferença posteriormente na linha 16
print("Esse programa vai calcular quanto tempo durou a partida de futebol que você participou/assistiu")
print("Digite as horas inicias:")
h1 = int(input())
horaseg1 = h1*3600
print("Digite os minutos inicias:")
m1 = int(input())
minseg1 = m1*60
print("Digite as horas finais:")
h2 = int(input())
horaseg2 = h2*3600
print("Digite os minutos finais:")
m2 = int(input())
minseg2 = m2*60
segundos = (horaseg2+minseg2)-(horaseg1+minseg1)
#Nessas últimas linhas eu utilizo do resultado da diferença dos dois horários e converto cada um para seu estado original de medida
h = int(segundos / 3600)
resto = segundos % 3600
m = int(resto / 60)
print("Foram",h,"horas e", m,"minutos de partida de futebol") |
499feb0f5edd5e46ad0b38716c73b5835a9b8738 | MY-Park/AI-Projects | /2017_코드_A*.py | 40,378 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import math
# AlphaBeta, GameTree, GameNode class modify from https://tonypoer.io/2016/10/28/
class AlphaBeta:
def __init__(self, game_tree, AI_turn):
self.game_tree = game_tree
self.root = game_tree.root
self.AIturn = AI_turn
return
def alpha_beta_search(self, node):
infinity = float('inf')
best_val = -infinity
beta = infinity
successors = self.getSuccessors(node)
best_state = None
for state in successors:
value = self.min_value(state, best_val, beta)
if value > best_val:
best_val = value
best_state = state
print "AlphaBeta : Utility Value of Root Node = " + str(best_val)
print "AlphaBeta : Best State is : " + best_state.name
return best_state.name
def max_value(self, node, alpha, beta):
print "AlphaBeta-->MAX : Visited Node :: " + node.name
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
value = -infinity
successors = self.getSuccessors(node)
for state in successors:
value = max(value, self.min_value(state, alpha, beta))
if value >= beta:
return value
alpha = max(alpha, value)
return value
def min_value(self, node, alpha, beta):
print "AlphaBeta-->MIN : Visited Node :: " + node.name
if self.isTerminal(node):
return self.getUtility(node)
infinity = float('inf')
value = infinity
successors = self.getSuccessors(node)
for state in successors:
value = min(value, self.max_value(state, alpha, beta))
if value <= alpha:
return value
beta = min(beta, value)
return value
# #
# UTILITY METHODS #
# #
# successor states in a game tree are the child nodes...
def getSuccessors(self, node):
assert node is not None
return node.children
# return true if the node has NO children (successor states)
# return false if the node has children (successor states)
def isTerminal(self, node):
assert node is not None
return len(node.children) == 0
def check_input(self):
count = [0, 0, 0, 0, 0, 0, 0]
max = 1
for x in range(len(self.gridInfo) - 1):
count[self.gridInfo[x]] += 1
if max(count) > 6:
return False
return True
def getUtility(self, node):
assert node is not None
gridInfo = node.name
former = 'F'
latter = 'L'
ch = self.AIturn
count = [0, 0, 0, 0, 0, 0, 0]
grid = [[' ' for col in range(7)] for row in range(6)]
for x in range(len(gridInfo) - 1):
count[int(gridInfo[x])] += 1
if max(count) > 6:
return 0
for x in range(0, len(gridInfo)):
idx = int(gridInfo[x])
# get index where to put
for row in range(0, 6):
if grid[5 - row][idx] == ' ':
if x % 2 == 0: # former's turn
grid[5 - row][idx] = former
else: # later's turn
grid[5 - row][idx] = latter
break
for iteration in range(0, 2):
if iteration == 0:
under = 4.5
else:
if ch == 'F':
ch = 'L'
under = 4.7
else:
ch = 'F'
under = 4.7
###################################################
row_score = 0
for row in range(6):
for start in range(4):
count = 0
for x in range(4):
if grid[row][start + x] != ch and grid[row][start + x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if grid[row][start + x] == ch:
count = count + 1
# count character number
if count < 0:
score = 0
elif count == 0:
score = 1
else:
score = math.pow(under, count)
# give score to 4 space set
row_score = row_score + score
# iterate in row
# iterate by row
print "row_score:", row_score
# column
col_score = 0
for col in range(7):
for start in range(3):
count = 0
for x in range(4):
if grid[start + x][col] != ch and grid[start + x][col] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if grid[start + x][col] == ch:
count = count + 1
# count character number
if count < 0:
score = 0
else:
score = math.pow(under, count)
# give score to 4 space set
col_score = col_score + score
# iterate in col
# iterate by col
print "col_score:", col_score
# right diagonal
rd_score = 0
for row in range(3, 6):
for start in range(3):
count = 0
for x in range(4):
if row - start - x < 0 or start + x > 6:
count = -1
break
if grid[row - start - x][start + x] != ch and grid[row - start - x][start + x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if grid[row - start - x][start + x] == ch:
count = count + 1
# count character number
if count < 0:
score = 0
else:
score = math.pow(under, count)
# give score to 4 space set
rd_score = rd_score + score
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
for col in range(1, 4):
for start in range(3):
count = 0
for x in range(4):
if 5 - start - x < 0 or col + start + x > 6:
count = -1
break
if grid[5 - start - x][col + start + x] != ch and grid[5 - start - x][col + start + x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if grid[5 - start - x][col + start + x] == ch:
count = count + 1
# count character number
if count < 0:
score = 0
else:
score = math.pow(under, count)
# give score to 4 space set
rd_score = rd_score + score
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
print "rd_score:", rd_score
# left diagonal
ld_score = 0
for row in range(3, 6):
for start in range(3):
count = 0
for x in range(4):
if row - start - x < 0 or 6 - start - x < 0:
count = -1
break
if grid[row - start - x][6 - start - x] != ch and grid[row - start - x][6 - start - x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if grid[row - start - x][6 - start - x] == ch:
count = count + 1
# count character number
if count < 0:
score = 0
else:
score = math.pow(under, count)
# give score to 4 space set
ld_score = ld_score + score
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
for col in range(3, 7):
for start in range(3):
count = 0
for x in range(4):
if 5 - start - x < 0 or col - start - x < 0:
count = -1
break
if grid[5 - start - x][col - start - x] != ch and grid[5 - start - x][col - start - x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if grid[5 - start - x][col - start - x] == ch:
count = count + 1
# count character number
if count < 0:
score = 0
else:
score = math.pow(under, count)
# give score to 4 space set
ld_score = ld_score + score
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
print "ld_score:", ld_score
total_score = row_score + col_score + rd_score + ld_score
if iteration == 0:
my_score = total_score
else:
opponent_treat = total_score
###################################################
total_score = my_score - opponent_treat
print "my score : ", my_score
print "opp treat : ", opponent_treat
print total_score
return total_score
class GameNode:
def __init__(self, name, value=0, parent=None):
self.name = name # string
self.value = value # an int
self.parent = parent # a node reference
self.children = [] # a list
def addChild(self, childNode):
self.children.append(childNode)
class GameTree:
def __init__(self):
self.root = None
def build_tree(self, depth, initial_root, num_child=7):
self.root = initial_root
node_list = [self.root]
parent_idx = 0
check_list = ['0', '1', '2', '3', '4', '5', '6']
check = True
parent_num = 1
parent_count = 0
for d in range(depth):
for p in range(parent_num):
parent = node_list[parent_idx]
for ind in range(num_child):
child_name = parent.name + str(ind)
for col in check_list:
if child_name.count(col) > 6:
check = False
if check:
new_node = GameNode(child_name, 0, parent)
parent.addChild(new_node)
node_list.append(new_node)
parent_count += 1
check = True
parent_idx += 1
parent_num = parent_count
parent_count = 0
def print_tree(self):
node_list = [self.root]
while len(node_list) != 0:
new_list = []
s = ""
for c in node_list:
new_list.extend(c.children)
s += c.name + " "
print s
node_list = new_list
class Grid:
def __init__(self):
self.grid = [[' ' for col in range(7)] for row in range(6)]
self.gridInfo = ''
return
def print_grid(self):
print "----------------------"
for row in range(6):
print "|",
for col in range(7):
print self.grid[row][col] + "|",
print
print "----------------------"
print self.gridInfo
def put_by_force(self, col_num, ch):
for row in range(5, -1, -1):
if self.grid[row][col_num] == ' ':
self.grid[row][col_num] = ch
print ch
return False
return True
def clear_grid(self):
self.grid = [[' ' for col in range(7)] for row in range(6)]
def remove_recent(self, col_num):
for row in range(6):
if self.grid[row][col_num] != ' ':
self.grid[row][col_num] = ' '
return False
return True
def by_my_advantage(self):
stringlength = len(self.gridInfo)
advantage = [0, 0, 0, 0, 0, 0, 0]
gridcopy = self.grid
if stringlength % 2 == 0: # 지금까지 짝수번째 턴이었다면(이제 내가 놓아야함)
char = "O" # 현재 차례는 O(홀수) 차례
oppchar = "X"
else:
char = "X" # 현재 차례는 x(짝수) 차례
oppchar = "O"
gridCount = [self.gridInfo.count("0"), self.gridInfo.count("1"), self.gridInfo.count("2"),
self.gridInfo.count("3"),
self.gridInfo.count("4"),
self.gridInfo.count("5"), self.gridInfo.count("6")] # 각 자리의 최대 인덱스를 구하는 리스트.
OverGrid = [0, 0, 0, 0, 0, 0, 0] # Grid(6개 이상 두는걸 예측 못하게!!!)를 넘어갈 경우를 대비한 리스트지용
for i in range(0, 7):
if gridCount[i] == 6: # 만약 최대 인덱스가 6이면 해당 자리의 overgird를 1로 바꿈
OverGrid[i] = 1
else:
OverGrid[i] = 0
##############################################################################################################
##############################################################################################################
# row의 경우
for k in range(0, 7):
if OverGrid[k] == 1: # 일단 해당 자리의 overgrid가 1이면 최대 인덱스가 6인 것이므로 재빨리 for문을 벗어난다. advantage는 -100으로 책정
advantage[k] = -1000
continue
count = 0 # row에서 count는 내돌이 있는 자리. empty는 세지 않는다
fourCount = 0 # 사실 가로는 이어져서 4여야만 connect4를 이룰 수 있으니까 빈칸, 내돌 4개까지만 체크하겠어용
gridcopy[5 - gridCount[k]][k] = char # 해당 자리의 돌을 끼얹는다....! 이제부터 이 자리를 기준으로 검사하겠음
# column에서 emptycount가 있었는데 row는 걍 fourCount로 <내돌 + emptycount>까지 합쳤습니당
for i in range(0, 7 - k): # 둔 돌을 기준으로 오른쪽 탐색
if fourCount == 4: # 만약 4개를 둘 자리가 충만하다면 걍 점수매기러 바로 ㄱㄱ
break
elif gridcopy[5 - gridCount[k]][k + i].count(char) == 1: # 내 돌이라면
fourCount += 1
count += 1
elif gridcopy[5 - gridCount[k]][k + i] == oppchar: # 상대편 돌이라면
break
else: # 빈칸이라면
fourCount += 1
for i in range(0, k): # 둔 돌을 기준으로 왼쪽 탐색 (단 둔 돌은 제외한다. 오른쪽에서 이미 셌거든용)
if fourCount == 4:
break
elif gridcopy[5 - gridCount[k]][k - i - 1].count(
char) == 1: # 왼쪽 탐색. 만약 내 돌이 없는 순간(빈칸or 상대편의 돌) 바로 정지+ 방금둔 돌까지 같이 셈
count += 1
fourCount += 1
elif gridcopy[5 - gridCount[k]][k - i - 1] == oppchar:
break
else:
fourCount += 1
gridcopy[5 - gridCount[k]][k] = ' ' # 예측한 돌 초기화
row_advantage = 0 # row advantage를 책정
if fourCount < 4:
row_advantage += 0
elif fourCount >= 4 and count == 0:
row_advantage += 1
elif fourCount >= 4 and count == 1:
row_advantage += 2
elif count == 2 and fourCount >= 4:
row_advantage += 4
elif count == 3 and fourCount >= 4:
row_advantage += 8
elif count == 4 and fourCount >= 4:
row_advantage += 1000
else:
row_advantage += 0
advantage[k] += row_advantage # row advantage를 해당 자리의 advantage에 저장 row끝
##############################################################################################################
##############################################################################################################
# column의 경우
for k in range(0, 7):
if OverGrid[k] == 1: # 일단 해당 자리의 overgrid가 1이면 최대 인덱스가 6인 것이므로 재빨리 for문을 벗어난다. advantage는 -100으로 책정
advantage[k] = -1000
continue
count = 0
emptycount = 0
gridcopy[5 - gridCount[k]][k] = char
# column
for i in range(0, gridCount[k] + 1):
if gridcopy[5 - gridCount[k] + i][k].count(char) == 1:
count += 1
elif gridcopy[5 - gridCount[k] + i][k].count(char) != 1: # 다른 돌이 있으면 탐색 종료
break
for i in range(5 - gridCount[k]):
emptycount += 1
gridcopy[5 - gridCount[k]][k] = ' '
col_advantage = 0
if count == 0 and emptycount >= 4:
col_advantage += 1
if count == 1 and emptycount >= 3:
col_advantage += 2
elif count == 2 and emptycount >= 2:
col_advantage += 4
elif count == 3 and emptycount >= 1:
col_advantage += 8
elif count == 4 and emptycount >= 0:
col_advantage += 1000
else:
col_advantage += 0
advantage[k] += col_advantage
##############################################################################################################
##############################################################################################################
# 대각선의 경우
for k in range(0, 7):
if OverGrid[k] == 1: # 일단 해당 자리의 overgrid가 1이면 최대 인덱스가 6인 것이므로 재빨리 for문을 벗어난다. advantage는 -100으로 책정
advantage[k] = -1000
continue
count1 = 0 # 대각선에서 count는 내돌이 있는 자리. empty는 세지 않는다 이 때 count1은 /방향 count2는 반대방향
fourCount1 = 0 # 대각선도 이어져서 4여야만 connect4를 이룰 수 있으니까 빈칸, 내돌 4개까지만 체크하겠어용
fourCount2 = 0
count2 = 0
gridcopy[5 - gridCount[k]][k] = char # 내가 둘 자리
up = 6 - gridCount[k] # 내가 둘 돌 포함한 위쪽
down = gridCount[k] + 1 # 내가 둘 돌 포함한 아래쪽
right = 7 - k # 내가 둘 돌 포함한 오른쪽
left = k + 1 # 내가 둘 돌 포함한 왼쪽
if up <= right: # /방향 중에 위쪽 결정 : 이유는 grid 벗어나면 안되니까
northeast = up
else:
northeast = right
if down <= left: # /방향 중에 아래쪽
southwest = down
else:
southwest = left
if up <= left: # 반대방향 위쪽
northwest = up
else:
northwest = left
if down <= right: # 반대방향 아래쪽
southeast = down
else:
southeast = right
# 대각선도 걍 fourCount로 내돌+emptycount까지 합쳤습니당
# diagonal
# /방향 대각선
for i in range(0, northeast):
if fourCount1 == 4: # 만약 4개를 둘 자리가 충만하다면 걍 점수매기러 바로 ㄱㄱ
break
elif gridcopy[5 - gridCount[k] - i][k + i].count(char) == 1: # /쪽 위쪽 탐색
fourCount1 += 1
count1 += 1
elif gridcopy[5 - gridCount[k] - i][k + i] == oppchar:
break
else:
fourCount1 += 1
for i in range(0, southwest - 1): # /쪽 아래쪽 탐색
if fourCount1 == 4:
break
elif gridcopy[6 - gridCount[k] + i][k - i - 1].count(char) == 1:
count1 += 1
fourCount1 += 1
elif gridcopy[6 - gridCount[k] + i][k - i - 1] == oppchar:
break
else:
fourCount1 += 1
for i in range(0, northwest): # 반대쪽 위쪽 탐색
if fourCount2 == 4:
break
elif gridcopy[5 - gridCount[k] - i][k - i].count(char) == 1:
count2 += 1
fourCount2 += 1
elif gridcopy[5 - gridCount[k] - i][k - i] == oppchar:
break
else:
fourCount2 += 1
for i in range(0, southeast - 1): # 반대쪽 아래쪽 탐색
if fourCount2 == 4:
break
elif gridcopy[6 - gridCount[k] + i][k + i + 1].count(char) == 1:
count2 += 1
fourCount2 += 1
elif gridcopy[6 - gridCount[k] + i][k + i + 1] == oppchar:
break
else:
fourCount2 += 1
gridcopy[5 - gridCount[k]][k] = ' ' # 내가 둘 곳 초기화
# / 방향일 때 advantage
di_advantage = 0
if fourCount1 < 4:
di_advantage += 0
elif count1 == 0 and fourCount1 >= 4:
di_advantage += 1
elif count1 == 1 and fourCount1 >= 4:
di_advantage += 2
elif count1 == 2 and fourCount1 >= 4:
di_advantage += 4
elif count1 == 3 and fourCount1 >= 4:
di_advantage += 8
elif count1 == 4 and fourCount1 >= 4:
di_advantage += 16
else:
di_advantage += 0
advantage[k] += di_advantage
# 반대 방향일 때 advantage
di_advantage = 0
if fourCount2 < 4:
di_advantage += 0
elif count2 == 0 and fourCount2 >= 4:
di_advantage += 1
elif count2 == 1 and fourCount2 >= 4:
di_advantage += 2
elif count2 == 2 and fourCount2 >= 4:
di_advantage += 4
elif count2 == 3 and fourCount2 >= 4:
di_advantage += 8
elif count2 == 4 and fourCount2 >= 4:
di_advantage += 1000
else:
di_advantage += 0
advantage[k] += di_advantage
for k in range(0, 7):
if OverGrid[k] == 1: # 일단 해당 자리의 overgrid가 1이면 최대 인덱스가 6인 것이므로 재빨리 for문을 벗어난다. advantage는 -100으로 책정
advantage[k] = -1000
continue
gridcopy[5 - gridCount[k]][k] = char
opp_row_Advantage = 0
for j in range(0, 6): # 세로세기
rowCount = 0 # 시작점 체크 count
for n in range(0, 4): # 가로 4칸씩 체크(시작점 : 0,1,2,3)
oppfourcount = 0 # 4개 확인 되었는지 체크
oppcount = 0 # 상대편이 4개 범위에서 둔 돌의 갯수
oppemptycount = [9, 9, 9, 9] # 어느게 상대 4개 범위 중 empty공간인지.
oppemptycount_col = [0, 0, 0, 0]
for i in range(0, 4): # 4칸 체크 (0~3, 1~4, 2~5, 3~6)
if gridcopy[5 - j][rowCount + i] == oppchar:
oppcount += 1
oppfourcount += 1
elif gridcopy[5 - j][rowCount + i] == char:
break
else:
oppfourcount += 1
oppemptycount[i] = rowCount + i # 어느 부분이 empty인지 체크.... 세로 갯수를 셀거임.
for m in range(0, j + 1):
if gridcopy[5 - j - m][rowCount + i] != oppchar and gridcopy[5 - j - m][rowCount] != char:
oppemptycount_col[i] += 1
else:
break
if oppfourcount < 4:
opp_row_Advantage += 0
elif oppfourcount == 4 and oppcount == 2:
for i in range(0, 4):
if oppemptycount[i] != 9:
if oppemptycount_col[i] > 2:
opp_row_Advantage += 4
elif oppemptycount_col[i] == 1 or oppemptycount_col[i] == 2:
opp_row_Advantage += 8
else :
opp_row_Advantage += 4
elif oppfourcount == 4 and oppcount == 3:
for i in range(0, 4):
if oppemptycount[i] != 9:
if oppemptycount_col[i] == 1:
opp_row_Advantage += 16
else:
opp_row_Advantage += 8
else:
opp_row_Advantage += 0
rowCount += 1
gridcopy[5 - gridCount[k]][k] = ' '
advantage[k] -= opp_row_Advantage
for k in range(0, 7):
if OverGrid[k] == 1: # 일단 해당 자리의 overgrid가 1이면 최대 인덱스가 6인 것이므로 재빨리 for문을 벗어난다. advantage는 -100으로 책정
advantage[k] = -1000
continue
gridcopy[5 - gridCount[k]][k] = char
opp_col_Advantage = 0
for j in range(0, 7): # 가로세기
emptycount = 0
oppcount = 0
for i in range(0, 6):
if gridcopy[5 - i][j] == oppchar:
oppcount += 1
elif gridcopy[5 - i][j] == char:
oppcount = 0
else:
emptycount = 6 - i
break
if oppcount == 0:
opp_col_Advantage += 0
elif oppcount == 2 and emptycount >= 2:
opp_col_Advantage += 8
elif oppcount == 3 and emptycount >= 1:
opp_col_Advantage += 64
else:
opp_col_Advantage += 0
gridcopy[5 - gridCount[k]][k] = ' '
advantage[k] -= opp_col_Advantage
for k in range(0, 7):
if OverGrid[k] == 1: # 일단 해당 자리의 overgrid가 1이면 최대 인덱스가 6인 것이므로 재빨리 for문을 벗어난다. advantage는 -100으로 책정
advantage[k] = -1000
continue
gridcopy[5 - gridCount[k]][k] = char
opp_diagonal_Advantage = 0
rd_score = 0
for row in range(3, 6):
for start in range(3):
count = 0
emptycount = 0
for x in range(4):
if row - start - x < 0 or start + x > 6:
count = -1
break
if gridcopy[row - start - x][start + x] != oppchar and gridcopy[row - start - x][start + x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if gridcopy[row - start - x][start + x] == oppchar:
count = count + 1
elif gridcopy[row - start - x][start + x] == ' ':
if row - start - x == 5:
emptycount += 1
elif gridcopy[row - start - x + 1][start + x] == oppchar or gridcopy[row - start - x + 1][
start + x] == char:
emptycount += 1
else:
emptycount += 0
# count character number
if count < 0:
oppscore = 0
elif count == 3 and emptycount == 1:
oppscore = 64
elif count == 2 and emptycount == 2:
oppscore = 64
else:
oppscore = 0
# give score to 4 space set
rd_score = rd_score + oppscore
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
for col in range(1, 4):
for start in range(3):
emptycount = 0
count = 0
for x in range(4):
if 5 - start - x < 0 or col + start + x > 6:
count = -1
break
if gridcopy[5 - start - x][col + start + x] != oppchar and gridcopy[5 - start - x][
col + start + x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if gridcopy[5 - start - x][col + start + x] == oppchar:
count = count + 1
elif gridcopy[5 - start - x][col + start + x] == ' ':
if 5 - start - x == 5:
emptycount += 1
elif gridcopy[5 - start - x + 1][col + start + x] == oppchar or gridcopy[5 - start - x + 1][
col + start + x] == char:
emptycount += 1
else:
emptycount += 0
# count character number
if count < 0:
oppscore = 0
elif count == 3 and emptycount == 1:
oppscore = 64
elif count == 2 and emptycount == 1:
oppscore = 32
elif count == 2 and emptycount == 2:
oppscore = 64
else:
oppscore = 0
# give score to 4 space set
rd_score = rd_score + oppscore
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
# print "rd_score:", rd_score
# left diagonal
ld_score = 0
for row in range(3, 6):
for start in range(3):
emptycount = 0
count = 0
for x in range(4):
if row - start - x < 0 or 6 - start - x < 0:
count = -1
break
if gridcopy[row - start - x][6 - start - x] != oppchar and gridcopy[row - start - x][
6 - start - x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if gridcopy[row - start - x][6 - start - x] == oppchar:
count = count + 1
elif gridcopy[row - start - x][6 - start - x] == ' ':
if row - start - x == 5:
emptycount += 1
elif gridcopy[row - start - x + 1][6 - start - x] == oppchar or gridcopy[row - start - x + 1][
6 - start - x] == char:
emptycount += 1
else:
emptycount += 0
# count character number
if count < 0:
oppscore = 0
elif count == 3 and emptycount == 1:
oppscore = 64
elif count == 2 and emptycount == 2:
oppscore = 64
else:
oppscore = 0
# give score to 4 space set
ld_score = ld_score + oppscore
# iterate in row diagonally 3 4 5
# iterate by row 3 4 5
for col in range(3, 7):
for start in range(3):
emptycount = 0
count = 0
for x in range(4):
if 5 - start - x < 0 or col - start - x < 0:
count = -1
break
if gridcopy[5 - start - x][col - start - x] != oppchar and gridcopy[5 - start - x][
col - start - x] != ' ':
count = -1
break
# if there is one opponent character in 4 space set, no score
if gridcopy[5 - start - x][col - start - x] == oppchar:
count = count + 1
elif gridcopy[5 - start - x][col - start - x] == ' ':
if 5 - start - x == 5:
emptycount += 1
elif gridcopy[5 - start - x + 1][col - start - x] == oppchar or \
gridcopy[5 - start - x + 1][
col - start - x] == char:
emptycount += 1
else:
emptycount += 0
# count character number
if count < 0:
oppscore = 0
elif count == 3 and emptycount == 1:
oppscore = 64
elif count == 2 and emptycount == 2:
oppscore = 64
else:
oppscore = 0
# give score to 4 space set
ld_score = ld_score + oppscore
opp_diagonal_Advantage = rd_score + ld_score
gridcopy[5 - gridCount[k]][k] = ' '
advantage[k] -= opp_diagonal_Advantage
return advantage.index(max(advantage))
def put_by_rule(self):
if self.grid[5][3] == ' ':
position_x = 5
position_y = 3
print 6 - position_x, position_y + 1
return 3
else:
return self.by_my_advantage()
def check_input(self):
count = [0, 0, 0, 0, 0, 0, 0]
max = 1
for x in range(len(self.gridInfo) - 1):
count[self.gridInfo[x]] += 1
if max(count) > 6:
return False
return True
if __name__ == "__main__":
grid = Grid()
player1_ch = 'O'
player2_ch = 'X'
grid.print_grid()
AI_turn = raw_input("select AI turn, F : former, L : latter…")
count = 0
while True:
if count % 2 == 0:
ch = player1_ch
else:
ch = player2_ch
print "1: print grid"
print "2: make move by force"
print "3: make move by algorithm"
print "4: make move by rule"
print "5: remove recent"
print "6: clear grid"
print "7: end game"
choose = input("select ")
if choose < 1 or choose > 7:
while choose < 1 or 7 < choose:
choose = input("choose again ")
# make right selection
if choose == 1:
grid.print_grid()
elif choose == 2:
col_num = input("which column to put by force?(0-6) ")
if col_num > 6 or col_num < 0:
print "wrong input"
continue
if grid.put_by_force(col_num, ch):
print "There's no place to put…"
grid.print_grid()
print "count : ", count
continue
else:
grid.gridInfo = grid.gridInfo + str(col_num)
grid.print_grid()
count += 1
elif choose == 3:
root = GameNode(grid.gridInfo, 0, None)
tree = GameTree()
tree.build_tree(6, root)
tree.print_tree()
alphabeta = AlphaBeta(tree, AI_turn)
best_state_name = alphabeta.alpha_beta_search(tree.root)
print best_state_name
grid.gridInfo = grid.gridInfo + best_state_name[len(best_state_name) - 1]
grid.put_by_force(int(best_state_name[len(best_state_name) - 1]), ch)
grid.print_grid()
count += 1
elif choose == 4:
col_num = grid.put_by_rule()
grid.put_by_force(col_num, ch)
grid.gridInfo = grid.gridInfo + str(col_num)
grid.print_grid()
count += 1
elif choose == 5: # Do not use this option when nothing is on the board
col_num = int(grid.gridInfo[len(grid.gridInfo) - 1])
if grid.remove_recent(col_num):
print("There's nothing to remove")
grid.print_grid()
print "count : ", count
continue
else:
grid.gridInfo = grid.gridInfo[0:len(grid.gridInfo) - 1]
grid.print_grid()
count -= 1
elif choose == 6:
grid.clear_grid()
grid.gridInfo = ''
grid.print_grid()
count = 0
elif choose == 7:
print("Bye :)")
break
if len(grid.gridInfo) > 41:
print("Game is Over :)")
break
print "count : ", count
# above if statements print position |
8051d9bb3f98a3b9a5768e4a7ab760caee2ff00d | Mehvix/competitive-programming | /MSOE Op Computer Competition/2018/2018_Problem7.py | 1,550 | 4 | 4 | import math
time = int(input("Enter UNIX time:"))
# time = 1111111111
minute = 60
hour = minute * 60
day = hour * 24
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
year_noleap = day * 365
year_leap = day * 366
year_four = 3*year_noleap + year_leap
total_years = 1970
total_months = 1
total_days = 1
total_hours = 12
total_hours_am_pm = "PM"
total_mins = 0
def convert(initial_time: int, unit: int):
return math.floor(initial_time / unit), initial_time % unit
while time > year_leap:
if (total_years % 4 == 0) or (total_years % 100 == 0):
total_years += 1
time -= year_leap
print(total_years, "LEAP")
else:
total_years += 1
time -= year_noleap
print(total_years, "NO LEAP")
"""
total_years += 4*(convert(time, year_four)[0])
time = convert(time, year_four)[1]
"""
for month in range(len(months)):
cur_momth = int(months[month])
if (day * cur_momth) < time:
total_months += 1
time -= (day * cur_momth)
else:
break
total_days += convert(time, day)[0]
time = convert(time, day)[1]
total_hours += convert(time, hour)[0]
time = convert(time, hour)[1]
total_mins += convert(time, minute)[0]
time = convert(time, minute)[1]
for _ in range(2):
if total_hours > 12:
total_hours -= 12
if total_hours_am_pm == "PM":
total_hours_am_pm = "AM"
else:
total_hours_am_pm = "PM"
print("{}:{} {} {}/{}/{}".format(total_hours, total_mins, total_hours_am_pm, total_months, total_days, total_years))
|
c8c7c66658202d2683239abb752d02055bd19b7e | sbbasak/CIT_ES_PP_2001_Assignment-1 | /input.py | 128 | 4.375 | 4 |
# 1. take an input and print it.
print('Enter your nick name:')
your_name = input()
print('Welcome!' + your_name + '.')
|
423a23b0a17a7bda7427234788ab293d6d1d0711 | or0986113303/LeetCodeLearn | /python/280 - Wiggle Sort/main.py | 1,226 | 3.953125 | 4 | class Solution(object):
def mergesort(self, source):
if len(source) <= 1 :
return source
middle = len(source) >> 1
leftpart = self.mergesort(source[:middle])
rightpart = self.mergesort(source[middle:])
return self.merge(leftpart, rightpart)
def merge(self, leftpart, rightpart):
leftindex, rightindex = 0, 0
result = []
while len(leftpart) > leftindex and len(rightpart) > rightindex:
if leftpart[leftindex] > rightpart[rightindex]:
result.append(rightpart[rightindex])
rightindex += 1
else :
result.append(leftpart[leftindex])
leftindex += 1
result += leftpart[leftindex:]
result += rightpart[rightindex:]
return result
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
nums.sort()
numssorted = self.mergesort(nums)
for index in range(1, len(nums)-1, 2):
nums[index], nums[index + 1] = nums[index + 1], nums[index]
print(nums)
print(numssorted)
|
5f1e06850c679d27d599e38370968d24fb0a69ee | skyyi1126/leetcode | /quora_diagonal_sort.py | 555 | 3.796875 | 4 | def solution(A):
N = len(A)
def sort_diagonal(i,j): #i, j is the starting index of the diagonal line
to_sort = []
while (i<N and j<N):
to_sort.append(A[i][j])
i += 1
j += 1
i -= 1
j -= 1
to_sort.sort()
while (i>-1 and j>-1):
A[i][j] = to_sort.pop()
i -= 1
j -= 1
for i in range(N):
sort_diagonal(i,0)
for i in range(1,N):
sort_diagonal(0,i)
return A
print(solution([[8, 4, 1],[4, 4, 1],[4, 8, 9]])) |
bdb211d000daaa801da4e9eddc85346d5f781845 | xshirl/ctci | /chapter2/2.4.partition.py | 1,560 | 3.765625 | 4 | from Node import Node
def partition(head, x):
h1 = l1 = Node(0)
h2 = l2 = Node(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l2.next = None
l1.next = h2.next
return h1.next
class Solution:
def partition(self, head, x):
h1 = l1 = Node(0)
h2 = l2 = Node(0)
while head:
if head.val < x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l2.next = None
l1.next = h2.next
return h1.next
def partition2(self, head, x):
left_head = Node(None) # head of the list with nodes values < x
right_head = Node(None) # head of the list with nodes values >= x
left = left_head # attach here nodes with values < x
right = right_head # attach here nodes with values >= x
# traverse the list and attach current node to left or right nodes
while head:
if head.val < x:
left.next = head
left = left.next
else: # head.val >= x
right.next = head
right = right.next
head = head.next
right.next = None # set tail of the right list to None
left.next = right_head.next # attach left list to the right
return left_head.next # head of a new partitioned list
|
6f7b804a5988266451ae56fa94d2c3bd90855f59 | IchiiDev/homeworks | /NSI-Terminale-2021-2022/modules/exercises/balistique.py | 1,887 | 3.703125 | 4 | import math
import matplotlib.pyplot as plt
import numpy as np
import turtle as t
class projectile:
G = 9.81
def __init__(self, alpha, v, h):
self.alpha = alpha
self.v = v
self.h = h
return
def getDistance(self):
return (self.v / self.G) * math.cos(self.alpha) * (self.v * math.sin(self.alpha) + math.sqrt((self.v * math.sin(self.alpha))**2 + 2 * self.G * self.h))
def getFlightTime(self):
return (self.v * math.sin(self.alpha) + math.sqrt((self.v * math.sin(self.alpha))**2 + 2 * self.G * self.h)) / self.G
def getMaxHeight(self):
return (self.v**2 * math.sin(self.alpha)**2) / 2 ** self.G
def getY(self, x):
alpha = self.alpha * math.pi / 180
return -1 / 2 * self.G * x ** 2 / ((math.cos(alpha))**2 * self.v ** 2) + math.tan(alpha) * x * self.h
def tracerTrajectoire(self, xmax, n):
"""
Représenter la trajectoire
xmax : valeur maximale pour tracer la courbe
n : nombre de points sur la courbe
"""
liste_X = np.linspace(0, xmax, n)
liste_Y = [ self.getY(x) for x in liste_X]
plt.figure()
plt.plot(liste_X, liste_Y)
plt.grid()
plt.xlabel("Distance d")
plt.ylabel("Hauteur y")
plt.legend()
plt.show()
def animerTrajectoire(self, xmax, n, e):
"""
Animer la trajectoire
xmax : valeur maximale pour tracer la courbe
n : nombre de points sur la courbe
e : coefficient de mise à l'échelle
"""
liste_X = np.linspace(0, xmax, n)
liste_Y = [ self.getY(x) for x in liste_X]
t.speed("slowest")
t.up()
t.goto(liste_X[0] * e, liste_Y[0] * e)
t.down()
for k in range(1, n):
t.goto(liste_X[k] * e, liste_Y[k] * e)
t.done()
|
b4c469f92139c4e13006f5a746bc127e4bd4a094 | RowanASRCResearch/Image-Fusion | /Merging/ImageMerge.py | 14,451 | 3.640625 | 4 | from PIL import Image
import PixelProcess
debug = 0
class Merger:
def __init__(self, outfile):
"""
`Author`: Bill Clark
A merger is a class that allows for a number of images to merged sequentially. It is designed to
merge each image incrementally, outputting to an outfile when requested. There are a variety of
ways to preform the merges for different circumstance. The class contains an autosave feature that
will save the image after each merge, which is defaulted to off. There is also a contained PixelChecker
and PixelActor, which define how the merges process.
Merger works off an internal state. Each merge operation (irrelevant of number merged in that operation)
changes the state of the output data. Merge and MergeAs change the state permanently. ExportMerge and
TestMerge do not change the state of the output data.
`outfile`: The file address to save the output to.
"""
self.initialized = 0
self.autoSave = 0
self.outfile = outfile
self.processor = PixelProcess.PixelRemote()
self.mergedFiles = []
def setup(self, file):
"""
`Author`: Bill Clark
This method is called if a merge is activated and no prior merges have been done. It sets the image to
be merged as the output result, as nothing cannot be merged with an image object. This method is
internal and does not need to be called by a user. It is called if necessary from the merge methods.
`file`: A path to an image to initialize the Merge with.
"""
self.outimage = Image.open(file)
self.processor.outdata = self.outimage.load()
if self.autoSave: self.save()
self.initialized = 1
def merge(self, *images):
"""
`Author`: Bill Clark
The main merge method. All other variants actually call this merge at some point in execution. The
method calls setup if no merges have been done prior so that merges can be done against the first.
This uses the checkandact method to operate on each image given to it. That method covers all the
actual pixel processing.
When debug is enabled, merge prints the percentage of different and same pixels.
`images`: Any number of image paths to merge together.
"""
if not self.initialized:
self.setup(images[0])
images = images[1:]
if len(images) > 0:
for image in images:
changed = self.checkAndAct(image)
self.mergedFiles.append(image)
if debug: self.printDiffSame(changed)
if debug: self.show()
if self.autoSave: self.save()
def testMerge(self, *images):
"""
`Author`: Bill Clark
A test merge is a merge that doesn't save state. Each call to merge changes the internal data.
In the case a user wants to see the result of a merge without modifying the data, test merge will
do the job. Test merge is actually a call to exportmerge taking advantage of it's outfile variable.
`images`: Any number of image paths to be merged.
"""
self.exportMerge(None, *images)
def exportMerge(self, outfile, *images):
"""
`Author`: Bill Clark
Export merge is a merge operation that does not change state. Unlike TestMerge, this merge will
write the temporary image to a given outfile. If the outfile is None, export will not write anything.
This side effect is how TestMerge works. Export merge turns off the autosave feature to be sure that
doesn't modify the main output file.
`images`: the image paths to be merged.
`outfile`: Where to set the new output path to.
"""
# Make a backup of the outimage if one has been initialized.
orig = None
if self.initialized: orig = self.outimage.copy()
# Saves the autosave state and merges.
state = self.autoSave
self.autoSave = 0
self.merge(*images)
self.autoSave = state
# If the outfile is None, show the image and continue. If an outfile exists, save the image instead.
if outfile is not None: self.save(self.outimage, outfile)
else: self.show()
# If the back up was made, restore the status to before the last merge. Else, reset the object.
if orig is not None:
self.outimage = orig
self.processor.outdata = self.outimage.load()
else:
self = Merger(self.outfile)
def mergeAs(self, outfile, *images):
"""
`Author`: Bill Clark
This is a variant of the main merge method. It changes the outfile permanently, functioning like
a save as option. Otherwise it differs completely to merge.
`images`: the image paths to be merged.
`outfile`: Where to set the new output path to.
"""
self.outfile = outfile
self.merge(*images)
def _tupleSub(self, t, tt):
"""
`Author`: Bill Clark
Finds the difference of each RGB value in two pixels. The difference has to be
greater than 5 to fail.
`t`: The first pixel to compare.
`tt`: The second to compare.
`return`: False if the difference between any RGB is greater than 5, else true.
"""
for one, two in zip(t, tt):
if abs(one - two) > 5:
return False
return True
def _rowSizer(self, x, y, row, length):
"""
`Author`: Bill Clark
This method take a row and makes the length equal to the length parameter. It fills
the row using the tracked image pixel data, building a row on y value Y starting at
x in that row. Supports shrinking a row as well, though that isn't needed anymore.
`x`: X value to start the row on.
`y`: Y value of the row.
`row`: The array that will hold the row.
`length`: required length of the row.
`return`: The new row.
"""
while len(row) != length: #get the row to match the size.
if len(row) > length:
del row[-1]
elif len(row) < length:
row.append(self.processor.outdata[x+len(row),y])
return row
def _compareRow(self, sideOne, sideTwo, row):
"""
`Author`: Bill Clark
Compares two rows to another. This is used to compare the top and bottom, as well as the
left and right rows of the subimage to an equally sized row from the tracked image.
The comparison is done via tuplesub, this controls the pixel flow into that function.
`sideOne`: The top or right side to be compared.
`sideTwo`: The bottom or left side to be compared.
`row`: The row to compare to from the tracked image.
`return`: Flag (True if a match was found), if1 (sideOne is same or not), & if2 (same for sideTwo)
"""
flag, if1, if2 = True, True, True
for side1, side2, lg in zip(sideOne, sideTwo, row):
if if1: if1 = self._tupleSub(side1, lg)
if if2: if2 = self._tupleSub(side2, lg)
if not if1 and not if2:
flag = False
break
return flag, if1, if2
def cropFind(self, outfile, smallImage):
"""
`Author`: Bill Clark
Finds where a subimage of the tracked image fits in the tracked image.
This is done by comparing the sides of the outfile image with each
row of pixels in the tracked image. This acommodates for rotation. The match
is as close to exact as is practical. Saving and cropping images can sometimes
cause small differences such as 1 or or 2 values.
The if result not none section can be replaced later to change what is done
with the result.
`outfile`: path to save the merged crop to.
`smallImage`: A subimage of the tracked image.
`return`: None if no match is found, the result is one is.
"""
smim = Image.open(smallImage)
smdata = smim.load()
xlen, ylen = smim.size
result = None
sides = [[], [], [], []]
high = max(xlen, ylen)
for i in xrange(high):
if i < xlen:
sides[0].append(smdata[(i, 0)])
sides[2].append(smdata[((xlen-1)-i, ylen-1)])
if i < ylen:
sides[1].append(smdata[(xlen-1, i)])
sides[3].append(smdata[(0, (ylen-1)-i)])
for side in sides:
side = tuple(side)
sides = tuple(sides)
for y in range(self.outimage.size[1]):
row1 = self._rowSizer(0,y,[],xlen-1)
row2 = self._rowSizer(0,y,[],ylen-1)
for x in range(self.outimage.size[0]):
if result is not None:
break
if (x + xlen) <= self.outimage.size[0]: #Top and Bottom check.
row1.append(self.processor.outdata[x+len(row1),y])
flag, if0, if2 = self._compareRow(sides[0], sides[2], row1)
if flag and if0: result = x, y, 0
if flag and if2: result = x, y, 2
if (x + ylen) <= self.outimage.size[0]:
row2.append(self.processor.outdata[x+len(row2),y])
flag, if1, if3 = self._compareRow(sides[1], sides[3], row2)
if flag and if1: result = x, y, 1
if flag and if3: result = x, y, 3
del row1[0]
del row2[0]
if result is not None:
im = Image.new("RGBA", (self.outimage.size[0], self.outimage.size[0]))
imdata = im.load()
for y in range(smim.size[1]):
for x in range(smim.size[0]):
newx = result[0] + x
newy = result[1] + y
imdata[newx, newy] = smdata[x,y]
im.save(outfile)
self.exportMerge(outfile, outfile)
return result
def checkAndAct(self, img):
"""
`Author`: Bill Clark
The primary action method. This method takes an image and merges it onto the output data stored
in the class. For every pixel in each image, the class's pixelChecker is used to compare them.
If the check returns true, the class's pixelActor is called to act on the pixels. For every acted on
pixel pair, the method's counter is increased. This count is returned as a statistic.
`img`: An image file to be merged onto the class's image.
`return`: The number of modified pixels.
"""
compareimage = Image.open(img)
self.processor.comparedata = compareimage.load()
counter = 0
for y in range(self.outimage.size[1]):
for x in range(self.outimage.size[0]):
counter += self.processor.run(x, y, x, y)
return counter
def convert(self, *images):
"""
`Author`: Bill Clark
This method converts any number of given images to RGBA color format. Pixel comparision is done via
the rgb values, and requires the images to be in that format. The converted files are saved to
a Converts folder as to not fill ones input folder with temporary files.
`images`: The images that need to be converted.
`return`: A list of file paths leading to the convert images, which can passed to further methods.
"""
ret = []
count = 0
for image in images:
img = Image.open(image)
im = img.convert("RGBA")
split = image.split('/')
path = '/'.join(split[:-1]) + '/Converts/' + ''.join(split[-1:])
ret.append(path)
im.save(path)
count += 1
return ret
def show(self, image=None):
"""
`Author`: Bill Clark
Shows the image if an image is given, otherwise defaults to the class's image.
`image`: The image to show, defaults to the image contained in the class.
"""
if not image: image = self.outimage
image.show()
def save(self, image=None, outfile=None):
"""
`Author`: Bill Clark
Saves an image to disk. The image can be specified, other wise the class's image is defaulted to.
The outfile can also be optionally specified.
`image`: Defaults to the class's image unless specified. The image to be saved.
`outfile`: The location to save to. Defaults to the class's output path.
"""
if not image: image = self.outimage
if not outfile: outfile = self.outfile
image.save(outfile)
def printDiffSame(self, counter):
"""
`Author`: Bill Clark
Prints the different pixel percentage and the same pixel percentage.
`counter`: The count of changed pixels in a merge operation. Obtained from checkandact.
"""
print "Different Pixels:", counter, repr(round((counter/360000.)*100,2)) + '%', " Same Pixels:", \
360000-counter, repr(round(((360000-counter)/360000.)*100,2)) + '%'+ '\n'
if __name__ == "__main__":
debug = 0
inputs = ['Input/Camera 1.jpg', 'Input\Camera cropend.jpg']
m = Merger('Output/ImFuse.jpg')
m.processor = PixelProcess.ExtractPixelRemote()
m.processor.setActorCommand(PixelProcess.TakeNonEmptySecondCommand())
m.processor.setCheckCommand(PixelProcess.ColorDiffCommand())
m.processor.checkcmd.diffnum = 0
m.merge(inputs[0])
# m.merge()
print m.cropFind('foo.jpg', inputs[1])
# print "Number of pixels recorded.", len(m.processor.pixels)
#
# post = m.processor.getGroupedPixels()
#
# post.sortCount()
# post.filter()
#
# for p in post.generator():
# print p
#
# f = post.first()
# print f
#
# # for group in post: # Post the groups to the outimage.
# # for p in group.pixels:
# # imdata[p[0], p[1]] = m.processor.pixels[p]
#
# #Output the first group to it's own image.
# f.save('Output/Only Pixels.png', m.processor.pixels)
#
# m.processor.setActorCommand(PixelProcess.RedHighlightCommand())
#
# # m.exportMerge('Output/DifferenceFile.jpg', 'Output/One Fused Provided.jpg')
#
# m.save()
|
766ed7715a9ae969fdcc7718bf13839981ccdd4d | cccccccccccccc/Myleetcode | /49/groupanagrams.py | 990 | 3.65625 | 4 | """
timecomplexity = O(n*m) n=len(strs),m=len(s) s is item in strs spacecomplexity = O(n+m)
construct deflautdict deflautdict is a method from moudle collections can easy to use append() from List
use the deflautdict to contain result. iterate all s in strs, define tmp list count [0]*26, iterate every word in s
and do ord(c)-ord('a') let the result tobe count's index and add 1 to index
trans the count list into tuple and let it be dict's key and append the s Because tuple can be compared by the whole item.
finally return all res.values()
"""
from typing import List
from collections import defaultdict
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
res = defaultdict(list)
for s in strs:
count = [0]*26
for c in s:
count[ord(c)-ord('a')]+=1
res[tuple(count)].append(s)
return res.values()
A = Solution()
a = ["eat","tea","tan","ate","nat","bat"]
print(A.groupAnagrams(a)) |
908d5206ec6e0d288f038a9fc6f6006a083e442e | rebecca16/CYPAbigailAD | /libro/problemas_resueltos/capitulo1/ifelse.py | 299 | 3.90625 | 4 | edad = int (input("Dame tu edad: ") )
INE = bool (int (input("Tines INE (0 No / 1 Si)?: ") ) )
if edad >= 18 and INE == True:
print ("Es mayor de edad")
print ("Puede entrar al bar")
else:
print ("Eres menor de edad")
print ("Puedes ir a jugar Lol")
print ("Fin del programa")
|
e9e66f8a248e413ac15d93621b32cb2e164653e1 | ritesh-deshmukh/Algorithms-and-Data-Structures | /180Geeks/Strings/Permutations of a given string.py | 487 | 4.125 | 4 | # Given a string, print all permutations of a given string.
string = list('ABC')
def permutations(string, step = 0):
if step == len(string):
print ("".join(string), end=" ")
for i in range(step, len(string)):
string_copy = [character for character in string]
string_copy[step], string_copy[i] = string_copy[i], string_copy[step]
permutations(string_copy, step + 1)
print(f"Given string: {string}")
print("Permuatations:")
permutations(string)
|
fdfb5c6fdf991787b26fc3834f96832ab4a7fed1 | sushmithasushi/playerlevel | /HEXA.py | 127 | 3.75 | 4 | try:
a1=input()
a1=int(a1,16)
a1=str(a1)
if a1.isnumeric()==True:
print('yes')
except:
print('no')
|
43e84f0117eaa3cc6d31afccd211cd730c9cc002 | Toka-Taka/mill-db | /pymilldb/context/Argument.py | 1,166 | 3.9375 | 4 | import abc
class Argument(abc.ABC):
def __init__(self, name):
self.name = name
@abc.abstractmethod
def print(self):
pass
@abc.abstractmethod
def signature(self):
pass
class ArgumentParameter(Argument):
def __init__(self, name, parameter=None):
super().__init__(name)
self.parameter = parameter
@property
def print(self):
return self.parameter.name
@property
def signature(self):
return self.parameter.signature
class ArgumentValue(Argument):
@property
def print(self):
return
@property
def signature(self):
return
class ArgumentSequenceCurrent(Argument):
def __init__(self, name, sequence=None):
super().__init__(name)
self.sequence = sequence
@property
def print(self):
return
@property
def signature(self):
return
class ArgumentSequenceNext(Argument):
def __init__(self, name, sequence=None):
super().__init__(name)
self.sequence = sequence
@property
def print(self):
return
@property
def signature(self):
return
|
e9d5de9016239474c04185415bcb200b68a84568 | apurvdhadankar/Translator-with-python | /translator.py | 652 | 3.71875 | 4 | import tkinter as tk
from googletrans import Translator
win = tk.Tk()
win.title("Translator")
win.geometry("300x150")
def translation():
word = entry.get()
translator = Translator(service_urls=['translate.google.com'])
translation1 = translator.translate(word,dest="marathi")
label1 = tk.Label(win,text=f'Translated In Marathi : {translation1.text}',bg="yellow")
label1.grid(row=2,column=0)
label = tk.Label(win,text="Enter Word : ")
label.grid(row=0,column=0,sticky="W")
entry = tk.Entry(win)
entry.grid(row=1,column=0)
button = tk.Button(win,text="Translate",command=translation)
button.grid(row=1,column=2)
win.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.