blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
abba1dbd2ee82a32bf53986395d516462bf6c771 | CheukYuen/Leetcode-python-master | /Lintcode/Binary-search/Maximum Number in Mountain Sequence.py | 528 | 3.9375 | 4 | def mountainSequence(nums):
# Write your code here
if not nums or len(nums) == 0:
return None
start = 0
end = len(nums) - 1
while start + 1 < end:
mid1 = (end - start) / 2 + start
mid2 = end - (end - mid1) / 2
if nums[mid1] < nums[mid2]:
start = mid1 + 1
elif nums[mid1] > nums[mid2]:
end = mid2 - 1
else:
start = mid1
end = mid2
return max(nums[start], nums[end])
print mountainSequence([1, 3, 8, 5, 4])
|
bfa821532ce7980cded0593ba4abe188f0b252ab | rohanroy556/SpamFilter | /tkinter/event_button.py | 336 | 3.921875 | 4 | from tkinter import *
root = Tk()
def printName():
print("Hello my name is rohan")
def eventButton(event):
print("Yo Rohan")
button_1 = Button(root, text="Print my name", command=printName)
button_1.pack()
button_2 = Button(root, text="Event button")
button_2.bind("<Button-1>", eventButton)
button_2.pack()
root.mainloop() |
2746e22b25add1f703135e68f88929bf49c5a8df | rais2-pivotal/pythonsamples | /loopwhiledone_minmax.py | 370 | 3.90625 | 4 | #!/usr/bin/env python
answer = 0
numarray = []
while True:
answer = input("Enter a number: ")
if answer == 'done':
break
try:
val = int(answer)
numarray.append(val)
except ValueError:
print("Invalid input")
continue
print("Min from array is: " + str(min(numarray)) + " and Max from array is: " + str(max(numarray)))
|
c61687cc3193ff8ceb6f0a2908d4cd63fdc35cb2 | carogalvin/schedule_python | /rehearsals.py | 988 | 3.53125 | 4 | import dates
class RehearsalDate:
# date: string in the form "yyyy-mm-dd"
# actorList: a list of strings that are actor names
# sceneList: a list of strings that are scenes
def __init__(self, date, actorList, sceneList):
self.date = date
self.day = dates.dayOfWeek(date)
self.actorList = actorList
self.sceneList = sceneList
def __str__(self):
return "Date: " + self.date + "\nDay: " + dates.weekdays[self.day] + "\nActors Available: " + str(self.actorList) + "\nScenes: " + str(self.sceneList)
def addActor(self, actor):
self.actorList.append(actor)
def addScene(self, scene):
self.sceneList.append(scene)
def removeActor(self, actor):
for act in self.actorList:
if act == actor:
self.actorList.delete(act)
def removeScene(self, scene):
for scenes in self.sceneList:
if scenes == scene:
self.sceneList.delete(scenes)
|
9c669273f980d26fb6312af5423f8116d4d2e3d9 | smohorzhevskyi/Python | /First_homework_3.py | 723 | 4.03125 | 4 | """
Вывести символ * построчно, начиная с одной звездочки и, в зависимости от количества строк, заданных пользователем,
последовательно увеличивая на 1 звездочку на каждой новой строке. Если пользователь вводить числа меньшие 1 –
бросить исключение.
"""
def checknum(N):
if N < 0:
raise Exception()
N = int(input())
count = 0
try:
checknum(N)
except Exception as e:
print('Should be more than 1')
else:
while count <= N:
print('*' * count)
count += 1
|
91df76fd65b8139d98ea8798cbdf0b602dc136c1 | bodetc/CarND-Term1-Lessons | /Lesson7-MiniFlow/nn.py | 707 | 3.84375 | 4 | """
This script builds and runs a graph with miniflow.
There is no need to change anything to solve this quiz!
However, feel free to play with the network! Can you also
build a network that solves the equation below?
(x + y) + y
"""
from miniflow import *
x, y, z = Input(), Input(), Input()
f = Add(x, y, z)
g = Mul(x, y, z)
feed_dict = {x: 4, y: 5, z: 10}
sorted_nodes = topological_sort(feed_dict)
output = forward_pass(f, sorted_nodes)
# should output 19
print("{} + {} + {} = {} (according to miniflow)".format(feed_dict[x], feed_dict[y], feed_dict[z], output))
print("{} * {} * {} = {} (according to miniflow)".format(feed_dict[x], feed_dict[y], feed_dict[z], forward_pass(g, sorted_nodes)))
|
9a41c9fcb363dff199b0461573452484e84d2b98 | Zejjs/VigenereCrack | /vigenere.py | 11,289 | 3.9375 | 4 | import string
import languageFunctions
from frequencyFinder import english_frequency_score
from myMath import factors
def decipher_vigenere(cipher_text, key):
"""
Function deciphers a standard Vigenere encrypted cipher text using a key
Args:
cipher_text: string to be deciphered
key: string containing the key
Returns:
string: deciphered cipher text
"""
cipher_text = languageFunctions.format_for_analysis(cipher_text)
key = key.upper()
plaintext = []
key_index = 0
key_length = len(key)
alphabet_length = len(string.ascii_uppercase)
for index in range(len(cipher_text)):
if cipher_text[index] == " ":
plaintext.append(" ")
else:
cipher_value = string.ascii_uppercase.index(cipher_text[index])
key_value = string.ascii_uppercase.index(key[key_index % key_length])
key_index += 1
index_plaintext = (cipher_value - key_value) % alphabet_length
plaintext.append(string.ascii_uppercase[index_plaintext])
return "".join(plaintext)
def dictionary_attack(cipher_text, spaces=True):
"""
Function performs a dictionary attack on the cipher text.
Args:
cipher_text: string of text to be deciphered
spaces: bool saying whether the text contains spaces, defaults to True
Returns:
tuple containing the key and the plaintext
returns None, None if deciphering failed
"""
# Load the text and list of keys from the dictionary created by languageFunctions.py
cipher_text = languageFunctions.format_for_analysis(cipher_text)
key_list = list(languageFunctions.ENGLISH_DICTIONARY.keys())
# A dictionary attack takes a while, so the program tracks how deep into the dictionary it got so far
displayed_percent = 0
for key in key_list:
# Display how many % of the dictionary have we went through
curr_percent = int(key_list.index(key) / len(key_list) * 100)
if curr_percent > displayed_percent:
displayed_percent = curr_percent
print("Tried {:02}% of the words in the dictionary".format(displayed_percent))
# Try to decipher the text with a word from the dictionary
plaintext = decipher_vigenere(cipher_text, key)
# Check whether the resulting text is English and ask user for final confirmation whether deciphering is done
if languageFunctions.is_english(plaintext, spaces):
print("\nKey candidate: " + key)
print("Plaintext candidate:\n" + languageFunctions.find_words_in_nospace(plaintext))
while True:
response = input("\nPress C to continue looking for a key, or Enter to confirm the key choice: ")
if response == "":
return key, plaintext
if response.lower() == "c":
print("Looking for a new key...\n")
break
# Return a tuple of Nones if the attack fails
print("Failed to find a key using dictionary attack.")
return None, None
def find_likely_key_lengths(cipher_text, how_many=6):
"""
Function takes a string of cipher text, performs Kasiski examination to find likely key lengths
and returns them as a list
Args:
cipher_text: string of text to be analysed
how_many: int defining how many most likely keys should be returned, defaults to 6
Returns:
list: a list of integers denoting likely key lengths
"""
# Remove spaces and nonalpha chars from the text
text = languageFunctions.format_for_analysis(cipher_text, False)
# A dictionary that stores indexes of three to five character sequences appearing in the text
seq_dict = {}
# loops through character sequences of length 3, 4 and 5, and stores them in the dictionary.
# uses the sequences as keys, and indexes of sequences as values
for seq_length in range(3, 6):
for i in range(len(text) - seq_length + 1):
sequence = text[i:i + seq_length]
if sequence in seq_dict:
seq_dict[sequence].append(i)
else:
seq_dict[sequence] = [i]
spacing_set = set()
# goes through all the sequences in the seq_dict, removes those that only appear once,
# then adds the spacings between the remainder to the spacing_set
for key in seq_dict:
if len(seq_dict[key]) == 1:
continue
for i in range(len(seq_dict[key]) - 1):
for j in range(i + 1, len(seq_dict[key])):
spacing_set.add(seq_dict[key][j] - seq_dict[key][i])
factor_count_dict = {}
# for each spacing in the spacing set the function takes it's factors and stores them in the factor_count_dict
# the keys in the dictionary are the factors, the values are the counts. Most numerous factors are most likely to be
# the key length
# function discards factors of 1
for spacing in spacing_set:
for factor in factors(spacing):
if factor == 1:
continue
if factor in factor_count_dict:
factor_count_dict[factor] += 1
else:
factor_count_dict[factor] = 1
likely_key_lengths = []
# create a list of tuples, where each tuple is a factor and its count
for key in factor_count_dict:
likely_key_lengths.append((key, factor_count_dict[key]))
# sort the list by count in descending order
likely_key_lengths.sort(key=lambda t: t[1], reverse=True)
# strip the counts from the tuples, turning the list of tuples into a list of ints, sorted by count
for i in range(min(how_many, len(likely_key_lengths))):
likely_key_lengths[i] = likely_key_lengths[i][0]
# returns a list of n most likely lengths of the key, n equal to how_many, defaults to 6
return likely_key_lengths[:min(how_many, len(likely_key_lengths))]
def get_every_nth_letter(cipher_text, n):
"""
Function returns a list of n strings, each created by taking every nth letter.
For example:
get_every_nth_letter("ABCDEFGHI", 3)
would output:
["ADG", "BEH", "CFI")
Args:
cipher_text: string of text to be divided into substrings
n: number of strings to output
Returns:
list: a list with n elements, each a string made by taking every nth character
"""
text = languageFunctions.format_for_analysis(cipher_text, False)
list_of_strings = []
i = 0
while i < n:
list_of_strings.append([])
i += 1
# Function uses lists and later joins them into strings for speed
for i in range(len(text)):
list_of_strings[i % n].append(text[i])
for i in range(len(list_of_strings)):
list_of_strings[i] = "".join(list_of_strings[i])
return list_of_strings
def produce_permutations(list_of_key_lists):
"""
A recursive function that takes a list of lists of characters, and creates all possible combinations of words
using them, and outputs them in a string. For example:
produce_permutations([['A', 'B', 'C'], ['D'], ['E', 'F']])
would output:
["ADE", "ADF", "BDE", "BDF", "CDE", "CDF"]
Args:
list_of_key_lists: a list of lists, each inner list holds all the possible characters to be used at a given
position in the
Returns:
A list of strings, each composed of characters from sublists in the list provided as argument
"""
# base case: if length of list is 1, return the list
if len(list_of_key_lists) == 1:
return list_of_key_lists[0]
# if the list is longer than 1, take characters from first sublist, and append the function's call to itself,
# omitting the first sublist
else:
key_list = []
for char_a in list_of_key_lists[0]:
for char_b in produce_permutations(list_of_key_lists[1:]):
key_list.append(char_a + char_b)
return key_list
def find_possible_keys(cipher_text, key_length):
"""
Function slices the cipher text into substrings equal to length of key, and then treats each substring as a standard
Caesar cipher.
Each Caesar cipher is brute forced with every letter of the alphabet, then the character frequency distribution
in each brute force attempt is analysed and compared with English distribution. The keys that lead to
"most English" distributions are returned in a list
Args:
cipher_text: string of text to be deciphered
key_length: int, length of key with which the cipher text is encoded
Returns:
list: a list of strings, each a potential key that leads to an English-like distribution of letters.
"""
text = languageFunctions.format_for_analysis(cipher_text, False)
substring_list = get_every_nth_letter(text, key_length)
alphabet = string.ascii_uppercase
list_of_key_lists = []
for i in range(key_length):
key_list = list()
highest_match_score = 0
substring = substring_list[i]
for letter in alphabet:
freq_score = english_frequency_score(decipher_vigenere(substring, letter))
if freq_score > highest_match_score:
highest_match_score = freq_score
key_list.clear()
key_list.append(letter)
elif freq_score == highest_match_score:
key_list.append(letter)
list_of_key_lists.append(key_list)
list_of_keys = produce_permutations(list_of_key_lists)
return list_of_keys
def brute_force_with_list(cipher_text, list_of_keys, spaces=True):
"""
Function takes a cipher text and a list of keys, then tries each key until a solution in English is found.
Args:
cipher_text: string, the text to be deciphered
list_of_keys: a list of strings, where each string is a key to be tried
spaces: optional bool, denotes whether cipher_text has spaces. Defaults to True.
Returns:
tuple: a tuple of two strings, the first one being the key, second one the plaintext.
returns a tuple of Nones if no solution is found.
"""
text = languageFunctions.format_for_analysis(cipher_text)
key_list = list_of_keys
for key in key_list:
plaintext = decipher_vigenere(text, key)
if languageFunctions.is_english(plaintext, spaces):
print("Key candidate: " + key)
print("Plaintext candidate:\n" + languageFunctions.find_words_in_nospace(plaintext))
while True:
response = input("\nPress C to continue looking for a key, or Enter to confirm the key choice: ")
if response == "":
return key, plaintext
if response.lower() == "c":
print("Looking for a new key...\n")
break
print("Failed to find a key using frequency analysis.")
return None, None
|
80cf71037f56b17cade8bb498fe6c95a06c7bd29 | nkiryanov/ya-algorithms | /2-b/a_max_num.py | 244 | 3.65625 | 4 | def main():
x = -1
max = 0
while x != 0:
x = int(input())
if x == max:
count += 1
if x > max:
max = x
count = 1
print(count)
if __name__ == "__main__":
main() |
a8eef524c257d159ab49712885ea29456ee84c7e | nguyenhi1/comp110-21f-workspace | /lessons/memory_diagram1_Q1.py | 519 | 3.8125 | 4 |
def f(x: int, y: int) -> int:
if x + y > 10:
print("howdy!")
return x
else:
return x + y
def g(x: int) -> int:
if x % 2 == 0:
print("It's even.")
x = x + 1
else:
x = x * 2
return x
def bar(x: int, y: int) -> int:
if x > y:
print("woohoo!")
x = x * y
if x % 2 == 0:
x = x + 1
return x
else:
print("110")
x = x + 5
return x
print(str(bar(g(8), f(3,4)))) |
80afd7553c779399471076378320e7d4b45d90ff | geriwald/coding-exercises | /DailyCodingProblem/P01_matchingPairs.py | 602 | 4.03125 | 4 | # Good morning! Here's your coding interview problem for today.
# This problem was recently asked by Google.
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
# Bonus: Can you do this in one pass?
nums = (10, 15, 3, 7)
k = 17
def findPair(nums,goal):
comp=list()
for num in nums:
if num in comp:
print("%d+%d" % (num,goal-num))
return True
else:
comp.append(goal-num)
return False
print(findPair(nums,k)) |
bf9e5cc350182cd100d4ebf8d9ef72d2048f4997 | MrzvUz/Python | /Python_Entry/test.py | 5,180 | 4 | 4 | # def checkDriverAge():
# age = input("What is your age?: ")
# if int(age) < 18:
# print("Sorry, you are too young to drive this car. Powering off")
# elif int(age) > 18:
# print("Powering On. Enjoy the ride!");
# elif int(age) == 18:
# print("Congratulations on your first year of driving. Enjoy the ride!")
# checkDriverAge()
# def test(a):
# return a * 2
# print(test(4))
# def say_hello(name, role):
# return f"Hello {name}! How is your {role} career is going?"
# print(say_hello("Ali", "DevOps"))
# def highest_even(li):
# even_hi_num = []
# for num in li:
# if num % 2 == 0:
# even_hi_num.append(num)
# return max(even_hi_num)
# print(highest_even([10, 2, 3, 4, 5, 6, 8, 10]))
#Given the below class:
# class Cat:
# species = 'mammal'
# def __init__(self, name, age):
# self.name = name
# self.age = age
# # 1 Instantiate the Cat object with 3 cats
# cat1 = Cat("Jimmy", 10)
# cat2 = Cat("Timmy", 15)
# cat3 = Cat("Pimmy", 18)
# # 2 Create a function that finds the oldest cat
# def oldest_cat(*args):
# return max(args)
# print(f"The oldest cat is {oldest_cat(cat1.age, cat2.age, cat3.age)} years old.")
# # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
# class Cat:
# species = 'mammal'
# def __init__(self, name, age):
# self.name = name
# self.age = age
# # Instantiate the Cat object with 3 cats
# peanut = Cat("Peanut", 3)
# garfield = Cat("Garfield", 5)
# snickers = Cat("Snickers", 1)
# # Find the oldest cat
# def get_oldest_cat(*args):
# return max(args)
# # Output
# print(f"The oldest cat is {get_oldest_cat(peanut.age, garfield.age, snickers.age)} years old.")
# class Pets():
# animals = []
# def __init__(self, animals):
# self.animals = animals
# def walk(self):
# for animal in self.animals:
# print(animal.walk())
# class Cat():
# is_lazy = True
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def walk(self):
# return f'{self.name} is just walking around'
# class Simon(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# class Sally(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# #1 Add nother Cat
# class Jimmy(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# #2 Create a list of all of the pets (create 3 cat instances from the above)
# my_cats = []
# #3 Instantiate the Pet class with all your cats use variable my_pets
# cat_Simon = Simon("I'm Simon", 10)
# cat_Sally = Sally("I'm Sally", 15)
# cat_Jimmy = Jimmy("I'm Jimmy", 20)
# # def Cat(**kwargs):
# # my_cats.append(kwargs)
# #4 Output all of the cats walking using the my_pets instance
# print(f"{cat_Simon.walk(), cat_Sally.walk(), cat_Jimmy.walk()}")
### Solution
# class Pets():
# animals = []
# def __init__(self, animals):
# self.animals = animals
# def walk(self):
# for animal in self.animals:
# print(animal.walk())
# class Cat():
# is_lazy = True
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def walk(self):
# return f'{self.name} is just walking around'
# class Simon(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# class Sally(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# #1 Add nother Cat
# class Suzy(Cat):
# def sing(self, sounds):
# return f'{sounds}'
# #2 Create a list of all of the pets (create 3 cat instances from the above)
# my_cats = [Simon('Simon', 4), Sally('Sally', 21), Suzy('Suzy', 1)]
# #3 Instantiate the Pet class with all your cats
# my_pets = Pets(my_cats)
# #4 Output all of the cats singing using the my_pets instance
# my_pets.walk()
# my_student = {
# "name": "Rolf Smith",
# "grades": [70, 88, 90, 99]
# }
# def average(student):
# return sum(student["grades"]) / len(student["grades"])
# print(average(my_student))
# def power_of_two():
# user_input = input('Please enter a number: ')
# try:
# n = float(user_input)
# except ValueError:
# print('Your input was invalid.')
# finally:
# n_square = n ** 2
# return n_square
# print(power_of_two())
def interact():
while True:
try:
user_input = int(input('Please input an integer:')) # try to turn user input into an integer
except ValueError:
print('Please input integers only.') # print a message if user didn't input an integer
else:
print('{} is {}.'.format(user_input, 'even' if user_input % 2 == 0 else 'odd')) # print even/odd if the user input an integer
finally: # regardless of the previous input being valid or not
user_input = input('Do you want to play again? (y/N):') # ask if the user wants to play again
if user_input != 'y': # quit if the user didn't input `y`
print('Goodbye.')
break # break the while loop to quit |
5dfb86530af8899659e2207bd94a706f2d428732 | ZhouZoey/LeetCode-python | /leet13_RomanToInteger.py | 599 | 3.625 | 4 | import math
class Solution(object):
def romanToInt(self, s: str) -> int:
tmp = {"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000}
total = 0
for i in range(len(s) - 1):
if tmp[s[i]] < tmp[s[i+1]]:
total -= tmp[s[i]]
else:
total += tmp[s[i]]
total += tmp[s[-1]]
return total
if __name__ == "__main__":
s = 'mcmxciv'
a = Solution()
b = a.romanToInt(s)
print("b") |
7dd3d6e7af3dd86d230e5f29b4c9c5fbff512027 | Angel-cuba/Python-UDEMY | /ColeccionesMetodos/metodolista.py | 352 | 4.21875 | 4 | #append...agrega un elemento sobre el final
lista = ["Angel", "Luis", "Araoz"]
print(lista)
lista.append("Vera")
print(lista)
###################
##metodo extend
lista1 = ["Maria", "Yamil", "Dupi"]
lista.extend(lista1)
print(lista)
#################
# lista.count("Maria")
lista1 = ["Maria", "Yamil", "Dupi"]
lista1.insert(1, "Hola")
print(":",lista1)
|
8214df322b0fd8476857b0c3f64acf66822d7159 | maxfactory/pythontest | /python/6/6.4/aliens.py | 949 | 3.765625 | 4 | # # 字典列表
# alien_0 = {'color':'green','points':5}
# alien_1 = {'color':'yellow','points':10}
# alien_2 = {'color':'red','points':15}
# aliens = [alien_0,alien_1,alien_2]
# for alien in aliens:
# print(alien)
#--------------------------------------
# 使用range()生成30个外星人
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
# 对前三个的数值进行修改
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 10
alien['speed'] = 'medium'
# 显示前五个外星人
for alien in aliens[:10]:
if alien['color'] == 'green':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens:" + str(len(aliens)))
|
7cf128b2711edbc944c733114947819282dee77a | ZhiyuSun/leetcode-practice | /剑指Offer/51_数组中的逆序对.py | 4,829 | 3.609375 | 4 | """
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
# 2021.04.03 可以做,但是超时
class Solution:
def reversePairs(self, nums: List[int]) -> int:
if len(nums) < 2: return 0
count = 0
for i in range(len(nums)-1):
for j in range(i, len(nums)):
if nums[i] > nums[j]:
count += 1
return count
# 2021.04.03 官方解答,归并排序的思路,可惜我没看懂
class Solution2:
def mergeSort(self, nums, tmp, l, r):
if l >= r:
return 0
mid = (l + r) // 2
inv_count = self.mergeSort(nums, tmp, l, mid) + self.mergeSort(nums, tmp, mid + 1, r)
i, j, pos = l, mid + 1, l
while i <= mid and j <= r:
if nums[i] <= nums[j]:
tmp[pos] = nums[i]
i += 1
inv_count += (j - (mid + 1))
else:
tmp[pos] = nums[j]
j += 1
pos += 1
for k in range(i, mid + 1):
tmp[pos] = nums[k]
inv_count += (j - (mid + 1))
pos += 1
for k in range(j, r + 1):
tmp[pos] = nums[k]
pos += 1
nums[l:r+1] = tmp[l:r+1]
return inv_count
def reversePairs(self, nums: List[int]) -> int:
n = len(nums)
tmp = [0] * n
return self.mergeSort(nums, tmp, 0, n - 1)
# 2021.04.03 民间解法1
# https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/solution/bao-li-jie-fa-fen-zhi-si-xiang-shu-zhuang-shu-zu-b/
# 视频讲解笔记
# 高级排序算法(归并,快排)里,能够看到非常明显的阶段排序结果的算法就是归并排序
# 第二个数组合并回去的时候,看下第一个数组里还剩多少个元素没有合并回去
# 2021.04.03 民间大神解法
# 后有序数组中元素出列的时候,计算逆序个数
from typing import List
class Solution3:
def reversePairs(self, nums: List[int]) -> int:
size = len(nums)
if size < 2:
return 0
# 用于归并的辅助数组
temp = [0 for _ in range(size)]
return self.count_reverse_pairs(nums, 0, size - 1, temp)
def count_reverse_pairs(self, nums, left, right, temp):
# 在数组 nums 的区间 [left, right] 统计逆序对
if left == right:
return 0
mid = (left + right) >> 1
left_pairs = self.count_reverse_pairs(nums, left, mid, temp)
right_pairs = self.count_reverse_pairs(nums, mid + 1, right, temp)
reverse_pairs = left_pairs + right_pairs
# 代码走到这里的时候,[left, mid] 和 [mid + 1, right] 已经完成了排序并且计算好逆序对
if nums[mid] <= nums[mid + 1]:
# 此时不用计算横跨两个区间的逆序对,直接返回 reverse_pairs
return reverse_pairs
reverse_cross_pairs = self.merge_and_count(nums, left, mid, right, temp)
return reverse_pairs + reverse_cross_pairs
def merge_and_count(self, nums, left, mid, right, temp):
"""
[left, mid] 有序,[mid + 1, right] 有序
前:[2, 3, 5, 8],后:[4, 6, 7, 12]
只在后面数组元素出列的时候,数一数前面这个数组还剩下多少个数字,
由于"前"数组和"后"数组都有序,
此时"前"数组剩下的元素个数 mid - i + 1 就是与"后"数组元素出列的这个元素构成的逆序对个数
"""
for i in range(left, right + 1):
temp[i] = nums[i]
i = left
j = mid + 1
res = 0
for k in range(left, right + 1):
if i > mid:
nums[k] = temp[j]
j += 1
elif j > right:
nums[k] = temp[i]
i += 1
elif temp[i] <= temp[j]:
# 此时前数组元素出列,不统计逆序对
nums[k] = temp[i]
i += 1
else:
# assert temp[i] > temp[j]
# 此时后数组元素出列,统计逆序对,快就快在这里,一次可以统计出一个区间的个数的逆序对
nums[k] = temp[j]
j += 1
# 例:[7, 8, 9][4, 6, 9],4 与 7 以及 7 后面所有的数都构成逆序对
res += (mid - i + 1)
return res
|
9a433e00068611293acaa0f8bf8c6250905050fb | kesarb/leetcode-summary-python | /practice/solution/0605_can_place_flowers.py | 526 | 3.625 | 4 | class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
count = 0
value_list = [0] + flowerbed + [0]
res = False
for i in range(1, len(value_list) - 1):
if value_list[i - 1] == value_list[i] == value_list[i + 1] == 0:
value_list[i] = 1
count += 1
if count >= n:
res = True
return res |
5ab33d727ccdfe97ec6abe974b0f7b9ce7026fec | SanyaGera/Pyhton-codes | /Tuples.py | 266 | 4.125 | 4 | #Given an integer, n , and n space-separated integers as input, create a tuple,t, of those n integers. Then compute and print the result of hash(t).
#Solution
n = int(raw_input())
integer_list = map(int, raw_input().split())
t=tuple(integer_list)
print(hash(t))
|
928b351778f548cf9d3f1dd4a7457c37719caf10 | philipdongfei/Think-python-2nd | /Chapter09/Ex9_6.py | 879 | 3.96875 | 4 | def is_abecedarian(word):
word = word.lower()
preletter = word[0]
for letter in word[1:]:
if letter < preletter:
return False
else:
preletter = letter
return True
def word_is_abecedarian(path):
fin = open(path)
count = 0
total = 0
smallest = ''
for line in fin:
word = line.strip()
total += 1
if is_abecedarian(word):
print(word)
length = len(smallest)
if length == 0:
smallest = word
elif length > len(word):
smallest = word
count += 1
print('smallest word:', smallest)
return count / total
def main():
path = 'words.txt'
#letters = input('uses all letters > ')
print("words is abecedarian: %9.7f" %word_is_abecedarian(path))
if __name__ == '__main__':
main()
|
ef0f7a993719f68e6b29b95015a454393e54d295 | GaoZWei/Python_Study | /code/json/json3.py | 199 | 3.796875 | 4 | # 序列化 python=>json
import json
student = [
{'name': 'gao', 'age': 18, 'flag': False},
{'name': 'gao', 'age': 18}]
json_str = json.dumps(student)
print(json_str)
print(type(json_str))
|
c10301b8b772b30c045b102d736f988705136058 | Parkhyunseo/PS | /SDS/ds/ds_F_2504.py | 1,110 | 3.5625 | 4 | import sys
text = list(input())
stack = []
small = 0
big = 0
temp = 1
total = 0
for i in range(len(text)):
if text[i] == '(':
stack.append('(')
small += 1
temp *= 2
if i < len(text) - 1:
if text[i+1] == ')':
total += temp
elif text[i] == '[':
stack.append('[')
big += 1
temp *= 3
if i < len(text) - 1:
if text[i+1] == ']':
total += temp
elif text[i] == ')':
if len(stack) <= 0:
print(0)
sys.exit()
top = stack.pop()
if top != '(':
print(0)
sys.exit()
small -= 1
temp //= 2
else:
if len(stack) <= 0:
print(0)
sys.exit()
top = stack.pop()
if top != '[':
print(0)
sys.exit()
big -= 1
temp //= 3
if len(stack) > 0 or small !=0 or big !=0:
print(0)
else:
print(total)
|
b71206e5162df0164dac57e6d160181fb12f5849 | hodinhtan/python_advance_concept | /abstract-class.py | 926 | 4.03125 | 4 | from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def draw(self):
pass
def getArea(self):
pass
def getCircuit(self):
pass
@abstractmethod
def xaoxao(self):
pass
class Rectangle(Polygon):
def __init__(self, w ,h ):
self.w = w
self.h = h
def draw(self):
print("rectangle draw")
def getArea(self):
return self.w * self.h
def getCircuit(self):
return (self.w+self.h) * 2
def xaoxao(self):
print ("fuck u bitch")
class Square(Polygon):
def __init__(self, side ):
self.side = side
def draw(self):
print("rectangle draw")
def getArea(self):
return self.side ** 2
def getCircuit(self):
return (self.side * 4)
def xaoxao(self):
print ("love u bitch")
rec = Rectangle(2,3)
sq = Square(5)
print(rec.getArea(), sq.getCircuit()) |
4a5258f9feed4dd309de54dfc44b70be154b5f9b | paulghaddad/solve-it | /exercism/python/collatz-conjecture/collatz_conjecture.py | 564 | 4.1875 | 4 | ## Iterative Solution
def steps(number):
if number < 1:
raise ValueError('The number must be greater than 0')
steps = 0
while number > 1:
steps += 1
if number%2 == 0:
number //= 2
else:
number = 3*number + 1
return steps
# Recursive Solution
def steps(number):
if number < 1:
raise ValueError('The number must be greater than 0')
if number == 1:
return 0
if number%2 == 0:
return 1 + steps(number//2)
else:
return 1 + steps(3*number + 1)
|
353010ef12264ff6722cb11bfd6210c667832296 | TechOpsX/python-function | /4_return_value.py | 391 | 3.71875 | 4 | def no_return_func():
a = 1
def return_one_value():
return 1
def return_two_value():
return 1, 2
if __name__ == "__main__":
print(no_return_func())
print(return_one_value())
print(return_two_value())
a, b = return_two_value()
print(a, b)
# 只接受一个值,可以用_作为占位符,放弃接收值
_, c = return_two_value()
print(c)
|
e487b11b85d3c93f078511b59fc98d03791a091c | shiryu92/pdf | /map.py | 586 | 3.625 | 4 | '''
Author: shiryu92
Module: Map file to memory
Date: 30/07/2015
'''
import mmap
class MFile:
''' Map file to memory '''
def __init__(self, filepath);
''' Init file path '''
self.filepath = filepath
self.file = None
self.map = None
def mapfile(self):
''' Map file '''
try:
file = open(self.filepath)
map = mmap.mmap(file.fileno(), 0, access = mmap.ACCESS_READ)
return map
except Exception:
return None
def unmap(self):
''' Unmap file '''
if self.map != None:
self.map.close()
if self.file != None:
self.file.close()
|
415ac9e48fd0b333878687fe110d5811d2649848 | cholojuanito/image-processing | /lighting-shading/lighting.py | 7,623 | 3.59375 | 4 | """ Modified code from Peter Colling Ridge
Original found at http://www.petercollingridge.co.uk/pygame-3d-graphics-tutorial
"""
import pygame
import numpy as np
import wireframe as wf
import basicShapes as shape
from math import pi
class WireframeViewer(wf.WireframeGroup):
""" A group of wireframes which can be displayed on a Pygame screen """
def __init__(self, width, height, name="Wireframe Viewer"):
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height))
pygame.display.set_caption(name)
self.wireframes = {}
self.wireframe_colours = {}
self.object_to_update = []
self.displayNodes = False
self.displayEdges = True
self.displayFaces = True
self.perspective = False
self.eyeX = self.width/2
self.eyeY = 100
self.light_color = np.array([1, 1, 1])
self.view_vector = np.array([0, 0, -1])
self.light_vector = np.array([0, 0, -1])
self.background = (10, 10, 50)
self.nodeColour = (250, 250, 250)
self.nodeRadius = 4
self.control = 0
self.m_gloss = 10
# The following three coeffecients must add up to 1.0
self.m_diff = 0.4
self.m_spec = 0.5
self.m_amb = 0.1
def addWireframe(self, name, wireframe):
self.wireframes[name] = wireframe
# If colour is set to None, then wireframe is not displayed
self.wireframe_colours[name] = (250, 250, 250)
def addWireframeGroup(self, wireframe_group):
# Potential danger of overwriting names
for name, wireframe in wireframe_group.wireframes.items():
self.addWireframe(name, wireframe)
def display(self):
self.screen.fill(self.background)
for name, wireframe in self.wireframes.items():
nodes = wireframe.nodes
if self.displayFaces:
for (face, color) in wireframe.sortedFaces():
v1 = (nodes[face[1]] - nodes[face[0]])[:3]
v2 = (nodes[face[2]] - nodes[face[0]])[:3]
normal = np.cross(v1, v2)
normal /= np.linalg.norm(normal)
towards_us = normal.dot(self.view_vector)
# Only draw faces that face us
if towards_us > 0:
amb = self.light_color * (self.m_amb * color)
# Assume the face is in shadow
diff = np.array([0.0, 0.0, 0.0])
spec = np.array([0.0, 0.0, 0.0])
if (normal.dot(self.light_vector) > 0):
# Face normal is not in shadow
reflect_vector = 2 * \
(self.light_vector.dot(normal)) * \
normal - self.light_vector
diff = self.light_color * \
(self.m_diff * color) * \
normal.dot(self.light_vector)
spec = self.light_color * \
(self.m_spec * color) * \
self.view_vector.dot(
reflect_vector) ** self.m_gloss
light_total = np.add(amb, diff)
light_total = np.clip(
np.add(light_total, diff), 0, 255)
pygame.draw.polygon(self.screen, light_total, [
(nodes[node][0], nodes[node][1]) for node in face], 0)
if self.displayEdges:
for (n1, n2) in wireframe.edges:
if self.perspective:
if wireframe.nodes[n1][2] > -self.perspective and nodes[n2][2] > -self.perspective:
z1 = self.perspective / \
(self.perspective + nodes[n1][2])
x1 = self.width/2 + z1 * \
(nodes[n1][0] - self.width/2)
y1 = self.height/2 + z1 * \
(nodes[n1][1] - self.height/2)
z2 = self.perspective / \
(self.perspective + nodes[n2][2])
x2 = self.width/2 + z2 * \
(nodes[n2][0] - self.width/2)
y2 = self.height/2 + z2 * \
(nodes[n2][1] - self.height/2)
pygame.draw.aaline(
self.screen, color, (x1, y1), (x2, y2), 1)
else:
pygame.draw.aaline(
self.screen, color, (nodes[n1][0], nodes[n1][1]), (nodes[n2][0], nodes[n2][1]), 1)
if self.displayNodes:
for node in nodes:
pygame.draw.circle(self.screen, color, (int(
node[0]), int(node[1])), self.nodeRadius, 0)
pygame.display.flip()
def keyEvent(self, key):
if key == pygame.K_a:
# print("a is pressed")
temp = self.light_vector
temp = np.insert(temp, 3, 1)
self.light_vector = np.dot(temp, wf.rotateYMatrix(-pi/16))[:-1]
if key == pygame.K_d:
# print("d is pressed")
temp = self.light_vector
temp = np.insert(temp, 3, 1)
self.light_vector = np.dot(temp, wf.rotateYMatrix(pi/16))[:-1]
if key == pygame.K_w:
# print("w is pressed")
temp = self.light_vector
temp = np.insert(temp, 3, 1)
self.light_vector = np.dot(temp, wf.rotateXMatrix(pi/16))[:-1]
if key == pygame.K_s:
# print("s is pressed")
temp = self.light_vector
temp = np.insert(temp, 3, 1)
self.light_vector = np.dot(temp, wf.rotateXMatrix(-pi/16))[:-1]
if key == pygame.K_q:
# print("q is pressed")
temp = self.light_vector
temp = np.insert(temp, 3, 1)
self.light_vector = np.dot(temp, wf.rotateZMatrix(pi/16))[:-1]
if key == pygame.K_e:
# print("e is pressed")
temp = self.light_vector
temp = np.insert(temp, 3, 1)
self.light_vector = np.dot(temp, wf.rotateZMatrix(-pi/16))[:-1]
return
def run(self):
""" Display wireframe on screen and respond to keydown events """
running = True
key_down = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
key_down = event.key
elif event.type == pygame.KEYUP:
key_down = None
if key_down:
self.keyEvent(key_down)
self.display()
self.update()
pygame.quit()
resolution = 52
viewer = WireframeViewer(600, 400)
viewer.addWireframe('sphere', shape.Spheroid(
(300, 200, 20), (160, 160, 160), resolution=resolution))
# Colour ball
faces = viewer.wireframes['sphere'].faces
for i in range(int(resolution/4)):
for j in range(resolution*2-4):
f = i*(resolution*4-8) + j
faces[f][1][1] = 0
faces[f][1][2] = 0
viewer.displayEdges = False
viewer.run()
|
2b202bc07212a75fc08b4599a7bc9af41a9a9cef | odys-z/hello | /docs/_downloads/414531146a8ac482e05ce04ab1710685/q784.py | 1,846 | 4.21875 | 4 | '''
784. Letter Case Permutation
https://leetcode.com/problems/letter-case-permutation/
Given a string S, we can transform every letter individually to be lowercase or uppercase to create
another string.
Return a list of all possible strings we could create. You can return the output in any order.
Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: S = "3z4"
Output: ["3z4","3Z4"]
Example 3:
Input: S = "12345"
Output: ["12345"]
Example 4:
Input: S = "0"
Output: ["0"]
Constraints:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.
Created on 23 Feb 2021
@author: Odys Zhou
'''
from unittest import TestCase
from typing import List
class Solution:
''' 88.03%
'''
def letterCasePermutation(self, S: str) -> List[str]:
def btracking(s: str) -> List[str]:
if len(s) == 0: return []
elif len(s) == 1: return [s] if s.isdigit() else [s.lower(), s.upper()]
res = []
tracks = btracking(s[:-1])
for t in tracks:
if (s[-1].isdigit()):
res.append(t + s[-1])
else:
res.append(t + s[-1].lower())
res.append(t + s[-1].upper())
return res
return btracking(S)
if __name__ == '__main__':
t = TestCase()
s = Solution()
t.assertCountEqual(['a1b2', 'a1B2', 'A1b2', 'A1B2'], s.letterCasePermutation('a1b2'))
t.assertCountEqual(['3z4', '3Z4'], s.letterCasePermutation('3z4'))
t.assertCountEqual(['3z4', '3Z4'], s.letterCasePermutation('3Z4'))
t.assertCountEqual(['12345'], s.letterCasePermutation('12345'))
t.assertCountEqual(['0'], s.letterCasePermutation('0'))
t.assertCountEqual(['a', 'A'], s.letterCasePermutation('A'))
print('OK!') |
e19a9eecc148c13eaf86491cbde5a70313156500 | eronekogin/leetcode | /2023/minimum_skips_to_arrive_at_meeting_on_time.py | 790 | 3.640625 | 4 | """
https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/
"""
class Solution:
def minSkips(self, dist: list[int], speed: int, hoursBefore: int) -> int:
"""
dp[j] / speed stands for the minimum arrival time after j skips.
"""
N = len(dist)
dp: list[float] = [0] * (N + 1)
for i, d in enumerate(dist):
for j in range(N, -1, -1):
dp[j] += d
if i < N - 1:
dp[j] = (dp[j] + speed - 1) // speed * speed
if j:
dp[j] = min(dp[j], dp[j - 1] + d)
target = speed * hoursBefore
for i, t in enumerate(dp):
if t <= target:
return i
return -1
|
84f41ccdefd2d16b6cbae57b7cc57899b3b88561 | jee599/2D_TeamProject | /homework/turtle.py | 258 | 3.6875 | 4 | import turtle
t = turtle.Pen()
def star(n):
for i in range(n):
t.up()
t.goto(0,0)
t.right(360/n)
t.forward(100)
for j in range (5):
t.down()
t.right(144)
t.forward(30)
star(10)
|
c4de7d19db341d69cb1426c2d502461fd96caedc | franklarios/pycompsci | /chp1/chaos2point0.py | 328 | 3.90625 | 4 | # File: chaos2point0.py
# A simple program illustrating chaotic behavior. Uses 2.0 instead of 3.9
# original chaos.py script.
def main():
print("This program illustrates a chaotic function")
x = eval(input("Enter a number between 0 and 1: "))
for i in range(10):
x = 2.0 * x * (1-x)
print(x)
main()
|
3712344d3aa8e97838bd4338a3e10c733d02423c | hbferreira1/python-introduction | /exponenciacao.py | 307 | 3.828125 | 4 | def exponenciacao():
n1 = int(input("número: "))
n2 = int(input("elevado a: "))
for i in range(20):
print(n1 **n2)
n2 = n2 + 1
print(n1 ** n2)
if (n1 ** n2) >= 1000:
break
print("O número já é maior que 1000")
exponenciacao()
|
9d9089011cf2895fcb479a97fa99b6991b83ce59 | jaehyunan11/leetcode_Practice | /Amazon_LEETCODE/7.Reverse_Integer.py | 455 | 3.609375 | 4 | class Solution:
def reverse(self, x):
# int -> str -> int (change to str to flip and then change to int)
# [1:] due to -1 sign
result = int(str(x)[::-1]) if x >= 0 else -int(str(x)[1:][::-1])
if -2**31 <= result <= (2**31)-1:
return result
else:
return 0
# TIME: O(Log(n)) flip the str which is Log(N)
# Space : O(1) no extra space is used
S = Solution()
x = 123
print(S.reverse(x))
|
0f4fb8bbb3eb784938f6ef799a4740487af20fe8 | deniseicorrea/Aulas-de-Python | /python/ex052.py | 375 | 3.984375 | 4 | numero = int(input('Digite um número: '))
tot = 0
for c in range(1, numero + 1):
if numero % c == 0:
print('\033[33m', end= '')
tot += 1
else:
print('\033[31m', end= '')
print(f'{c}', end= ' ')
print(f'\n\033[mO número {numero} foi divisível {tot} vezes')
if tot == 2:
print('Número primo')
else:
print('Não é número primo') |
e49a7788363799cf47064f8a4862a7cc5fb8a1ba | tolgaouz/Standford-cs231n-Assignment-Solutions | /assignment1/cs231n/classifiers/softmax.py | 4,050 | 3.828125 | 4 | import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
num_data = X.shape[0]
num_class = W.shape[1]
scores = X.dot(W)
# subtracting the maximum score so we can stabilize the outcomes and avoid any calculation errors we might get
stabilized_scores = scores - np.amax(scores,axis=1,keepdims=True)
for i in range(num_data):
curr_stabilized_scores = stabilized_scores[i,:]
loss += -(curr_stabilized_scores[y[i]]) + np.log(np.sum(np.exp(curr_stabilized_scores)))
for j in range(num_class):
# took the derivative of softmax function w.r.t W for each Wj
delta_score = np.exp(curr_stabilized_scores[j])/np.sum(np.exp(curr_stabilized_scores))
if j == y[i]:
dW[:,j] += (-1 + delta_score)*X[i]
else:
dW[:,j] += delta_score*X[i]
loss /= num_data
loss += np.sum(W*W)*reg
#############################################################################
# END OF YOUR CODE #
#############################################################################
dW /= num_data
dW += W*2*reg
return loss, dW
def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.
Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
scores = X.dot(W)
num_data = X.shape[0]
num_class = W.shape[1]
#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################
stabilized_scores = scores - np.amax(scores,axis=1,keepdims=True)
true_class_scores = stabilized_scores[np.arange(stabilized_scores.shape[0]),y]
true_class_scores.shape = (stabilized_scores.shape[0],1)
loss_matrix = -true_class_scores + np.log(np.sum(np.exp(stabilized_scores),axis=1,keepdims=True))
loss = np.sum(loss_matrix)
loss /= num_data
loss += reg*np.sum(W*W)
delta_scores = np.exp(stabilized_scores)/ np.sum(np.exp(stabilized_scores), axis=1,keepdims=True)
delta_scores[np.arange(num_data),y] = delta_scores[np.arange(num_data),y] - 1
dW = np.dot(X.T,delta_scores)
dW /= num_data
dW += reg*W*2
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
|
c88c38a855e4ea3a0640503ce826777c6d158346 | tibigame/ShogiNotebook | /ShogiNotebook/util.py | 492 | 3.65625 | 4 | from typing import Tuple
def xor(x: bool, y: bool)-> bool:
"""排他的論理和"""
return x and not y or not x and y
def reverse_bw(pos: Tuple[int, int], is_black=True)-> Tuple[int, int]:
"""先後の符号を反転したタプルを返す"""
if is_black:
return pos
return 10 - pos[0], 10 - pos[1]
def d_print(string: str, debug_str="[Debug] ", is_debug=False):
"""デバッグプリント用"""
if is_debug:
print(f"{debug_str + string}")
|
569174fdb66ccaf8480775cd56c8acfea6d69444 | sshukla31/solutions | /dynamic_programming/max_sub_square_matrix.py | 2,150 | 4.1875 | 4 | """
Find Maximum Sub Square for a given matrix
1) Create a temp matrix of (row+1) * (col+1)
2) Fill up first row and col with 0
3) Start with [row+1][col+1] cell
4) If matrix[row][col] == 1, then,
min(
matrix[row-1][col-1],
matrix[row][col-1],
matrix[row-1][col-1]
) + 1
5) Keep a max_count variable to store max value derived from point 4
6) Return max_count
"""
def max_sub_square(matrix=None):
"""
Return max sub square for a given matrix
"""
if matrix is None:
return None
rows = len(matrix) + 1
cols = len(matrix[0]) + 1
max_count = 0
count_matrix = [[0 for col_index in range(cols)] for row_index in range(rows)]
for row_index in range(1, rows):
for col_index in range(1, cols):
if matrix[row_index - 1][col_index - 1] == 1:
count_matrix[row_index][col_index] = min(
count_matrix[row_index][col_index - 1],
count_matrix[row_index - 1][col_index],
count_matrix[row_index - 1][col_index - 1]
) + 1
max_count = max(max_count, count_matrix[row_index][col_index])
return max_count
if __name__ == "__main__":
print "############"
print "## Test 1 ##"
print "############"
matrix = [
[0, 1, 1, 0, 1],
[1, 1, 1, 0, 0],
[1, 1, 1, 1, 0],
[1, 1, 1, 0, 1]
]
expected_result = 3
actual_result = max_sub_square(matrix)
assert expected_result == actual_result
print "############"
print "## Test 2 ##"
print "############"
matrix = [
[0, 0, 1, 1, 1],
[1, 0, 1, 1, 1],
[0, 1, 1, 1, 1],
[1, 0, 1, 1, 1]
]
expected_result = 3
actual_result = max_sub_square(matrix)
assert expected_result == actual_result
print "############"
print "## Test 3 ##"
print "############"
matrix = [
[0, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 1],
[1, 1, 1, 1, 1]
]
expected_result = 4
actual_result = max_sub_square(matrix)
assert expected_result == actual_result
|
12a84a19ccadb409b56f117a820c8e853377a4a0 | ittoyou/1805 | /13day/列表清空.py | 95 | 3.75 | 4 | list = [1,2,3,4,5,6,7,8,9]
for i in range(len(list)-1,-1,-1):
list.pop(i)
print(list)
|
1def0b375d6b7f6d8ec10e58f8aefc784c923486 | Egan-eagle/python-exercises | /week1&2.py | 3,145 | 4.3125 | 4 | # Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
#COMMENT
Re: Week 2 task
by EGAN MTHEMBU - Saturday, 3 February 2018, 6:47 PM
C:\Users\egan\Desktop\fib.py\WEEK2>python test.py
My surname is Mthembu
The first letter M is number 77
The last letter u is number 117
Fibonacci number 194 is 15635695580168194910579363790217849593217
ord(c)
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example,ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
i.e
firstno = ord(first) M = 77
lastno = ord(last) U = 117
x = firstno + lastno = 194
Fibonacci number 194 is 15635695580168194910579363790217849593217
WEEK1 EXERCISE
# Egan Mthembu 24.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
x = 19
ans = fib(x)
print("Fibonacci number", x, "is", ans)
Re: Fibonacci exercise responses
by EGAN MTHEMBU - Wednesday, 24 January 2018, 11:12 PM
Egan : E + N = 19, Fibonacci Number = 4181
C:\Users\ppc\Desktop\Fibonacci>python fib3.py
Fibonacci number 19 is 4181# Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
#COMMENT
#Re: Week 2 task
#EGAN MTHEMBU - Saturday, 3 February 2018, 6:47 PM
#My surname is Mthembu
The first letter M is number 77
The last letter u is number 117
Fibonacci number 194 is 15635695580168194910579363790217849593217
ord(c)
Given a string repord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
i.e
firstno = ord(first) M = 77
lastno = ord(last) U = 117
x = firstno + lastno = 194
Fibonacci number 194 is 15635695580168194910579363790217849593217
##WEEK1 EXERCISE
# Egan Mthembu 24.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
x = 19
ans = fib(x)
print("Fibonacci number", x, "is", ans)
Re: Fibonacci exercise responses
by EGAN MTHEMBU - Wednesday, 24 January 2018, 11:12 PM
Egan : E + N = 19, Fibonacci Number = 4181
Fibonacci number 19 is 4181
|
856a725aae4747329aac945ad964500d52eca519 | Nafisa-tabassum2046/my-pycharm-project | /while loop use anis.py | 584 | 3.8125 | 4 | # i = 1
# while(i<=20):
# print(i)
# i = i+1
# print("program end for serial number")
# i= 1
# while(i<=100):
# print(i)
# i = i+2
# print("program end for odd number")
# i = 2
# while(i<=200):
# print(i)
# i = i+2
# print("program end for even number")
# #while use kore jog ar kaj#
# sum =0
# i = 1
# while (i<=4):
# sum = sum +i
# i = i+1
# print(sum)
n = int(input("Enter the last number: "))
sum = 0
i =int(input("enter the 1st number: "))
while (i <= n):
sum = sum +i
i = i + 1
print(sum)
|
605c154695d64ac41fd40fea6f8115bb4e62ba16 | btjanaka/algorithm-problems | /codejam/2020-qual-nesting-depth.py | 1,008 | 3.71875 | 4 | # Author: btjanaka (Bryon Tjanaka)
# Problem: (CodeJam) 2020-qual-nesting-depth
# Title: Nesting Depth
# Link: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/0000000000209a9f
# Idea: Similar to the classic balanced parentheses problem, except that we
# now keep track of an additional number telling the current depth. If the depth
# is too small for the next digit we encounter, we add on open parens, and if
# if it is too large, we add on closing parens.
# Difficulty: medium
# Tags: stack, greedy
for case in range(int(input())):
s = input().strip()
s2 = ""
cur_depth = 0
for ch in s:
x = int(ch)
if cur_depth < x:
while cur_depth < x:
s2 += "("
cur_depth += 1
elif cur_depth > x:
while cur_depth > x:
s2 += ")"
cur_depth -= 1
s2 += ch
while cur_depth > 0:
s2 += ")"
cur_depth -= 1
print("Case #{}: {}".format(case + 1, s2))
|
30870e39e580766e30728810f5907c507dc17c7c | henryztong/PythonSnippet | /数据库/sqlite3数据库/db_set.py | 1,023 | 4.125 | 4 | from sqlite3 import connect
# 定义一个数据库,生成在当前目录中
db_name = 'test.db'
# 创建连接
con = connect(db_name)
# 创建游标
cur = con.cursor()
# 创建表
# cur.execute('create table star (id integer,name text,age integer,address text)')
# # 设定数据
# rows = [(1,'小米',22,'北京'),(2,'小明',23,'天津'),(3,'小王',24,'成都')]
# # 遍历并插入数据
# for item in rows:
# cur.execute('insert into star (id,name,age,address) values (?,?,?,?)',item)
# # 提交修改内容
# con.commit()
# # 遍历并查询数据
# cur.execute('select * from star')
# for row in cur:
# print(row)
# 修改
# cur.execute('update star set age=? where id=?',(16,3))
# con.commit()
# # 遍历并查询数据
# cur.execute('select * from star')
# for row in cur:
# print(row)
# 删除
cur.execute('delete from star where id = ?',(3,))
con.commit()
# 遍历并查询数据
cur.execute('select * from star')
for row in cur:
print(row)
# 使用完数据库后关闭连接
con.close()
|
d13b652626ee2c553717b475d3946461b7a80ad7 | chengqiangaoci/back | /sp1/python全栈/面向对象编程/子类中调用父类方法.py | 1,545 | 4.125 | 4 | #__两个下划线开头,声明该方法为私有方法,不能在类地外部调用,即不能被实例调用
# class Vehicle():#定义交通工具
# Country = "China"
# def __init__(self,name,speed,load,power):
# self.name = name
# self.speed = speed
# self.load = load
# self.power = power
# def run(self):
# print("开动了")
# class Subway(Vehicle):#地铁
# def __init__(self,name,speed,load,power,line):
# # self.name = name
# # self.speed = speed
# # self.load = load
# # self.power = power
# Vehicle.__init__(self,name,speed,load,power)#调用父类的数据属性,但是要参数
# self.line = line#这是子类自己新增加的
# def show_info(self):
# Vehicle.run(self)#调用父类的函数属性
# print(self.name,self.line)
# line13 = Subway("武汉地铁","10KM/S",10000,"电",2)
# line13.show_info()
#super调用父类的关系
class Vehicle():#定义交通工具
Country = "China"
def __init__(self,name,speed,load,power):
self.name = name
self.speed = speed
self.load = load
self.power = power
def run(self):
print("开动了")
class Subway(Vehicle):#地铁
def __init__(self,name,speed,load,power,line):
# self.name = name
# self.speed = speed
# self.load = load
# self.power = power
super().__init__(name,speed,load,power)#super不需要self
self.line = line#这是子类自己新增加的
def show_info(self):
super().run()#调用父类的函数属性
print(self.name,self.line)
line13 = Subway("武汉地铁","10KM/S",10000,"电",2)
line13.show_info()
|
4576775d13176ae57a1fb0ea5e75b0af8a9cd7e6 | Nigirimeshi/leetcode | /0202_happy-number.py | 3,382 | 3.921875 | 4 | """
快乐数
标签:数学
链接:https://leetcode-cn.com/problems/happy-number
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:
对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
示例:
输入:19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
我的解题思路:
1. 暴力计算。
依次计算各位数字平方和,递归判断是否为 1。
用集合记录已出现过的平方和以及 n,若递归过程中出现重复数字,说明会无限循环,此时返回 False。
官方解法:
1. 用哈希集合检查循环。(通过:√)
每次计算各位数字平方和,最终会有以下 3 种可能:
- 最终得到 1。
- 无限循环。
- 值越来越大,最后接近无穷大。
对于 3 位数的数字,它不可能大于 243。
这意味着它要么被困在 243 以下的循环内,要么跌到 1。
4 位或 4 位以上的数字在每一步都会丢失一位,直到降到 3 位为止。
所以我们知道,最坏的情况下,算法可能会在 243 以下的所有数字上循环,
然后回到它已经到过的一个循环或者回到 1。
但它不会无限期地进行下去,所以我们排除第三种选择。
时间复杂度:O(243⋅3 + logn + loglogn + logloglogn)... = O(logn)。
空间复杂度:O(logn)。
2. 快慢指针检查环。
反复计算平方和实际得到的链是一个链表,只需要判断链表是否有环,即可判断无限循环计算的情况。
slow 指针每次移动 1 个结点,fast 每次移动 2 个结点。
- 若 slow 和 fast 相等,则存在环,返回 False;
- 若 fast 等于 1,则返回 True。
时间复杂度:O(logn)。
空间复杂度:O(1)。
"""
import unittest
from typing import Set
class Solution:
def is_happy(self, n: int) -> bool:
return self.compute(n, {n, })
def compute(self, n: int, nums: Set[int]) -> bool:
if n == 1:
return True
_sum = 0
while n > 0:
num = n % 10
_sum += num * num
n //= 10
if _sum in nums:
return False
nums.add(_sum)
return self.compute(_sum, nums)
class OfficialSolution:
def is_happy(self, n: int) -> bool:
"""快慢指针检查环。"""
slow = n
fast = self.get_next(n)
while fast != 1 and slow != fast:
slow = self.get_next(slow)
fast = self.get_next(self.get_next(fast))
return fast == 1
def get_next(self, n: int) -> int:
_sum = 0
while n > 0:
n, digit = divmod(n, 10)
_sum += digit ** 2
return _sum
class TestSolution(unittest.TestCase):
def setUp(self) -> None:
self.s = Solution()
def test_is_happy(self) -> None:
self.assertTrue(
self.s.is_happy(1)
)
self.assertTrue(
self.s.is_happy(19)
)
self.assertFalse(
self.s.is_happy(123)
)
if __name__ == '__main__':
unittest.main()
|
517e6b2b7806c3b6268e7c8d42991954ad9921ae | corey-marchand/madlib-cli | /madlib_cli/__init__.py | 1,350 | 4.25 | 4 |
def mad_lib_game():
Adjective_one = input("Enter a adjective: ")
Adjective_two = input("Enter another adjective: ")
Adjective_three = input("Enter another adjective: ")
Adjective_four = input("Enter another adjective: ")
Large_animal = input("Enter the name of a large animal: ")
Small_animal = input("Enter the name of a small animal: ")
girls_name = input("Enter a female name: ")
Adjective_five = input("Enter another adjective: ")
Adjective_six = input("Enter another adjective: ")
Plural_noun = input("Enter a plural noun: ")
Number = input("Enter a number between 1 and 50: ")
First_name = input("Enter a first name: ")
past_tense_verb = input("Enter a past tense verb: ")
print(f"I the {Adjective_one} and {Adjective_two} {First_name} have {past_tense_verb}{First_name}'s {Adjective_three} sister and plan to steal her {Adjective_four} {Plural_noun}!")
print(f"What are a {Large_animal} and backpacking {Small_animal} to do? Before you can help {girls_name}, you'll have to collect the {Adjective_five} {Plural_noun} and {Adjective_six} {Plural_noun} that open up the {Number} worlds connected to A {First_name} Lair.")
print(f"There are {Number} {Plural_noun} and {Number} {Plural_noun} in the game, along with hundreds of other goodies for you to find.")
mad_lib_game()
|
b0c1b193befa5949ad1de68086fa7c5ce0fe76a4 | kebingyu/python-shop | /the-art-of-programming-by-july/chapter1/string-permutation-3.py | 684 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
如果不是求字符的所有排列,而是求字符的所有组合,应该怎么办呢?
当输入的字符串中含有相同的字符串时,相同的字符交换位置是不同的排列,但是同一个组合。
举个例子,如果输入abc,它的组合有a、b、c、ab、ac、bc、abc。
"""
def combination1(word, length):#{{{
if length == 1:
return [word[0]]
else:
head = word.pop()
ret = [head]
comb = combination1(word, length - 1)
for _ in comb:
ret.extend([_, head + _])
return ret
#}}}
import sys
word = [_ for _ in sys.argv[1]]
print combination1(word, len(word))
|
6353c367270445fdbe93063a9b2b5acb37e76c72 | prajwal041/ProblemSolving | /Learning/Inno/matching.py | 809 | 3.609375 | 4 | from difflib import SequenceMatcher
def longestSubstring(str1, str2):
# initialize SequenceMatcher object with
# input string
seqMatch = SequenceMatcher(None, str1, str2)
# find match of longest sub-string
# output will be like Match(a=0, b=0, size=5)
match = seqMatch.find_longest_match(0, len(str1), 0, len(str2))
return str1[match.a: match.a + match.size]
# print longest substring
# if (match.size != 0):
# print(str1[match.a: match.a + match.size])
# else:
# print('No longest common sub-string found')
str = 'ab'
pre = 'b'
suf = 'a'
val1 = longestSubstring(str,pre)
val2 = longestSubstring(str,suf)
print(val1)
print(val2)
if str.index(val1)>str.index(val2):
print(val2)
print(str[str.index(val1[:1]):len(str)-str[::-1].index(val2[-1])])
|
6aea66f17ee283745e39085f1fb7975f481b09d3 | gregariouspanda/Julia-learns-python | /create_dictionary.py | 590 | 3.546875 | 4 | import sys
import string
def create_dictionary(file_name):
f = open(file_name,'r')
s = f.read()
rlst=s.split()
lst = ['$']
for word in rlst:
if word[-1] in string.punctuation:
lst.append(word[:-1])
if word[-1] == ',':
lst.append(word[-1])
else:
lst.append('$')
else:
lst.append(word)
words = {}
for index, word in enumerate(lst[:-1]):
if word not in words.keys():
words[word] = []
words[word].append(lst[index + 1])
return (words)
|
ed898d550613f1c9ca77d28c02eed6ec98c6d6fa | nosrefeg/Python3 | /mundo3/exercicios/089.py | 929 | 3.796875 | 4 | alunos = []
while True:
dados = [input('Digite o nome do aluno: '), [float(
input('Digite a primeira nota: ')), float(input('Digite a segunda nota: '))]]
alunos.append(dados[:])
confirm = input('Quer continuar? (S/N) ').strip().upper()
while confirm not in 'SN':
confirm = input('Quer continuar? (S/N) ').strip().upper()
if confirm == 'N':
print('==' * 30)
print(f'{"Nº":<5} {"Nome":^5} {"Média":>10}')
print('--' * 30)
for i in range(0, len(alunos)):
print(
f'{i:<5} {alunos[i][0]:^5} {(alunos[i][1][0] + alunos[i][1][1]) / 2:>10}')
print('--' * 30)
while True:
pos = int(input('Mostrar notas de qual aluno? (999 para parar) '))
if pos == 999:
break
if pos < len(alunos):
print(f'Notas de {alunos[pos][0]} são {alunos[pos][1]}')
break
|
da87ac782415f4e2fb3b3a493f3b07bc37f20093 | SARWAR007/PYTHON | /Python Projects/list_map.py | 271 | 3.921875 | 4 | def find_greater(list_all):
#desired_no = list_all[1]
for index in list_all:
if (index > 6):
print(index)
return index
list1 = [1,6,8,40,5,3,7]
number = 6
find_greater(list1)
print(list(filter(find_greater,[1,6,8,40,5,3,7])))
|
dc31e639ec8805a7175a690112fcd06527dafa8e | Aasthaengg/IBMdataset | /Python_codes/p02747/s965569589.py | 235 | 3.625 | 4 | s = str(input())
if len(s)%2:
print('No')
exit()
for i in range(len(s)):
if not i%2 and s[i] == "h":
continue
elif i%2 and s[i] == "i":
continue
else:
print("No")
exit()
print('Yes') |
184bfa6475a42ba88e07e7fb3a86a5fc003f891c | Monsieurvishal/PythonProjects | /RockPaperScissorsGame/RockPaperScissorsGame.py | 2,250 | 3.859375 | 4 |
# @author Neel Patel
# @file RockPaperScissorsGame.py
from random import randint
best, out = input("Best ______ out of _______?").split()
best = int(best)
out = int(out)
moves = ["rock", "paper", "scissors"]
comp_wins, player_wins = 0, 0
def comp_win(comp_param, player_param, win_param):
print("Computer played " + moves[comp_param] + " and player played " + player_param)
print("Computer wins : " + str(win_param))
print("Player wins : " + str(player_wins))
print()
def player_win(comp_param, player_param, win_param):
print("Computer played " + moves[comp_param] + " and player played " + player_param)
print("Computer wins : " + str(comp_wins))
print("Player wins : " + str(win_param))
print()
for i in range(0, out):
if player_wins == best:
print("Player won!")
break
elif comp_wins == best:
print("Computer won")
break
comp_move = randint(0,2)
player_move = input("Please enter your play(rock, paper, scissors): ")
if player_move not in moves:
print("Invalid Entry")
player_index = moves.index(player_move)
if player_index == comp_move:
print("Both played the same move")
elif player_index == 0:
if comp_move == 1:
comp_wins += 1
comp_win(comp_move, player_move, comp_wins)
elif comp_move == 2:
player_wins += 1
player_win(comp_move, player_move, player_wins)
elif player_index == 1:
if comp_move == 0:
player_wins += 1
player_win(comp_move, player_move, player_wins)
elif comp_move == 2:
comp_wins += 1
comp_win(comp_move, player_move, comp_wins)
elif player_index == 2:
if comp_move == 0:
comp_wins += 1
comp_win(comp_move, player_move, comp_wins)
elif comp_move == 1:
player_wins += 1
player_win(comp_move, player_move, player_wins)
print()
if player_wins != best and comp_wins != best:
if player_wins > comp_wins:
print("Player won more games than computer!")
elif player_wins == comp_wins:
print("Game Tied!")
else:
print("Computer won more games than player!")
print()
|
b6c1f624880055a2674e368d13d4268a6fe9cde9 | leinian85/year2019 | /month02/code/re/day01/exercise02.py | 629 | 3.640625 | 4 | """
regex.py re模块功能函数演示
"""
import re
str = "Alex:1994,Sunny:1996"
pattern = r"(\w+):\d+"
l = re.findall(pattern, str)
print(l)
# compile
pattern = r"\w+:\d+"
regex = re.compile(pattern)
l = regex.findall(str)
print(l)
l = regex.findall(str, 10)
print(l)
# 替换目标字符串
"""
regex1.py re模块 功能演示函数
生成 match对象的函数
"""
str = "今年是2019年,见过70周年"
# 完全匹配
m = re.fullmatch(r"[,\w]+", str)
print(m.group())
#匹配开始位置
m = re.match(r"\w+?",str)
print(m.group())
#匹配第一处符合正则规则的内容
m = re.search(r"\d+",str)
print(m.group()) |
42a581b88db7e3c204d65c887e03e30c0aa64719 | YashasviBhatt/Python | /binaryToDecimal.py | 1,288 | 4.3125 | 4 | # Program to find the decimal equivalent of binary number having n digits
def BinaryToDecimal(bin_num,bin_len):
# creating a list enlisted with binary codes of decimal numbers
binary_input_list = ["{:b}".format(num) for num in range(0,2**bin_len)]
multiplier=1
dec_eqvlnt=0
flag=0
for num in binary_input_list :
if str(bin_num)==num :
flag=1
if flag==0 :
print('Invalid Binary Entered')
exit()
# calculating the decimal equivalent
else :
while bin_num>=1 :
dec_eqvlnt+=int(bin_num%10*multiplier)
bin_num=int(bin_num/10)
multiplier*=2
return dec_eqvlnt
binary_input=int(input('Enter a Binary Number : '))
bin_len=len(str(binary_input))
# calling the BinaryToDecimal function that returns a value to a variable
binary_eqvlnt=BinaryToDecimal(binary_input,bin_len)
print('The Decimal Equivalent of {} is {}'.format(binary_input,binary_eqvlnt))
# you can use bin function in python which will return bin equivalent of number
# a=int(input('Enter Binary'))
# print(bin(a)) // it will return binary equivalent with 0b at the starting if inputted number is a decimal
# print({:b}.format(a)) // it will return decimal equivalent |
dabe119a78c2945102f76109f7f96f2b05604961 | s1273274/CS-104-03 | /Richter Scale.py | 769 | 4.0625 | 4 | End=True
while End == True:
richter = float (input("Enter the Richter scale value. if you type -99 it will kill the program:"))
if richter == -99:
break
while richter < 0:
richter = float(input("Please enter a valid number: "))
if(richter >= 8.0):
print("Most structures will fall")
continue
elif (richter >= 7.0):
print("Many buildings will be destroyed")
continue
elif (richter >= 6.0):
print("Most buildings will be considerably damaged, some collapse")
continue
elif (richter >= 4.5):
print("Damage too poorly constructed buildings")
continue
elif (richter > 0):
print("No destruction of buildings")
else:
print("The value must be greater than 0 enter another value")
continue
|
3ea7e87553aa7e74944d5c6c2a6d1a28de480411 | mwisslead/Random | /Levenshtein/levenshtein.py | 389 | 3.65625 | 4 | import sys
def levenshtein(a, b, i, j):
if min(i,j) == 0:
return max(i,j)
return min(
levenshtein(a, b, i-1, j) + 1,
levenshtein(a, b, i, j-1) + 1,
levenshtein(a, b, i-1, j-1) + (0 if a[i-1] == b[j-1] else 1)
)
def main(argv):
print(levenshtein(argv[1], argv[2], len(argv[1]), len(argv[2])))
if __name__ == '__main__':
main(sys.argv)
|
d917c2ae2d8a4f62a219a03df7605081735fa50c | mihaip/adventofcode | /2019/06/part1.py | 648 | 3.671875 | 4 | #!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.txt") as f:
for line in f.readlines():
parent, child = map(get_object, line.strip().split(")"))
parent.children.append(child)
checksum = 0
def traverse(node, distance):
global checksum
checksum += distance
for child in node.children:
traverse(child, distance + 1)
traverse(root, 0)
print("checksum: %d" % checksum)
|
036328079b28c95691235104367621209a1a6f9f | cececombemale/Application_Security_Image_Crop | /image_crop.py | 1,048 | 3.609375 | 4 | from PIL import Image
import sys
import math
# get the file name
try:
name = sys.argv[1]
except:
print("You did not enter the file name of the image you would like to crop, try again by rerunning the program")
sys.exit(0)
#open the image
try:
img = Image.open(name)
except:
print("The image could not be opened, try again with another format")
sys.exit(0)
# Size of the image in pixels (size of orginal image)
width, height = img.size
#instantiate new variable for cropped image
new = img
#if the image is wider than it is long, take pixels off the left and right
#side so that the width equals the height (square) and the image is centered
if width > height:
dif = width-height
dif = dif/2
new = img.crop((dif,0, width-dif, height))
#if the image is longer than it is wide, take pixels off the top and bottom
#so that the height equals the width (square) and the image is centered
if height > width:
dif = height-width
dif = dif/2
new = img.crop((0, dif, width, height-dif))
# save new image
new.save("new"+name)
|
246c5cb9b5cc692d884586fcad9f9a1a998f0129 | pzh2587758/pzhthon3.6code | /py3.6原码/str_bytearray_memoryview之间的关系.py | 2,349 | 3.5 | 4 | """正好最近用到memoryview来回答下这个问题。
bytearray是可变(mutable)的字节序列,相对于Python2中的str,但str是不可变(immutable)的。
在Python3中由于str默认是unicode编码,所以只有通过bytearray才能按字节访问。
memoryview为支持buffer protocol[1,2]的对象提供了按字节的内存访问接口,好处是不会有内存拷贝。
默认str和bytearray支持buffer procotol。
下面两种行为的对比:
简单点就是,str和bytearray的切片操作会产生新的切片str和bytearry并拷贝数据,使用memoryview之后不会。"""
#不使用memoryview
>> a = 'aaaaaa'
>> b = a[:2] # 会产生新的字符串
>> a = bytearray('aaaaaa')
>> b = a[:2] # 会产生新的bytearray
>> b[:2] = 'bb' # 对b的改动不影响a
>> a
bytearray(b'aaaaaa')
>> b
bytearray(b'bb')
#使用memoryview
>> a = 'aaaaaa'
>> ma = memoryview(a)
>> ma.readonly # 只读的memoryview
True
>> mb = ma[:2] # 不会产生新的字符串
>> a = bytearray('aaaaaa')
>> ma = memoryview(a)
>> ma.readonly # 可写的memoryview
False
>> mb = ma[:2] # 不会会产生新的bytearray
>> mb[:2] = 'bb' # 对mb的改动就是对ma的改动
>> mb.tobytes()
'bb'
>> ma.tobytes()
'bbaaaa'
#我的使用场景是网络程序中socket接收和接收数据的解析:
#使用memoryview之前的sock接收代码简化如下
def read(size):
ret = ''
remain = size
while True:
data = sock.recv(remain)
ret += data # 这里不断会有新的str对象产生
if len(data) == remain:
break
remain -= len(data)
return ret
#使用meoryview之后,避免了不断的字符串拼接和新对象的产生
def read(size):
ret = memoryview(bytearray(size))
remain = size
while True:
data = sock.recv(remain)
length = len(data)
ret[size - remain: size - remain + length] = data
if len(data) == remain:
break
remain -= len(data)
return ret
#返回memoryview还有一个优点,在使用struct进行unpack解析时可以直接接收memoryview对象,非常高效(避免大的str进行分段解析时大量的切片操作)。
#例如:
mv = memoryview('\x00\x01\x02\x00\x00\xff...')
type, len = struct.unpack('!BI', mv[:5])
... |
5fe8c282104a1b2c413e13537131237b5beeafd9 | vanihb/assign1 | /Assignment two/lcm.py | 329 | 4.125 | 4 | def cal_lcm(a,b):
if a>b:
large=a
else:
large=b
while(True):
if((large%a == 0) and (large%b == 0)):
lcm=large
break
large += 1
return lcm
n1=int(input("enter num1:"))
n2=int(input("enter num2:"))
print("lcm of two numbers is:",cal_lcm(n1,n2))
|
e3acec9febad760df63d26effd6492ed2b4c63cd | ullumullu/adventofcode2020 | /challenges/day5.py | 1,814 | 4 | 4 | """ --- Day 5: Binary Boarding ---
Part1:
As a sanity check, look through your list of boarding passes.
What is the highest seat ID on a boarding pass?
Part 2:
What is the ID of your seat?
"""
from typing import Tuple, Iterator
def binary_range_search(search_cmds: Iterator[str],
search_range: Tuple[int, int]) -> Tuple[int, int]:
"""
In this case partition contains the indication which part of the range to keep.
L --> keep left half of the range
R --> keep right half of the range
"""
for search_cmd in search_cmds:
diff = int((search_range[1] - search_range[0]) / 2)
if search_cmd == "L":
search_range = (search_range[0], search_range[0]+diff)
elif search_cmd == "R":
search_range = (search_range[1]-diff, search_range[1])
return search_range
def find_seat(bord_pass: str, total_rows: int = 128, total_cols: int = 8) -> Tuple[int, int, int]:
"""Parses the airlines binary space partitioning to return the row and column.
The first 7 characters will either be F or B; these specify exactly one of the
128 rows on the plane (numbered 0 through 127). Each letter tells you which half
of a region the given seat is in.
The last three characters will be either L or R; these specify exactly one of
the 8 columns of seats on the plane (numbered 0 through 7).
"""
# Row
row_range = (0, total_rows-1)
row_search = map(lambda cmd: "L" if cmd ==
"F" else "R", list(bord_pass[:7]))
row = binary_range_search(row_search, row_range)
# Col
col_range = (0, total_cols-1)
col_search = list(bord_pass[7:])
col = binary_range_search(col_search, col_range)
# Id
seat_id = row[0] * 8 + col[0]
return (row[0], col[0], seat_id)
|
ed58a590566ec4fc800221be1eb7bd41a34cecc3 | christian-miljkovic/python_projects | /python_project 2/MiljkovicChristian_assign2_part1.py | 894 | 4.28125 | 4 | # Christian Miljkovic
# CSCI-UA.0002 section 03
# Assignment #2
#print out the intorduction
print("Hello! I'm here to help you calculate your tip.")
#have user input the cost of the bill
bill=float(input("How much was your bill? (enter a positive integer without $): "))
#ask the user how much tip they want to leave
user_tip = (float(input("How much tip would you like to leave? (enter a positive integer without $): ")))/100
#print thanks
print("Thanks!")
#calculate the tip based on the user input
suggested_tip=bill*user_tip
form_suggested_tip= format(suggested_tip,".2f")
print("You need to leave", end=" ")
print("$", form_suggested_tip, sep="", end=" ")
print("as a tip.")
#calculate the total bill with the actual tip
total_bill=bill+suggested_tip
form_total_bill= format(total_bill,".2f")
print("Your total bill will be", end=" ")
print("$",form_total_bill,sep="")
|
7e89e3eef42cd1d2350906adc19382d3dccb1099 | charu11/pythonPro | /expo.py | 195 | 3.953125 | 4 | # exponent function
def raise_to_power(base_num, power_num):
result = 1
for index in range(power_num):
result = result * base_num
return (result)
print(raise_to_power(4, 3)) |
01a46ffa2b4575f1c067e75b4993b48dca979b45 | mynameischokan/python | /Numbers, Dates, and Times/1_14.py | 1,522 | 4.59375 | 5 | """
************************************
**** 3.14. Finding the Date Range for the Current Month
************************************
#########
# Problem
#########
# You have some code that needs to loop over each date in the current month,
# and want an efficient way to calculate that date range.
#########
# Solution
#########
# Looping over the dates doesn’t require building a list of all the dates ahead of time.
# You can just calculate the starting and stopping date in the range,
# then use `datetime.timedelta` objects to increment the date as you go.
"""
import calendar
from datetime import datetime, date, timedelta
def get_month_range(start_date=None):
if start_date is None:
# Code goes here
# Initialize start_date with first day of current month
pass
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
# Code goes here
# Define end_date use timedelta
return start_date, end_date
def print_days_of_month():
# Code goes here
# Initialize `a_day` with day=1
a_day = None
first_day, last_day = get_month_range()
while first_day < last_day:
print(first_day)
first_day += a_day
def date_range(start, stop, step):
# Code goes here
# Create a while loop that will will yield start while start < stop with step=step
pass
for d in date_range(datetime(2012, 9, 1), datetime(2012,10,1), timedelta(hours=6)):
print(d)
if __name__ == '__main__':
print_days_of_month()
pass
|
a7bc54d4283d597ce799cfe2c73f7ebb03815238 | andrewgordon17/Bois | /bois_plot.py | 2,459 | 3.546875 | 4 | from matplotlib import pyplot as plt
from matplotlib import animation
from bois_classes import Swarm
from movement_functions import *
#This code creates a swarm and graphs its progress in matplotlib
#Variables that affect the swarm
NUMBER_OF_BOIS = 500
BOI_SIZE = .005
RADIUS = .2 #Radius a Boi can see
SHOW_RADIUS = False #when True shows the radius as a circle around each Boi
#Variables that affect the display
NUM_STEPS = 2000 #required for the animation function. SHould be larger than NUMBER_OF_BOIS
NUM_PER_ANIMATE =500 #The number of Bois that update position each frame
INTERVAL = 2000 #the time between frames, in ms
#The parameters for the window where the bois appear at the start
X_LIM = (-1,2)
Y_LIM = (-1,2)
#the parameters for the window that is plotted
X_AX_LIM = (-4,5)
Y_AX_LIM = (-4,5)
fig = plt.figure()
ax = plt.axes(xlim=X_AX_LIM, ylim=Y_AX_LIM)
patches = []
for i in range(NUMBER_OF_BOIS):
if SHOW_RADIUS:
outer = plt.Circle((X_LIM[0], Y_LIM[0]), RADIUS, fill=False)
patches.append((plt.Circle((X_LIM[0], Y_LIM[0]), BOI_SIZE),outer))
else:
patches.append(plt.Circle((X_LIM[0], Y_LIM[0]), BOI_SIZE))
swm = Swarm(num=NUMBER_OF_BOIS, mf=line_find_best_fit, xwin = X_LIM, ywin = Y_LIM, radius = RADIUS, edge_behavior = ['WARN'])
def init():
if SHOW_RADIUS:
for i in range(NUMBER_OF_BOIS):
patches[i][0].center = (swm.bois[i].xpos, swm.bois[i].ypos)
patches[i][0].center = (swm.bois[i].xpos, swm.bois[i].ypos)
ax.add_patch(patches[i][0])
ax.add_patch(patches[i][1])
return tuple(patches)
else:
for i in range(NUMBER_OF_BOIS):
patches[i].center = (swm.bois[i].xpos, swm.bois[i].ypos)
ax.add_patch(patches[i])
return tuple(patches)
def animate(i):
i = (NUM_PER_ANIMATE*i)%NUMBER_OF_BOIS
edited = []
for j in range(NUM_PER_ANIMATE):
idx = (i+j)%NUMBER_OF_BOIS
swm.turn(swm.bois[idx])
if SHOW_RADIUS:
patches[idx][0].center = (swm.bois[idx].xpos, swm.bois[idx].ypos)
edited.append(patches[idx][0])
patches[idx][1].center = (swm.bois[idx].xpos, swm.bois[idx].ypos)
edited.append(patches[idx][1])
else:
patches[idx].center = (swm.bois[idx].xpos, swm.bois[idx].ypos)
edited.append(patches[idx])
return tuple(edited)
anim = animation.FuncAnimation(fig, animate,
init_func=init,
frames=NUM_STEPS,
interval=INTERVAL,
blit=False)
plt.show()
|
b1c9015b9eebbc84fe97f18b5ea2ac6078315f1b | divyank0/euler_project | /50.py | 670 | 3.53125 | 4 | from math import sqrt as sqrt;
from math import floor as floor;
import sys;
def is_prime(aa):
return all(aa%ii for ii in range(2,floor(sqrt(aa))+1));
s=0;
p=[];
for i in range(2,1000000):
if is_prime(i)==True:
p.append(i);
print("ffff");
c=0;
s=0;
cc=0;
count=0;
for j in p:
cc=0;
s=j;
c=c+1;
for jj in p[c:]:
cc=cc+1;
s=s+jj;
if s>1000000:
break;
if is_prime(s) :
if cc>count:
count=cc
print(cc,s);
|
d2f729fdf61294277c45136d2f5a7b4807258cce | cintax/dap_2019 | /inverse_series.py | 328 | 3.921875 | 4 | #!/usr/bin/env python3
import pandas as pd
def inverse_series(s):
ind = list(s.index)
val = s.values
#print(ind, val)
return pd.Series(list(s.index),s.values)
def main():
s1 = pd.Series([1,2,3,4,5], index = list("abcde"))
print(s1)
print(inverse_series(s1))
if __name__ == "__main__":
main()
|
957d280dc9a510caa08e1977e3da78d8243ccb82 | NohYeaJin/programmers_problem | /programmers_english_play.py | 946 | 3.5625 | 4 | def solution(n, words):
num = len(words)
answer = []
for i in range(1,num,1):
if(words[i][0]!=words[i-1][len(words[i-1])-1]):
i = i + 1
num1 = i % n
if(num1==0):
num1 = n
num2 = int(i / n)
else:
num2 = i/n+1
num2 = int(num2)
answer = [num1,num2]
return answer
else:
for j in range(i):
if(words[i]==words[j]):
i = i + 1
num1 = i % n
if(num1==0):
num1 = n
num2 = int(i / n)
else:
num2 = i/n+1
num2 = int(num2)
answer = [num1,num2]
return answer
return [0,0]
print(solution(2,["hello", "one", "even", "never", "now", "world", "draw"])) |
4eb0d27d92af4012dcd5e181cc6f20bc6d187020 | ashish-bisht/must_do_geeks_for_geeks | /dp/python/laregest_inc_subseq/recursive.py | 567 | 3.765625 | 4 | def largest_increasing_subseq(nums):
return helper(nums, 0, float("-inf"))
def helper(nums, index, last_num):
if index >= len(nums):
return 0
with_cur_num = 0
if nums[index] > last_num:
with_cur_num = 1 + helper(nums, index+1, nums[index])
without_cur_num = helper(nums, index+1, last_num)
return max(with_cur_num, without_cur_num)
print(largest_increasing_subseq([4, 2, 3, 6, 10, 1, 12]))
print(largest_increasing_subseq([-4, 10, 3, 7, 15]))
print(largest_increasing_subseq([-4]))
print(largest_increasing_subseq([]))
|
dad98be673e722ea9104571f965c8e0cece07277 | BushBaBy1989/Sickle-Cell-Disease | /SickleCellDisease.py | 2,992 | 3.78125 | 4 | #Files we needs to read and write
DNAReadFile = open('DNA.txt', 'r')
#These 2 files first used for writing
DNANormalFile = open('normalDNA.txt', 'w')
DNAMutateFile = open('mutatedDNA.txt', 'w')
#Function that translates DNA sequence to Amino Acid Sequence
def translate(DNAinput):
#Needed Variables
AAseq = ""
#Run through the DNA sequence 3 letters at a time and see which amino acid sequences it matches
for i in range(0, len(DNAinput), 3):
if DNAinput[i:i+3] == "ATT" or DNAinput[i:i+3] == "ATC" or DNAinput[i:i+3] == "ATA":
AAseq += "I"
elif DNAinput[i:i+3] == "CTT" or DNAinput[i:i+3] == "CTC" or DNAinput[i:i+3] == "CTA" or DNAinput[i:i+3] == "CTG" or DNAinput[i:i+3] == "TTA" or DNAinput[i:i+3] == "TTG":
AAseq += "L"
elif DNAinput[i:i+3] == "GTT" or DNAinput[i:i+3] == "GTC" or DNAinput[i:i+3] == "GTA" or DNAinput[i:i+3] == "GTG":
AAseq += "V"
elif DNAinput[i:i+3] == "TTT" or DNAinput[i:i+3] == "TTC":
AAseq += "F"
elif DNAinput[i:i+3] == "ATG":
AAseq += "M"
else:
AAseq += "X"
return AAseq
#Function that reads in DNA from a File, corrects the file and also creates a mutated DNA file
def mutate():
#Read in the file
DNAStr = DNAReadFile.read()
#Fix the DNA sequence
DNAStrNormal = DNAStr.replace("a", "A")
#Create the mutated DNA sequence
DNAStrMutate = DNAStr.replace("a", "T")
#Write to the text file and close it so that is saves for reading later
DNANormalFile.write(DNAStrNormal)
DNAMutateFile.write(DNAStrMutate)
DNANormalFile.close()
DNAMutateFile.close()
#Function that reads in txt files of DNA sequences and outputs Amino Acid sequences to the user
def txtTranslate():
#Needed variables
translateStrN = ""
translateStrM = ""
#Now these 2 files are needed for reading
DNANormalFile = open('normalDNA.txt', 'r')
DNAMutateFile = open('mutatedDNA.txt', 'r')
#Read in normal DNA file
DNAStrNormal = DNANormalFile.read()
#Get the input ready for tranlating
for i in range(0, len(DNAStrNormal)):
if DNAStrNormal[i] != "\n":
translateStrN += DNAStrNormal[i]
#Print out the Amino Acid Sequence
print("Amino Acid sequence of normal DNA: " + "\n")
print(translate(translateStrN))
#Read in mutated DNA file
DNAStrMutate = DNAMutateFile.read()
#Get the input ready for tranlating
for i in range(0, len(DNAStrMutate)):
if DNAStrMutate[i] != "\n":
translateStrM += DNAStrMutate[i]
#Print out the Amino Acid Sequence
print("\n" + "Amino Acid sequence of mutated DNA: " + "\n")
print(translate(translateStrM))
return
#Calls the functions
mutate()
txtTranslate()
#Close the files
DNAReadFile.close()
DNANormalFile.close()
DNAMutateFile.close()
|
6da7b5027f14c0966cca70fda2561e7d6628a106 | sarkarChanchal105/Coding | /Leetcode/python/Medium/replace-words.py | 1,439 | 4.15625 | 4 | """
https://leetcode.com/problems/replace-words
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence after the replacement.
Example 1:
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 2:
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Example 3:
Input: dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
Output: "a a a a a a a a bbb baba a"
Example 4:
Input: dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Example 5:
Input: dictionary = ["ac","ab"], sentence = "it is abnormal that this solution is accepted"
Output: "it is ab that this solution is ac"
"""
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
pass |
ae0b9e5553f9dcc57079fc1bd3ffb2b1c931fa97 | mannawar/MIT-lecture-series-Practise | /MIT-Lec10.py | 466 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 10:34:30 2019
@author: Mannawar Hussain
"""
#linear search on unsorted list
def linear_search (L,e):
found = False
for i in range (len(L)):
if e == L[i]:
found = True
return found
#linear search on sorted list
def search (L, e):
for i in range(len(L)):
if L[i] == e:
return True
if L[i] > e:
return False
return False |
c30eb44e7920fff2ba1884cde731e434853f8987 | WolfPack3/Saman_Documents | /Handover/Binck/SpaceRemoval.py | 1,707 | 3.578125 | 4 |
import argparse
import csv
import os
parser = argparse.ArgumentParser()
parser.add_argument('-in-csv', help='pathname of input csv file')
parser.add_argument('-out-csv', help='pathname of output csv file')
args = parser.parse_args()
# get the index of the first and last none space character
def get_firstlast_index(a_string):
first_last = []
# get index of first character
for index, letter in enumerate(a_string):
if letter != ' ':
first_last.append(index)
break
# get index of last character
for index, letter in reversed(list(enumerate(a_string))):
if letter != ' ':
first_last.append(index+1)
break
return first_last
# remove spaces from start and end of text
def strip_value(string):
indexs = get_firstlast_index(string)
if len(indexs) == 2:
first_index = indexs[0]
last_index = indexs[1]
substring = string[first_index:last_index]
return substring
else:
return string.strip()
# remove value if not O or F
def keep_O_F(ordersoort):
if ordersoort != 'O' and ordersoort != 'F':
return True
else:
return False
# in file
in_csv_file = open(args.in_csv, 'r')
reader_obj = csv.reader(in_csv_file, delimiter=';')
# out file
out_csv_file = open(args.in_csv, 'w', newline='')
writer_obj = csv.writer(out_csv_file, delimiter=';')
for counter, row in enumerate(reader_obj):
if keep_O_F(row[14]):
continue
for index, entry in enumerate(row):
row[index] = strip_value(entry)
writer_obj.writerow(row)
out_csv_file.close()
in_csv_file.close()
|
10a3ee806354f40087ab72f0e57c9689e4d663e2 | istd50043-2020-fall/sutd50043_student | /lab11/ex2/ex2.py | 423 | 3.578125 | 4 | from mapreduce import *
def read_db(filename):
db = []
with open(filename, 'r') as f:
for l in f:
db.append(l)
f.close()
return db
test_db = read_db("./data/price.csv")
# TODO: FIXME
# the result should contain a list of suppliers,
# with the average sale price for all items by this supplier.
result = []
for supplier,avg_price in result:
print(supplier, avg_price) |
0fa23cc3d8b8c532ec75fc1e90fae284d44e6808 | jpgsaraceni/python | /intermediario.py | 7,099 | 3.640625 | 4 | """
DICIONÁRIOS <dic> = {<chave>: <valor>, <...>} // cria dicionário
<dic> = dict(<chave>: <valor>)
ACRESCENTAR CHAVE <dic>[<nova chave>] = <valor>
ACESSAR CHAVE <dic>[<chave>]
DELETAR CHAVE del <dic>[<chave>]
CHECAR CHAVE if <chave> in <dic>
ACESSAR VALORES <dic>.values()
ACESSAR PARES <dic.items()
.POP <dic>.pop(['<chave>]')
.POPITEM <dic>.popitem() // corta ultimo item
.UPDATE <dic>.update(<dic2>) // concatenar
COMPREHENSION <dic> = {<chave><comando>: <valor><comando> for <chave>, <valor> in <iterável>}
// iterável deve ter dois valores em cada elemento
***********************************************************************************************************************
FUNÇÕES def <fun>(<arg>=<valor padrão>): // abre a função. args e valor opcionais
// quando chamar a função, pode colocar nos parênteses os valores com ou sem <var> = antes.
// sem os parênteses não executa
RETURN return <valor> // termina a função. default = None
*ARGS def <fun>(*args): // quando não souber quantos args virão
// args é por convenção. empacota os argumentos como tupla
**KWARGS def <fun>(*args, **kwargs): // argumentos nomeados (<chave> = <valor>)
LAMBDA <var> = (lambda <arg>: <retorno>) // cria uma função na declaração
.GET <var> = kwargs.get('<chave>') // retorna valor recebido para a chave
***********************************************************************************************************************
LIST COMPREHENSION
// coloca uma regra na declaração da lista usando for in, referenciando outro iterável
<lista> = [<var><op> for <var> in <iter>]
***********************************************************************************************************************
SET <set> = {<valores>} // sem repetição e sem índice
.ADD <set>.add(<valor>) // acrescenta valor
.DISCARD <set>.discard(<valor>)
.UPDATE <set>.update(<valor>) // adiciona da iterado do valor
OPERADORES DE CONJ. <set>.union(<set2>) ou <set> | <set2> // união
<set> & <set2> // interseção
<set> - <set2> // diferença
<set> ^ <set2> // AUB - A int B
COMPREHENSION <set> = {<var> for <var> in <iter>}
***********************************************************************************************************************
ITERÁVEIS str, list, set, iter, etc
ITERADORES retornam um valor de cada vez (pode ser de lista, tupla, etc)
GERADORES <var> = (<valor> for <valor> in <iterável>) // só salvam um valor na memória
NEXT next(<iterável) // retorna o próximo valor
// os valores utilizados em iteradores e geradores são consumidos.
***********************************************************************************************************************
MÓDULOS from <arquivo> import <dados> // para um dado
ctrl + espaço (depois do import) mostra tudo que há no módulo
import <mod> // para o modulo todo
from <mod> import * // importa tudo, não precisa escrever <mod>.
<dado> para acessar.
<mod>. mostra tudo do módulo também
<mod>.<dado> precisa dessa sintaxe para executar comando, não pode diretamente se importar tudo
from <mod> import <dado> as <nome> // muda o nome nesse código
from itertools import
COUNT
from functools import
REDUCE reduce(<func>, <iterável>, <val inicial>) // acumulador
INSTALAR MOD pip install <mod> // no terminal
__name__ __name__ // retorna o nome do arquivo com relação ao
que está sendo executado (__main__)
***********************************************************************************************************************
RANDOM (MOD)
randint random.randint(<de>,<a>) // retorna um inteiro aleatório
random random() // número entre 0 e 1
***********************************************************************************************************************
FILTER filter(<func>: <iterável>) // retorna os elementos true
MAP map(<func>: <iterável>)
// aplica função a cada elemento
***********************************************************************************************************************
TRATAR EXCEÇÕES
try:
<comandos>
except:
<comandos>
EXCEPTION except Exception as <var>: // se ocorrer qualquer erro, <var> recebe
o erro.
CLASSE DE ERRO except <classe erro> as <var>: // manda para a <var> caso aquele erro ocorra
ELSE // executado se não ocorrer erro
FINALLY finally:
<comando> // sempre executa
RAISE // relança exceção tratada
raise <exceção>("<mensagem">) // se ocorrer o erro, aparece o erro c mens
***********************************************************************************************************************
PACOTES // Diretório contendo arquivo __init__.py
acessar mod <pac>.<mod>.<dado>
from <pac>.<mod> import <dado>
***********************************************************************************************************************
ARQUIVOS
"""
# revisar itertools
|
a474e19f5f4451e5bc647ba25d29e1663c271f72 | yohn-dezmon/unzipping-combining-json | /moreBasic.py | 768 | 3.890625 | 4 | import json
# here I'm trying to understand how to access the respective json objects from each JSON file within
# the array
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])
file1 = "/Users/HomeFolder/Desktop/CongressBills/bills 2/hjres/hjres4/data.json"
file2 = "/Users/HomeFolder/projects/jsonExtractCombine/merged_file2.json"
file3 = "/Users/HomeFolder/projects/jsonExtractCombine/merged_file_similar.json"
# Can I use this without open function?
with open(file3, "rb") as popsicle:
y = json.load(popsicle)
# let's assum that y is now a LIST of json objects
print(y[0]["subjects_top_term"])
# print(y[1][0]["subjects_top_term"])
# print(y[0])
print("*"*10)
# print(y)
print("*"*10)
print(y[1]["subjects_top_term"])
|
6a159a65ea848c61eb4b35980b2bd524a5487b56 | BzhangURU/LeetCode-Python-Solutions | /T522_Longest_Uncommon_Subsequence_II.py | 2,209 | 4.125 | 4 | ##Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
##
##A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
##
##The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
##
##Example 1:
##Input: "aba", "cdc", "eae"
##Output: 3
##Note:
##
##All the given strings' lengths will not exceed 10.
##The length of the given list will be in the range of [2, 50].
##My comments: if subsequence of string a is LUS, then a must be LUS. So we
## sort strings, and find the longest LUS. ##def findLUSlength(strs: List[str]) -> int:
import functools
class Solution:
def cmpStr(self, a, b):
if len(a)!=len(b):
return len(b)-len(a)
else:
for i in range(len(a)):
if a[i]!=b[i]:
return ord(a[i])-ord(b[i])
return 0
def isSubsequence(self, a, b):
if len(a)>len(b):
return False
else:
j=0
for i in range(len(a)):
while a[i]!=b[j]:
j=j+1
if j>=len(b) or len(a)-i>len(b)-j:
return False
j=j+1
return True
#Check if string a is subsequence of b
def findLUSlength(self, strs: List[str]) -> int:
strs2=sorted(strs, key=functools.cmp_to_key(self.cmpStr))
for i in range(len(strs2)):
isLUS=True
if i<len(strs2)-1:
if strs2[i]==strs2[i+1]:
continue
for j in range(i):
if self.isSubsequence(strs2[i], strs2[j]):
isLUS=False
break
if isLUS:
return len(strs2[i])
return -1
|
4feaf30132801c5f195e35a3cf5758d9670b5901 | willineed/nu | /Lab 4 Camel.py | 3,101 | 4.125 | 4 | import random
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down! Survive your")
print("desert trek and outrun the natives.")
traveled = 0
miles_traveled = 0
thirst = 0
camel_tiredness = 0
natives_traveled = -20
drinks_canteen = 4
done = False
while not done:
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full sped.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
user_choice = input("Your choice? ")
if user_choice.upper() == "Q":
done = True
elif user_choice.upper() == "E":
print("Miles traveled:", miles_traveled)
print("Drinks in canteen:", drinks_canteen)
print("The natives are", miles_traveled - natives_traveled,"miles behind you.")
print("")
elif user_choice.upper() == "D":
camel_tiredness = 0
print("The camel is happy")
print("")
natives_traveled += random.randrange(7, 15)
elif user_choice.upper() == "C":
traveled = random.randrange(10, 21)
print("You just traveled", traveled, "miles.")
print("")
miles_traveled += traveled
thirst += 1
camel_tiredness += random.randrange(1, 4)
natives_traveled += random.randrange(7, 15)
elif user_choice.upper() == "B":
traveled = random.randrange(5, 13)
print("You just traveled", traveled, "miles.")
print("")
miles_traveled += traveled
thirst += 1
camel_tiredness += 1
natives_traveled += random.randrange(7, 15)
elif user_choice.upper() == "A":
if drinks_canteen > 0:
thirst = 0
drinks_canteen -= 1
print("You have satiated your thirst")
print("")
else:
print("You do not have any drinks left.")
if random.randrange(1, 21) == 1:
print("You have found an oasis!")
print("Your canteen has been refilled.")
print("Your thirst has been satiated.")
print("Your camel is now rested.")
drinks_canteen = 4
thirst = 0
camel_tiredness = 0
print("")
if thirst > 6:
print("You died of thirst!")
done = True
elif thirst > 4:
print("You are thirsty!")
print("")
if camel_tiredness > 8:
print("Your camel is dead.")
done = True
elif camel_tiredness > 5:
print("Your camel is getting tired.")
print("")
if natives_traveled >= miles_traveled:
print("The natives have caught you!")
done = True
elif (miles_traveled - natives_traveled)< 15:
print("The natives are getting close!")
print("")
if miles_traveled >= 200:
print("You have made it across the desert!")
print("You have succesfully outrun the natives!")
done = True
|
7361412af609d8c287a2259684afd6dbf1dc6e5c | aparece1241/PythonProjects | /myPythonProject/arcade/newGame/newGame(rewrite).py | 23,570 | 3.59375 | 4 | from tkinter import *
import arcade
import random
import json
import os
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 600
SCREEN_TITLE = "NEW GAME"
FIRTTIME_RUN = True
gamedata = [{"name" : "", "score" : 0 ,"waves" : 0 },
{"name" : "", "score" : 0 ,"waves" : 0 },
{"name" : "", "score" : 0 ,"waves" : 0 },
{"name" : "", "score" : 0 ,"waves" : 0 },
{"name" : "", "score" : 0 ,"waves" : 0 }
]
NAME = ""
DATAS = ""
def readFile():
with open("gameData.txt", "r") as read:
data = json.load(read)
return data
def writeFile(data= gamedata):
with open("gameData.txt", "w") as create:
json.dump(data, create)
def CheckFileExist():
if os.path.exists("gameData.txt"):
global DATAS
DATAS = readFile()
else:
writeFile()
CheckFileExist()
def getValue(Pop_up,UserInput):
global NAME
NAME = UserInput.get()
Pop_up.destroy()
def get_input():
Pop_up = Tk()
Pop_up.title("Input")
Pop_up.resizable = False
L1 = Label(Pop_up, text="Enter your name")
L1.place(x=55, y=80)
L2 = Label(Pop_up, text="To Start The Game please")
L2.place(x=36, y=20)
E1 = Entry(Pop_up, fg="green")
E1.place(x=40, y=100)
B1 = Button(Pop_up, text="submit", command=lambda: getValue(Pop_up,E1))
B1.place(x=70, y=120)
Pop_up.mainloop()
get_input()
class Record():
def getHighScore(self,score,wave):
for data in DATAS:
print(data["score"])
if data["score"] < score:
data["name"] = NAME
data["score"] = score
data["waves"] = wave
print("data :",DATAS)
writeFile(DATAS)
readFile()
break
class Buttons():
def __init__(self,center_x,center_y,width,height,
color,text,function,text_color,tilt_angle = 0):
self.center_x = center_x
self.center_y = center_y
self.width = width
self.height = height
self.color = color
self.defualt = color
self.shadow_color1 = arcade.color.DARK_GRAY
self.shadow_color2 =arcade.color.WHITE
self.text = text
self.text_color = text_color
self.function = function
def draw_button(self):
textLenght = len(self.text)
deducX = 25
if textLenght == 5:
deducX = 25
elif textLenght > 5:
times = textLenght - 5
while times > 0:
deducX += 5
times -= 1
else:
times = 5 - textLenght
while times > 0:
deducX -= 5
times -= 1
arcade.draw_rectangle_filled(self.center_x,self.center_y,self.width,self.height,self.color)
arcade.draw_text_2(self.text,(self.center_x - deducX),(self.center_y - self.height * 0.15),self.text_color,font_size = 15)
#Top
arcade.draw_line(self.center_x - self.width/2,self.center_y + self.height/2,
self.center_x + self.width/2,self.center_y + self.height/2,
self.shadow_color1,2)
#Left
arcade.draw_line(self.center_x - self.width/2,self.center_y + self.height/2,
self.center_x - self.width/2,self.center_y - self.height/2,
self.shadow_color1,2)
#Right
arcade.draw_line(self.center_x + self.width/2,self.center_y + self.height/2,
self.center_x + self.width/2,self.center_y - self.height/2,
self.shadow_color1,2)
#buttom
arcade.draw_line(self.center_x - self.width/2,self.center_y - self.height/2,
self.center_x + self.width/2,self.center_y - self.height/2,
self.shadow_color1,2)
def draw_circle_button(self):
pass
def on_press(self):
self.shadow_color2 = arcade.color.DARK_GRAY
self.shadow_color1 = arcade.color.WHITE
self.color = (188, 190, 194)
def on_release(self):
self.shadow_color1 = arcade.color.DARK_GRAY
self.shadow_color2 = arcade.color.WHITE
self.color = self.defualt
def check_mouse_press(self,x,y):
if x > self.center_x - self.width/2 and x < self.center_x + self.width/2 :
if y > self.center_y - self.height/2 and y < self.center_y + self.height/2 :
self.on_press()
def check_mouse_release(self,x,y):
if x > self.center_x - self.width/2 and x < self.center_x + self.width/2 :
if y > self.center_y - self.height/2 and y < self.center_y + self.height/2 :
self.on_release()
if self.function != None:
self.function()
def Start():
Window.show_view(StartGame())
def Main():
Window.show_view(MainMenu())
def Instruct():
Window.show_view(Introduction())
def Exit():
exit()
class GameOver(arcade.View):
Back = Buttons(400, 150, 120, 50, arcade.color.GRAY, "Back", Main, arcade.color.BLACK)
Replay = Buttons(SCREEN_WIDTH - 400, 150, 120, 50, arcade.color.GRAY, "Replay", Start, arcade.color.BLACK)
Button_list = []
def on_show(self):
arcade.set_background_color(arcade.color.AVOCADO)
self.Button_list.append(self.Back)
self.Button_list.append(self.Replay)
def on_draw(self):
arcade.start_render()
arcade.draw_text_2("Game Over!", 320, SCREEN_HEIGHT/2, arcade.color.BLACK, 40, bold=True)
self.Back.draw_button()
self.Replay.draw_button()
def on_mouse_press(self, x: float, y: float, button: int, modifiers: int):
for button in self.Button_list:
button.check_mouse_press(x,y)
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int):
for button in self.Button_list:
button.check_mouse_release(x,y)
class Introduction(arcade.View):
back = Buttons(100, 80, 100, 50, arcade.color.GRAY, "Back", Main, arcade.color.WHITE)
play = Buttons(SCREEN_WIDTH - 100, 80, 100, 50, arcade.color.GRAY, "Play", Start, arcade.color.WHITE)
arrowButtonList = []
def messageDisplay(self):
arcade.draw_rectangle_filled(SCREEN_WIDTH/2,SCREEN_HEIGHT/2,500,420,(110,100,20,50))
arcade.draw_text_2("Controls :", 300, 470, arcade.color.WHITE, 20)
arcade.draw_text_2("To move your hero use the", 300, 420, arcade.color.WHITE, 20)
arcade.draw_text_2("arrow keys. ", 300, 370, arcade.color.WHITE, 20)
arcade.draw_text_2("To attack use the 'A' key to attack", 300, 320, arcade.color.WHITE, 20)
arcade.draw_text_2("Goal :", 300, 270, arcade.color.WHITE, 20)
arcade.draw_text_2( "Dont be killed !!!", 300, 220, arcade.color.WHITE, 20)
def on_show (self):
arcade.set_background_color(arcade.color.AVOCADO)
self.arrowButtonList.append(self.play)
self.arrowButtonList.append(self.back)
def on_draw (self):
arcade.start_render()
self.play.draw_button()
self.back.draw_button()
arcade.draw_text_2("User Guide", 425, 550, arcade.color.BLACK, 20, bold=True)
self.messageDisplay()
def on_mouse_press(self, x: float, y: float, button: int, modifiers: int):
for button in self.arrowButtonList:
button.check_mouse_press(x,y)
def on_mouse_release(self, x: float, y: float, button: int,
modifiers: int):
for button in self.arrowButtonList:
button.check_mouse_release(x,y)
class MainMenu(arcade.View):
Play = Buttons(305,260,150,50,
arcade.color.AVOCADO,"Play",
Instruct,arcade.color.GREEN)
Exits = Buttons(390,200,150,50,
arcade.color.AVOCADO,"Exit"
,Exit,arcade.color.GREEN)
Heroes = Buttons(485,260,150,50,
arcade.color.AVOCADO,"Heroes",
None,arcade.color.GREEN)
backdrop1 = arcade.Sprite("../../SpriteLists/zombie.png"
,center_x = 400,center_y = 400,scale = 0.8)
hero = arcade.Sprite("../../SpriteLists/hero.page.png"
,center_x = 680,center_y = 200)
zombie = arcade.Sprite("../../SpriteLists/zombie.page.png"
,center_x = 150,center_y = 150)
background = arcade.SpriteList()
button_list = []
back = arcade.load_texture("../image/head.png")
def on_show(self):
arcade.set_background_color(arcade.color.BISTRE_BROWN)
self.button_list.append(self.Play)
self.button_list.append(self.Exits)
self.button_list.append(self.Heroes)
self.background.append(self.hero)
self.background.append(self.backdrop1)
self.background.append(self.zombie)
def on_draw(self):
arcade.start_render()
arcade.draw_lrwh_rectangle_textured(0, 0,
SCREEN_WIDTH, SCREEN_HEIGHT,
self.back)
self.Play.draw_button()
self.Exits.draw_button()
self.Heroes.draw_button()
self.background.draw()
def on_mouse_press(self,x,y,button,modifiers):
for i in self.button_list:
i.check_mouse_press(x,y)
def on_mouse_release(self,x,y,button,modifiers):
for i in self.button_list:
i.check_mouse_release(x,y)
class hero():
def __init__(self,life,name):
self.lifePoints = life
self.name = name
self.direction = None
self.movementSpeed = 5
self.bullet_damage = 20
self.hero = arcade.AnimatedWalkingSprite()
self.hero_list = arcade.SpriteList()
self.hero.stand_right_textures = []
self.hero.stand_left_textures = []
self.hero.walk_right_textures = []
self.hero.walk_left_textures = []
self.hero.stand_right_textures.append(arcade.load_texture("../../SpriteLists/hero.walk.0.png"))
self.hero.stand_left_textures.append(arcade.load_texture("../../SpriteLists/hero.walk.0.png",mirrored = True))
self.bullet_direction = "RIGHT"
for i in range(0,5):
self.hero.walk_right_textures.append(arcade.load_texture(f"../../SpriteLists/hero.walk.{i}.png"))
self.hero.walk_left_textures.append(arcade.load_texture(f"../../SpriteLists/hero.walk.{i}.png",mirrored = True))
self.hero.scale = 0.3
self.hero.center_x = SCREEN_WIDTH//2
self.hero.center_y = SCREEN_HEIGHT * 0.15
self.hero.texture_change_frames = 70
self.hero_list.append(self.hero)
self.hero_bullet = arcade.SpriteList()
def move(self):
if self.direction == "LEFT":
self.hero.change_x = -self.movementSpeed
self.hero.change_y = 0
self.bullet_direction = self.direction
if self.direction == "RIGHT":
self.hero.change_x = self.movementSpeed
self.hero.change_y = 0
self.bullet_direction = self.direction
if self.direction == "DOWN":
self.hero.change_y = -self.movementSpeed
self.hero.change_x = 0
if self.direction == "UP":
self.hero.change_y = self.movementSpeed
self.hero.change_x = 0
def update_hero(self):
self.hero_list.update()
self.hero_list.update_animation()
def draw_hero(self):
self.update_hero()
self.hero_list.draw()
def setDirection(self,newDirection):
self.direction = newDirection
def setSpeed(self,newSpeed):
self.movementSpeed = newSpeed
def getHeroY(self):
return self.hero.center_y
def getHeroX(self):
return self.hero.center_x
def getHero(self):
return self.hero
def hero_attact(self):
bullet = arcade.Sprite("../../SpriteLists/bullet.png")
bullet.scale = 0.3
bullet.change_x = -5
bullet.center_x = self.hero.left
bullet.center_y = self.hero.center_y
if self.bullet_direction == "RIGHT":
bullet.angle = 180
bullet.center_x = self.hero.right
bullet.change_x = 5
self.hero_bullet.append(bullet)
def bulletUpadate(self):
self.hero_bullet.update()
def bulletDraw(self):
self.hero_bullet.draw()
def bulletCheck(self):
for bullet in self.hero_bullet:
if bullet.center_x < 0 or bullet.center_x > SCREEN_WIDTH:
bullet.kill()
def getBullets(self):
return self.hero_bullet
def getBulletDamage(self):
return self.bullet_damage
def getLifePoints(self):
return self.lifePoints
def setlLifePoints(self,newLife):
self.lifePoints = newLife
class Enemy():
def __init__(self,lifePoints,name,lowerBarrier,upperBarrier):
self.name = name
self.lifePoints = lifePoints
self.enemy_list = arcade.SpriteList()
self.lower = lowerBarrier
self.upper = upperBarrier
self.enemyLifeDict = {}
self.enemyDamage = 5
enemy = arcade.AnimatedTimeSprite()
for i in range(0,8):
enemy.textures.append(arcade.load_texture(f"../../SpriteLists/z{i}.png"))
enemy.center_x = enemy.center_x = random.choice([-10,SCREEN_WIDTH + 20])
enemy.center_y = random.randrange(self.lower+20,self.upper - 20)
enemy.scale = 0.3
enemy.change_x = 0.5
self.enemy_list.append(enemy)
self.enemyLifeDict = {}
def drawEnemy(self):
self.enemy_list.draw()
def getEnemy(self):
return self.enemy_list
def enemyUpdate(self):
self.enemy_list.update()
self.enemy_list.update_animation()
def setChange(self, enemy):
if enemy.originalPosition == "RIGHT":
enemy.change_x = -0.5
elif enemy.originalPosition == "LEFT":
enemy.change_x = 0.5
def find(self,enemy,HeroY,HeroX):
if enemy.center_y > HeroY:
enemy.change_y = -0.5
self.setChange(enemy)
if enemy.center_y < HeroY:
enemy.change_y = 0.5
self.setChange(enemy)
if enemy.center_y == HeroY and enemy.center_x == HeroX:
enemy.change_y = 0
enemy.change_x = 0
def newUpdate(self,HeroY : int ,HeroX : int):
for enemy in self.enemy_list:
if enemy.originalPosition == "RIGHT":
if enemy.center_x < 800:
self.find(enemy,HeroY,HeroX)
if enemy.originalPosition == "LEFT":
if enemy.center_x > 100:
self.find(enemy, HeroY,HeroX)
def defineXLocation(self):
for i in range(len(self.enemy_list)):
if self.enemy_list[i].originalPosition == "LEFT":
self.enemy_list[i].center_x = -50 * i
if self.enemy_list[i].originalPosition == "RIGHT":
self.enemy_list[i].center_x = SCREEN_WIDTH + (50*(i+1))
def setTexture(self):
enemy = arcade.AnimatedTimeSprite()
for i in range(0,8):
enemy.textures.append(arcade.load_texture(f"../../SpriteLists/z{i}.png",mirrored=True))
enemy.scale = 0.3
enemy.change_x = -0.5
enemy.center_y = random.randrange(self.lower + 20, self.upper - 20)
enemy.originalPosition = "RIGHT"
return enemy
def addLifePoints(self):
for enemy in self.enemy_list:
self.enemyLifeDict[enemy] = self.lifePoints
def enemyIncrease(self,level):
waves = level * 5
for wave in range(waves):
enemy = arcade.AnimatedTimeSprite()
for i in range(0, 8):
enemy.textures.append(arcade.load_texture(f"../../SpriteLists/z{i}.png"))
enemy.center_x = random.choice([-10,SCREEN_WIDTH + 20])
enemy.change_x = 0.5
enemy.center_y = random.randrange(self.lower + 20, self.upper - 20)
enemy.scale = 0.3
if enemy.center_x > 0:
self.enemy_list.append(self.setTexture())
self.enemy_list.append(enemy)
self.addLifePoints()
self.defineXLocation()
def getEnemyLife(self):
return self.enemyLifeDict
def setEnemyLife(self, newLife,enemy):
self.enemyLifeDict[enemy] = newLife
def setEnemy(self,newValue):
self.enemy_list = newValue
class Barrier():
def __init__(self,x,y):
self.barrier_list_up = arcade.SpriteList()
self.barrier_list_down = arcade.SpriteList()
self.barrier_list_up.append(arcade.Sprite("../../SpriteLists/barrier.png",center_x = 25,center_y = y))
for i in range(0,int(SCREEN_WIDTH/50)+4):
barrier = arcade.Sprite("../../SpriteLists/barrier.png",center_x = 25 + (i * 41.6) ,center_y = y)
self.barrier_list_up.append(barrier)
barrier1 = arcade.Sprite("../../SpriteLists/barrier.png",center_x = 25 + (i * 41.6),center_y = 20)
self.barrier_list_down.append(barrier1)
def draw_wall_up(self):
self.barrier_list_up.draw()
def draw_wall_down(self):
self.barrier_list_down.draw()
def getWalllistUp(self):
return self.barrier_list_up[0].center_y
def getWalllistDown(self):
return self.barrier_list_down[0].center_y
class StartGame(arcade.View):
Hero = hero(100,"Zkiller")
Barriers = Barrier(25,341)
Enemys = Enemy(100,"Enemy",Barriers.getWalllistDown(),Barriers.getWalllistUp())
Recorder = Record()
backdrop = arcade.load_texture("../../SpriteLists/backdrop.png")
direction = ""
valueFor = 5
valueForX = 5
wave = 1
score = 0
def setupHeroBoundary(self, lowerYbarrier, upperYbarrier , heroY, leftXbarrier ,rightXbarrier , heroX):
""" partial """
if heroY > upperYbarrier:
self.valueFor = 0
if self.direction == "DOWN":
self.Hero.setSpeed(self.valueForX)
self.valueFor = 5
if self.direction == "UP":
self.Hero.setSpeed(self.valueFor)
if heroY < lowerYbarrier+50:
self.valueFor = 0
if self.direction == "UP":
self.valueFor = 5
self.Hero.setSpeed(self.valueForX)
if self.direction == "DOWN":
self.Hero.setSpeed(self.valueFor)
if heroX > rightXbarrier:
self.valueForX = 0
if self.direction == "LEFT":
self.Hero.setSpeed(self.valueFor)
self.valueForX = 5
if self.direction == "RIGHT":
self.Hero.setSpeed(self.valueForX)
if heroX < leftXbarrier:
self.valueForX = 0
if self.direction == "RIGHT":
self.valueForX = 5
self.Hero.setSpeed(self.valueFor)
if self.direction == "LEFT":
self.Hero.setSpeed(self.valueForX)
def on_show(self):
arcade.set_background_color((123,156,24,255))
self.Enemys.enemyIncrease(self.wave)
def on_draw(self):
arcade.start_render()
arcade.draw_lrwh_rectangle_textured(0,0,SCREEN_WIDTH,SCREEN_HEIGHT,self.backdrop)
arcade.draw_rectangle_filled(SCREEN_WIDTH/2,SCREEN_HEIGHT-50,SCREEN_WIDTH,100,(127,212,23,127))
arcade.draw_text_2(f"score:{self.score}",50,SCREEN_HEIGHT - 20,arcade.color.WHITE,15,align="center")
arcade.draw_text_2(f"wave:{self.wave}", 50, SCREEN_HEIGHT - 70, arcade.color.WHITE, 15, align="center")
arcade.draw_text_2(f"life:{self.Hero.getLifePoints()}", 400, SCREEN_HEIGHT - 20, arcade.color.WHITE, 15, align="center")
self.Barriers.draw_wall_up()
self.Hero.draw_hero()
self.Enemys.drawEnemy()
self.Barriers.draw_wall_down()
self.Hero.bulletDraw()
def on_key_press(self,key,modifier):
if key == arcade.key.LEFT:
self.Hero.setDirection("LEFT")
self.Hero.setSpeed(self.valueForX)
self.direction = "LEFT"
if key == arcade.key.RIGHT:
self.Hero.setDirection("RIGHT")
self.Hero.setSpeed(self.valueForX)
self.direction = "RIGHT"
if key == arcade.key.DOWN:
self.Hero.setDirection("DOWN")
self.Hero.setSpeed(self.valueFor)
self.direction = "DOWN"
if key == arcade.key.UP:
self.Hero.setDirection("UP")
self.Hero.setSpeed(self.valueFor)
self.direction = "UP"
if key == arcade.key.A:
self.Hero.hero_attact()
def on_key_release(self,key,modifier):
self.Hero.setSpeed(0)
def checkCollision(self,enemys,bullets):
print(len(enemys))
for bullet in bullets:
for enemy in enemys:
if arcade.check_for_collision(enemy,bullet):
bullet.kill()
newlife = self.Enemys.getEnemyLife()[enemy] - self.Hero.getBulletDamage()
self.Enemys.setEnemyLife(newlife,enemy)
if self.Enemys.getEnemyLife()[enemy] == 0:
enemy.kill()
self.score += 1
for enemy in enemys:
if arcade.check_for_collision(enemy,self.Hero.getHero()):
newlifes = self.Hero.getLifePoints() - self.Enemys.enemyDamage
self.Hero.setlLifePoints(newlifes)
self.score += 1
enemy.kill()
def checkHero(self):
if self.Hero.getLifePoints() == 0:
self.Recorder.getHighScore(self.score,self.wave)
self.Enemys.setEnemy(arcade.SpriteList())
self.wave = 1
self.score = 0
self.Hero.setlLifePoints(100)
Window.show_view(GameOver())
def checkEnemys(self):
if len(self.Enemys.getEnemy()) == 0:
self.wave += 1
self.Enemys.enemyIncrease(self.wave)
self.Enemys.enemyUpdate()
def on_update(self,delta_time):
self.Hero.update_hero()
self.Hero.move()
self.setupHeroBoundary(self.Barriers.getWalllistDown(),
self.Barriers.getWalllistUp(),
self.Hero.getHeroY(),50,SCREEN_WIDTH - 50,
self.Hero.getHeroX())
self.Enemys.newUpdate(self.Hero.getHeroY(),self.Hero.getHeroX())
self.Enemys.enemyUpdate()
self.Hero.bulletUpadate()
self.checkCollision(self.Enemys.getEnemy(),self.Hero.getBullets())
self.Hero.bulletCheck()
self.checkHero()
self.checkEnemys()
'''change = False
left = self.LEFT_Boundary + self.x_View
right = self.RIGHT_Boundary + self.x_View
if self.sprite1.center_x < left:
self.x_View = self.x_View - self.movement_speed
left = self.LEFT_Boundary - self.x_View
right = self.RIGHT_Boundary - self.x_View
change = True
if self.sprite1.center_x > (right-25):
self.x_View = self.x_View + self.movement_speed
left = self.LEFT_Boundary - self.x_View
change = True
if change:
arcade.set_viewport(self.x_View,SCREEN_WIDTH + self.x_View,0,SCREEN_HEIGHT)'''
Window = arcade.Window(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_TITLE)
Window.show_view(GameOver())
arcade.run()
|
e106dac64df3fe60e3ca115cd7b3e25b20d4e32c | EliasPapachristos/Python-Udacity | /iterators_generators.py | 1,281 | 4.3125 | 4 | lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"]
def my_enumerate(iterable, start=0):
# Implement your generator function here
count = start
for el in iterable:
yield count, el
count += 1
for i, lesson in my_enumerate(lessons, 1):
print("Lesson {}: {}".format(i, lesson))
"""
If you have an iterable that is too large to fit in memory in full (e.g., when dealing with large files),
being able to take and use chunks of it at a time can be very valuable.
Implement a generator function, chunker, that takes in an iterable and yields a chunk of a specified size at a time.
"""
def chunker(iterable, size):
# Implement function here
for el in range(0, len(iterable), size):
yield iterable[el:el + size]
for chunk in chunker(range(25), 4):
print(list(chunk))
"""
Generator Expressions
Here's a cool concept that combines generators and list comprehensions!
You can actually create a generator in the same way you'd normally write a list comprehension,
except with parentheses instead of square brackets.
"""
sq_list = [x**2 for x in range(10)] # this produces a list of squares
sq_iterator = (x**2 for x in range(10)) # this produces an iterator of squares
|
1f858c8755bb4c927e9269b9b01871f4d2b15e24 | Wmeng98/Leetcode | /CTCI/Python/notes.py | 5,949 | 3.8125 | 4 | # Python
'''
Note Python 3's int doesn't have a max size (bounded by memory)
float('inf') is for infinity, guaranteed to be higher than any other int value
range vs. xrange (deprc in python3)
If you want to write code that will run on both Python 2 and Python 3, use range() as the xrange function is deprecated in Python 3
range() is faster if iterating over the same sequence multiple times.
xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however)
Python - Pass by Value or Reference
Neither of these 2 concepts applicable
Values are sent to functions by means of object reference
Pass-by-object-reference
Almost everything in Python is an object
Values passed to functions by object-reference
If immutable, modified value NOT available outside scope of function
Mutable objects
list, dict, set, byte array
Immutable objects
int, float, complex, string, tuple, frozen set, bytes
Deque
Double ended queue (impl probably a DOUBLY LINKED LIST - Bidirectional)
`from collections import deque `
append(), appendLeft, pop(), popLeft()
index(ele, beg, end), insert(i,a), remove(), count()
Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container,
as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
'''
'''
Python Mutable Data Types
Id - unique identifier for object -> points to location in memory
In python all data stored as object with 3 things:
id, type, value
Mutable Objects (changeable)
list, dict, set
Immutable objects:
Integer, float, string, tuple, bool, frozenset
STRINGS ARE NOT MUTABLE in PYTHON!!!
Passing arguments
[MUTABLE] If a mutable object is called by reference in a function, the original variable may be changed. If you want to avoid changing the original variable, you need to copy it to another variable.
[IMMUTABLE] When immutable objects are called by reference in a function, its value cannot be changed.
None
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None
Comparing 2 objects in Python
compare for EQUALITY or IDENTITY
== for equality
is for identity
__eq__ to compare 2 class instances
Even if two class instances have the same attribute values,
comparing them using == will return False
You have to tell python how exactly you want equality be defined.
do so by defining a special method __eq__ like this
NOTE: because two different objects can sometimes compare equal
(if not then don't bother overloading it). In this case the return id(self)
hash function is BROKEN (EQUAL OBJECTS MUST HASH THE SAME)
List Comprehension
- List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list
SYNTAX
- `newlist = [expression for item in iterable if condition == True]`
- NOTE: The return value is a new list, leaving the old list unchanged
- NOTE:
- The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome
- `newlist = [x if x != "banana" else "orange" for x in fruits]`
DefaultDict
- Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dict class
that returns a dictionary-like object. The functionality of both dictionaries and defualtdict are almost same except for the
fact that defualtdict never raises a KeyError. It provides a default value for the key that does not exists.
- from collections import defaultdict
Complexity of "in"
- Here is the summary for in:
list - Average: O(n)
set/dict - Average: O(1), Worst: O(n)
The O(n) worst case for sets and dicts is very uncommon, but it can happen if __hash__ is implemented poorly.
This only happens if everything in your set has the same hash value.
operator.itemgetter
- dict.items() -> array of tuples
- Return a callable object that fetches item from its operand using the operand’s __getitem__() method.
If multiple items are specified, returns a tuple of lookup values. For example
'''
'''
Sorting
lists have built-in list.sort() method, modifies list in place
sorted() function builds a new sorted list from an iterable
[KEY]
key param to specify a function (or other callable) to be called on each list prior to
making comparisons
sorted("This is a test string from Andrew".split(), key=str.lower)
value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes
LAMBDAS are a good candidate here!!!
NOTE: Common pattern is to sort complex objects using some of the objects indices as keys
sorted(student_tuples, key=lambda student: student[2])
sorted(student_objects, key=lambda student: student.age)
[OPERATOR MODULE FUNCTIONS]
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster
***** from operator import itemgetter, attrgetter *****
sorted(student_tuples, key=itemgetter(2))
sorted(student_objects, key=attrgetter('age'))
multiple levels of sorting. For example, to sort by grade then by age
sorted(student_tuples, key=itemgetter(1,2))
sorted(student_objects, key=attrgetter('grade', 'age'))
'''
|
7f03a18b6dca6ae96ee5cecb4bcd8803b970a272 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/mrkpet004/question1.py | 470 | 4.09375 | 4 | """program to print out the first occurrence of a string from an input list of strings
peter m muriuki"""
#get list of strings and store them in an array
name_str=input("Enter strings (end with DONE):\n")
strings=[]
while name_str!="DONE":
strings.append(name_str)
name_str=input("")
print ("\n"+"Unique list:")
b=0
for item in strings:
a=strings.index(item)
if a==b:
print(strings[a]) #print only the first occurrence of string
b+=1
|
5e2ae9a2fc0e17b439329cb612195720c2b1695d | reshmaladi/Python | /1.Class/Language_Python-master/Language_Python-master/LC5_1.py | 119 | 3.8125 | 4 | x=eval(input("Enter no1\t"))
y=eval(input("Enter no2\t"))
if x>y:
print(x-y)
elif x==y:
print(x,y)
else:
print(x+y)
|
fff9952f6a04f5e30cbb030e79a3dea4ce24788e | oceancoll/leetcode | /5.最长回文字符串/answer.py | 1,175 | 3.8125 | 4 | # coding:utf-8
"""
最长回文子字符串
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd"
输出: "bb"
"""
def longestPalindrome(s):
"""
最长回文字符串
固定一个点向两边扩散的方法
https://leetcode-cn.com/problems/longest-palindromic-substring/solution/hui-wen-wen-ti-dong-tai-gui-hua-jspython5-zui-chan/
:param s:
:return:
"""
# 扩散函数
def extend(left, right, s):
while (left>=0 and right<len(s) and s[left]==s[right]):
left-=1
right+=1
return s[left+1:right]
n = len(s)
if n==0:
return ""
# 最小值兜底
res = s[0]
for i in range(n-1):
# 针对奇偶情况向两边扩散
e1 = extend(i,i,s)
e2 = extend(i,i+1,s)
# 判断奇偶对应长度和记录最大长度的关系
if max(len(e1), len(e2))>len(res):
res = e1 if len(e1) >len(e2) else e2
return res
print longestPalindrome("babad") |
a13e010650f6bd885f5876f393392689ab7ae958 | calgns/Fatorial | /facW.py | 1,077 | 3.953125 | 4 | fatorial = 1
contador = 4.65
while contador > 1:
# um jeito de fazer as coisas print(f'{contador:,.2f} x ', end='').
print('{%g} x ' % contador, end='') # end = '' , alinhou as coisas, sem ele seria na vertical.
fatorial *= contador # e eu deixei ele dentro de {chaves} por querer. não precisa usar chaves no %.
contador -= 1
print("1 = ",round(fatorial,2))
# round(fatorial) ou round(factorial,None) faz o mesmo, já com numero no lugar diz quantos numero vai mostrar apos a
# virgula. o mesmo serve pro print(f"{contador:,.2f}")
#
# todos os comandos acima fazem a mesma coisa, isso é apenas uma questão de gosto, escolher um deles.
# os comandos ocultos do python são confusos mas eu vou tentar te explicar
# esses pequenos e velhos comandos secretos...
# -esses são os importantes: %s = str; %d = int; %f = float.
# ja o resto... é confuso.
# _esses tem o mesmo resultado dos principais.. %r=float; %u=int(sem arredondar); %i=int(sem arredondar); %a=float;
# mas o %g deixa apenas aparecer 2 zeros0 apos a virgula.ou seja ele é um pouco melhor;
|
9a1ee4199c00c8da03b1f4ffe555ebc67b80f11f | here0009/LeetCode | /Python/666_PathSumIV.py | 1,885 | 4.0625 | 4 | """
If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers.
For each integer in this list:
The hundreds digit represents the depth D of this node, 1 <= D <= 4.
The tens digit represents the position P of this node in the level it belongs to, 1 <= P <= 8. The position is the same as that in a full binary tree.
The units digit represents the value V of this node, 0 <= V <= 9.
Given a list of ascending three-digits integers representing a binary tree with the depth smaller than 5, you need to return the sum of all paths from the root towards the leaves.
It's guaranteed that the given list represents a valid connected binary tree.
Example 1:
Input: [113, 215, 221]
Output: 12
Explanation:
The tree that the list represents is:
3
/ \
5 1
The path sum is (3 + 5) + (3 + 1) = 12.
Example 2:
Input: [113, 221]
Output: 4
Explanation:
The tree that the list represents is:
3
\
1
The path sum is (3 + 1) = 4.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-iv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
from collections import Counter
class Solution:
def pathSum(self, nums) -> int:
counts = Counter()
res = 0
for num in nums[::-1]:
d, p, v = [int(s) for s in list(str(num))]
if (d,p) not in counts:
counts[(d,p)] = 1
res += counts[(d,p)]*v
counts[(d-1,(p+1)//2)] += counts[(d,p)]
# print(counts)
return res
S = Solution()
nums = [113, 215, 221]
print(S.pathSum(nums))
nums = [113, 221]
print(S.pathSum(nums))
nums = [113,229,349,470,485]
print(S.pathSum(nums)) |
994dba1d4c17082098128729072273cb8f9c369d | tsmith328/AoC2015 | /Day01/Day1.py | 394 | 3.703125 | 4 | floor = 0
with open("input1.txt") as f:
i = 1
skip = False
while True:
c = f.read(1)
if not c:
break
if c == "(":
floor += 1
else:
floor -= 1
if floor == -1 and not skip:
print("Entered basement on instruction number:", i)
skip = True
i += 1
print("Ends on floor:", floor) |
d648b539168897d283ff38fc30c3f409bbb31553 | CoreyFedde/voiceapp311 | /BostonData/Intents/SetAddressIntent.py | 1,354 | 3.671875 | 4 | from lambda_function.lambda_function import *
def set_address_in_session(intent, session):
"""
Sets the address in the session and prepares the speech to reply to the
user.
"""
# print("SETTING ADDRESS IN SESSION")
card_title = intent['name']
session_attributes = {}
should_end_session = False
if 'Address' in intent['slots']:
current_address = intent['slots']['Address']['value']
session_attributes = create_current_address_attributes(current_address)
speech_output = "I now know your address is " + \
current_address + \
". Now you can ask questions related to your address" \
". For example, when is trash day?"
reprompt_text = "You can find out when trash is collected for your " \
"address by saying, when is trash day?"
else:
speech_output = "I'm not sure what your address is. " \
"Please try again."
reprompt_text = "I'm not sure what your address is. " \
"You can tell me your address by saying, " \
"my address is 123 Main St., apartment 3."
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session))
|
c9415195d2a8a2f61bf3daae3199a7ecf2409ac8 | MagicDataStructures/Trabajo_01_prueba | /src/trabajo01_1.py | 4,243 | 3.5625 | 4 |
class Pawn:
def __init__(self, color):
self.color = color;
def __str__(self):
if self.color == 0:
return '??';
else:
return '?';
class Rook:
def __init__(self, color):
self.color = color;
def __str__(self):
if self.color == 0:
return '?';
else:
return '?';
class Knight:
def __init__(self, color):
self.color = color;
def __str__(self):
if self.color == 0:
return '?';
else:
return '?';
class Bishop:
def __init__(self, color):
self.color = color;
def __str__(self):
if self.color == 0:
return '?';
else:
return '?';
class Queen:
def __init__(self, color):
self.color = color;
def __str__(self):
if self.color == 0:
return '?';
else:
return '?';
class King:
def __init__(self, color):
self.color = color;
def __str__(self):
if self.color == 0:
return '?';
else:
return '?';
class ChessGame:
def __init__(self, white_player, black_player):
self.white_player = white_player;
self.black_player = black_player;
self.white_captured_pieces = [];
self.black_captured_pieces = [];
# init board
self.board = [[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
]
#init white pieces
# zero represents color white
for i in range(8):
self.board[6][i] = Pawn(0);
self.board[7][0] = Rook(0);
self.board[7][1] = Knight(0);
self.board[7][2] = Bishop(0);
self.board[7][3] = Queen(0);
self.board[7][4] = King(0);
self.board[7][5] = Bishop(0);
self.board[7][6] = Knight(0);
self.board[7][7] = Rook(0);
#init black pieces
# One represents the color black, of course. lol
for i in range(8):
self.board[1][i] = Pawn(1);
self.board[0][0] = Rook(1);
self.board[0][1] = Knight(1);
self.board[0][2] = Bishop(1);
self.board[0][3] = Queen(1);
self.board[0][4] = King(1);
self.board[0][5] = Bishop(1);
self.board[0][6] = Knight(1);
self.board[0][7] = Rook(1);
def move(self, from_1, from_2, to_1, to_2):
#if the space is empty, we just move the piece
if self.board[from_1][from_2] != 0:
piece = self.board[from_1][from_2];
if self.board[to_1][to_2] != 0:
captured_piece = self.board[to_1][to_2];
self.white_captured_pieces.append(captured_piece);
self.board[to_1][to_2] = piece;
self.board[from_1][from_2] = 0;
def display_moves(self): #mostrar movimientos
for i in self.board:
print([str(item) for item in i]);
def display_captured_pieces(self): #mostrar piezas capturadas
pass;
def undo(self): #Deshacer ltimo movimiento
pass;
def add(self, mov_index): #agregar movimiento en cualquier lugar
pass;
def delete(self, mov_index): #Eliminar movimiento
pass;
awesome = ChessGame('me', 'Magnus Carlsen');
switch = True;
notation = ['a', 'b', 'c', 'd','e','f','g','h'];
while switch:
print('inserte la coordenada de la pieza que desea mover');
coordenada_1 = str(input());
first = int(notation.index(coordenada_1[0]));
second = int(coordenada_1[1]);
print('Genial. Ahora inserte la coordenada a la que deseas mover tu pieza');
coordenada_2 = str(input());
primero = int(notation.index(coordenada_2[0]));
segundo = int(coordenada_2[1]);
awesome.move((8-second), first, (8-segundo), primero);
awesome.display_moves();
print('quieres salir?');
hey = str(input());
if hey == 'si':
break;
awesome.display_moves();
|
4189247227a6de559076207b14c6a6491a4c98a4 | ismaildawoodjee/nifi-data-pipeline | /sourcefiles/reading_writing_files/write_file.py | 370 | 3.890625 | 4 | """Writing to a CSV file"""
import csv
def write_example_csv():
with open("example.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
header = ["name", "age"]
writer.writerow(header)
row = ["Wesley", 26]
writer.writerow(row)
if __name__ == "__main__":
write_example_csv()
|
37d8579ce1f4989454f9f9f11947574e33ef521a | agentnova/LuminarPython | /Luminaarpython/collections/set/set.py | 487 | 3.71875 | 4 | emptyset = set()
a = {1, 2, 3, 4}
a.add(7)
print(a)
st = {1, 2, 3, 4}
st2 = {4, 5, 89}
st.update(st2)
print(st)
# duplicate not allowed
# insertion order not presered
# not mutable
# can store multiple types of values
a = {1, 4, 5}
b = {5, 7, 3}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
# create a list
# lst=[10,10,20,20,23,5,63,5,23]
# remove duplicate
# create a list students with name
# create a failed students list
# create passed students and print
|
a2db305d2c7e785ce30b4a5c577e8e9917f67481 | Jaandlu/Boggle | /scrabble_score.py | 1,546 | 3.859375 | 4 | import random
import string
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
class Player:
def __init__(slef, points):
points = ""
p1 = Player(0)
p2 = Player(0)
def score_counter(word, player):
player.points = 0
word = word.lower()
for l in word:
player.points += score[l]
print("You scored " + str(player.points) + " points")
def get_winner():
x = p1.points
y = p2.points
if x == y:
print("It's a tie!")
elif x > y:
print("Player 1 wins!")
else:
print("Player 2 wins!")
def play_game():
print("Here are your letters")
board = ''.join([random.choice(string.ascii_lowercase) for l in range(16)])
print(board)
print("Player 1 make a word.")
p1_word = input(": ")
score_counter(p1_word, p1)
print("Player 2 make a word.")
p2_word = input(": ")
score_counter(p2_word, p2)
get_winner()
play_again()
def play_again():
print("Would you like to play again? y or n: ")
user_input = input(": ")
if str(user_input) == "y":
play_game()
elif str(user_input) == "n":
quit
else:
print(user_input + " is not a valid response.")
play_again()
print("Let's play Boggle!")
play_game()
|
cd483b8ee5ce41bba0cb1778dad4ac8eca9d7873 | dh256/adventofcode | /2018/Day17/day17.py | 10,030 | 3.625 | 4 | from collections import namedtuple
import click
Point = namedtuple('Point', 'x y')
SAND = '.'
WATERFLOW = '|'
WATERSTANDING = '~'
CLAY = '#'
SPRING = '+'
class Grid():
def __init__(self,clay_strands):
self.spring=Point(500,0)
self.clay_strands = clay_strands
# add in sand
self.grid = []
for y in range(0,self.clay_strands.maxY+1):
row = [SAND] * (self.clay_strands.maxX+1)
self.grid.append(row)
#self.grid = [[SAND] * (self.clay_strands.maxX+1)] * (self.clay_strands.maxY+1)
self.grid[self.spring.y][self.spring.x] = SPRING
for strand in self.clay_strands.strands:
if strand.start.x == strand.end.x:
# vertical strand
for y in range(strand.start.y,strand.end.y+1):
self.grid[y][strand.start.x] = CLAY
else:
# horizonal strand
for x in range(strand.start.x,strand.end.x+1):
self.grid[strand.start.y][x] = CLAY
def constrained(self,point):
'''
determines whether at current pos is constrained
constrained if:
- while all entries in row y+1 are either CLAY or STANDING water and hit a CLAY at x-n (A) and x+m (B)
- essentially need to find position of last # to left and first # to right
then check that all entries in row y+1 between A and B are either all CLAY or are all STANDING WATER
'''
# go left
left_point = point
left_constrain = None
while left_constrain is None:
if self.grid[left_point.y][left_point.x-1] == CLAY:
left_point = Point(left_point.x-1,left_point.y)
left_constrain = True
else:
if self.grid[left_point.y+1][left_point.x-1] in (CLAY,WATERSTANDING):
left_point = Point(left_point.x-1,left_point.y)
else:
left_constrain = False
# go right
right_point = point
right_constrain = None
while right_constrain is None:
if self.grid[right_point.y][right_point.x+1] == CLAY:
right_point = Point(right_point.x+1,right_point.y)
right_constrain = True
else:
if self.grid[right_point.y+1][right_point.x+1] in (CLAY,WATERSTANDING):
right_point = Point(right_point.x+1,right_point.y)
else:
right_constrain = False
return (left_constrain and right_constrain,left_point.x,right_point.x)
def fill(self,pos=None):
'''
fill grid with water
can ignore everything above, water will start at spring.x,minY-1
'''
if pos is None:
pos = Point(self.spring.x,self.clay_strands.minY-1)
'''
can water fall - always fall if it can?
can fall if next square down is sand or y position < maxY
if it can fall keep going
if it can't fall, then need to check whether constrained
if y > maxY then stop
constrained if a clay strand found both left and right
if constrained fill row with standing water and move up
if not constrained flow left and right until can fall again or is constrained
Note: when working out if constrained ANCHOR point must be current x position of water
when move up it is essential that x stays the same
Recursion is in here somewhere - perhaps when splitting left and right.
'''
while True:
fall = self.can_fall(pos)
if fall[0] == False:
if fall[1] == "MAX" or fall[1] == "WATER_FLOW":
# stop - nothing more to do
break
else:
'''
either fully constrained (left and right clay on same row) in which case fill row with standing water between left constrain + 1 and right constrain - 1
or constrained on one side in which case water will flow to constrained side and stop and flow to unconstrained side until can fall
'''
constrained = self.constrained(pos)
if constrained[0]:
for x in range(constrained[1]+1,constrained[2]):
self.grid[pos.y][x] = WATERSTANDING
pos=Point(pos.x,pos.y-1)
else:
'''
find point where either:
'''
# go left
new_pos=pos
while True:
if self.grid[new_pos.y][new_pos.x-1] == CLAY:
# stop
break
else:
new_pos = Point(new_pos.x-1,new_pos.y)
self.grid[new_pos.y][new_pos.x] = WATERFLOW
fall = self.can_fall(new_pos)
if fall[0]:
# recurse
self.fill(new_pos)
break
# go right
new_pos=pos
while True:
if self.grid[new_pos.y][new_pos.x+1] == CLAY:
# stop
break
else:
new_pos = Point(new_pos.x+1,new_pos.y)
self.grid[new_pos.y][new_pos.x] = WATERFLOW
fall = self.can_fall(new_pos)
if fall[0]:
# recurse
self.fill(new_pos)
break
break
else:
pos = Point(pos.x,pos.y+1)
self.grid[pos.y][pos.x] = WATERFLOW
def can_fall(self,point):
'''
Returns a tuple (boolean,reason)
if boolean = FALSE, a reason is given either CLAY if encountered clay, WATER if encountered standing water or MAX if encountered MAXY
'''
fall = True
reason = None
if point.y >= self.clay_strands.maxY:
fall = False
reason = "MAX"
else:
if self.is_clay(point.x,point.y+1):
fall = False
reason = "CLAY"
elif self.is_water_standing(point.x,point.y+1):
fall = False
reason = "WATER"
elif self.is_water_flow(point.x,point.y+1):
fall = False
reason = "WATER_FLOW"
return (fall,reason)
def __repr__(self):
output = ""
for row in self.grid[self.clay_strands.minY:self.clay_strands.maxY+1]:
for col in row[self.clay_strands.minX:self.clay_strands.maxX+1]:
output += col
output += '\n'
return output
def countwater(self):
water = 0
for row in self.grid[self.clay_strands.minY:self.clay_strands.maxY+1]:
water_cells = [entry for entry in row if entry == WATERFLOW or entry == WATERSTANDING]
water += len(water_cells)
return water
'''
def is_sand(self,x,y):
return self.grid[y][x] == SAND
'''
def is_clay(self,x,y):
return self.grid[y][x] == CLAY
def is_water_standing(self,x,y):
return self.grid[y][x] == WATERSTANDING
def is_water_flow(self,x,y):
return self.grid[y][x] == WATERFLOW
'''
def is_water(self,x,y):
return self.is_water_flow(x,y) or self.is_water_standing(x,y)
'''
class ClayStrand(namedtuple('ClayStrand', 'start end')):
def __repr__(self):
return f'({self.start.x},{self.start.y})-({self.end.x},{self.end.y})'
class ClayStrands():
def __init__(self,filename):
with open(filename,"r") as fileinput:
self.strands = [self._getStrand(line) for line in fileinput]
self.minY = min(self.strands, key=lambda s:s.start.y).start.y
self.maxY = max(self.strands, key=lambda s:s.end.y).end.y
self.minX = min(self.strands, key=lambda s:s.start.x).start.x - 1
self.maxX = max(self.strands, key=lambda s:s.end.x).end.x + 1
def _getStrand(self,line):
# want to turn puzzle input into two (x,y) coords marking start and end point of a clay strand
# if first coord label is x then (x,coord2_start) to (x,coord2_end)
# if first coord label is y then (coord2_start,y) to (coord2_end,y)
startPoint = None
endPoint = None
line = line.strip('\n')
coords = line.split(', ')
coord_1_label = coords[0][0]
coord_1_value = int(coords[0][2:])
coord2_start_end = coords[1][2:].split('..')
coord2_start = int(coord2_start_end[0])
coord2_end = int(coord2_start_end[1])
if coord_1_label == "x":
startPoint = Point(coord_1_value,coord2_start)
endPoint = Point(coord_1_value,coord2_end)
else:
startPoint = Point(coord2_start,coord_1_value)
endPoint = Point(coord2_end,coord_1_value)
return(ClayStrand(startPoint,endPoint))
@click.command()
@click.option(
'--file',
'-f',
help='Input file'
)
def run(file):
strands = ClayStrands(file)
grid = Grid(strands)
grid.fill()
print(f'Water can reach {grid.countwater()} tiles')
# first guess of 533 was too low
# need to look at stopping if water found - did this
# second guess of 36799 was too high
if __name__ == "__main__":
run()
|
f864abf62c7849c31b37836ca10ae6ef773a1f48 | hbrinkhuis/HTBR.AoC2020 | /day3.py | 515 | 3.71875 | 4 | import math
import stdfuns
data = stdfuns.open_file_split('day3.txt')
rows = len(data)
columns = len(data[0])
matrix = [[i for i in j] for j in data]
def traverse(right, down):
trees = 0
for i, val in enumerate(range(0, rows, down)):
if matrix[val][(i*right) % columns] == '#':
trees += 1
return trees
print('Number of trees:', traverse(3,1), '(part 1)')
trees = list(map(traverse, (1,3,5,7,1), (1,1,1,1,2)))
print('Product of number of trees:', math.prod(trees), '(part 2)') |
d63ef14d19b241c3d5732f4aeda66da9a8c11072 | matty-boy79/python_learning | /lambda.py | 136 | 3.765625 | 4 | """
I DON'T UNDERSTAND THIS!!!!
"""
def myfunc(n):
return lambda a: a * n
mydoubler = myfunc(3)
print(mydoubler(11))
|
282a5cbd558cc73bf488ba32a713448e526c85c7 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/String/program-68.py | 1,916 | 4.15625 | 4 | #!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Create two strings from a given string. Create the first string #
# using those character which occurs only once and create the #
# second string which consists of multi-time occurring characters #
# in the said string. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : November 5, 2019 #
# #
############################################################################################
def obtain_data_from_user(input_mess: str) -> str:
is_valid, user_data = False, ''
while is_valid is False:
try:
user_data = input(input_mess)
if len(user_data) == 0:
raise ValueError('Please enter some string to work with')
is_valid = True
except ValueError as ve:
print(f'[ERROR]: {ve}')
return user_data
def process_str(main_str: str) -> dict:
data = dict(repeat='', unique='')
found_repeat = []
for char in main_str:
if main_str.count(char) > 1:
if char not in found_repeat:
data['repeat'] += char
found_repeat.append(char)
else:
data['unique'] += char
return data
if __name__ == "__main__":
main_data = obtain_data_from_user(input_mess='Enter main string: ')
proc_data = process_str(main_str=main_data)
print(f"Repeated: {proc_data['repeat']}\nNo repeated: {proc_data['unique']}") |
6efceec38b9e224017629512747906318c0756cb | komodikus/pentest_tools | /search_and_sort_files/main.py | 1,349 | 3.734375 | 4 | from tkinter import filedialog
from tkinter import Tk
import os
import shutil
from variables import default_dir, folder_to_copy, neededs_formats
def create_folder_for_format(folder_to_copy, file_format):
if not os.path.exists(folder_to_copy + '/{}'.format(file_format)):
os.makedirs(folder_to_copy + '/{}'.format(file_format))
def get_full_path_name(main_folder, file_name):
return main_folder + '\\' + file_name
def is_file_format(file, format):
if file.endswith('.{}'.format(format)):
return True
else:
return False
for i in neededs_formats:
create_folder_for_format(folder_to_copy, i)
if __name__ == '__main__':
main_path = filedialog.askdirectory(initialdir=default_dir, title="Select the Folder")
root = Tk()
root.withdraw()
for (dirpath, dirnames, filenames) in os.walk(main_path):
if len(filenames)<2:
check_format = filenames[0][-3:]
if check_format in neededs_formats:
shutil.copy(get_full_path_name(dirpath, *filenames), "{}\{}".format(folder_to_copy, check_format))
else:
for finded_file in filenames:
check_format = finded_file[-3:]
shutil.copy(get_full_path_name(dirpath, finded_file), "{}\{}".format(folder_to_copy, check_format))
print("Its all right")
|
c5240f3b9000152ab09f64d3ea639ad063e34de3 | djrrb/Python-for-Visual-Designer-Summer-2021 | /session-3/bezierPathDemo.py | 550 | 3.71875 | 4 | # make a shape using BezierPath
# shape height
sh = 200
# determine the length of each handle randomly
rightHandleLength = randint(-150, 150)
leftHandleLength = randint(-150, 150)
# define a bezier path
bp = BezierPath()
# move to my starting point
bp.moveTo((0, 0))
# straight line across
bp.lineTo((width(), 0))
# straight line up
bp.lineTo((width(), sh))
# make my curve
bp.curveTo(
(width(), sh+rightHandleLength), # right handle
(0, sh-leftHandleLength), # left handle
(0, sh) # upper left point
)
# draw the path
drawPath(bp) |
784cf90317229acc2a138f879c94b3b779a7af2c | Sushilkumar168141/cryptix_ctf_dump | /welcome_to_the_real_deal/ape.py | 339 | 3.5 | 4 | import random
from math import sqrt
a=''
with open('hashed.txt','r') as file:
a=file.read()
x = []
x = a.split(':')
wordlist=[]
msg = []
for j in x[:-1]:
wordlist.append(j)
#msg.append()
print(wordlist)
for word in wordlist:
msg.append(int(word,0))
print(msg)
unhashed_number = int(pow(numerator/denominator,2))
subtract_key = data
|
f165a3b01862f08e7f366f9a2022c987944ba863 | Anshul-GH/jupyter-notebooks | /UdemyPythonDS/DS_BinarySearchTree/App.py | 369 | 3.84375 | 4 | from DS_BinarySearchTree.BinarySearchTree import BST
bst = BST()
bst.insert(12)
bst.insert(10)
bst.insert(-2)
bst.insert(1)
print('Traversing the original tree:')
bst.traverseInOrder()
print('Max value in the tree:', bst.getMax())
print('Min value in the tree:', bst.getMin())
print('Traversing the tree with one node removed:')
bst.remove(10)
bst.traverseInOrder() |
bec1dde8f4d25459a8daaa4e3d6aab04bf47bb50 | Nkhinatolla/PoP | /Lection-4/while.py | 141 | 3.609375 | 4 | i = 5
while i < 15:
print(i, end = " ")
i = i + 2
print()
j = 1
while j < 15:
j = j + 1
if (j == 4):
continue
print(j, end = " ")
|
aac81fa6b8af0af8f37bddc2b09f3a57bd7b0c40 | mnickey/argParse | /argparse_basic.py | 3,740 | 4.3125 | 4 | """ positional arguments """
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("square", help="display a square of a given number",
# type=int)
# args = parser.parse_args()
# print args.square**2
""" optional arguments """
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("--verbosity", help="increase output verbosity")
# args = parser.parse_args()
# if args.verbosity:
# print "verbosity turned on"
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("-v", "--verbosity",
# help="increase output verbosity",
# action="store_true")
# args = parser.parse_args()
# if args.verbosity:
# print "verbosity turned on"
""" positional and optional arguments """
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("square", type=int,
# help="display a square of a given number")
# parser.add_argument("-v", "--verbose", action="store_true",
# help="increase output verbosity")
# args = parser.parse_args()
# answer = args.square**2
# if args.verbose:
# print "the square of {} equals {}".format(args.square, answer)
# else:
# print answer
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("square", type=int,
# help="display a square of a given number")
# parser.add_argument("-v", "--verbosity", type=int,
# help="increase output verbosity")
# args = parser.parse_args()
# answer = args.square**2
# if args.verbosity == 2:
# print "the square of {} equals {}".format(args.square, answer)
# elif args.verbosity == 1:
# print "{}^2 == {}".format(args.square, answer)
# else:
# print answer
# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("square", type=int,
# help="display a square of a given number")
# parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
# help="increase output verbosity")
# args = parser.parse_args()
# answer = args.square**2
# if args.verbosity == 2:
# print "the square of {} equals {}".format(args.square, answer)
# elif args.verbosity == 1:
# print "{}^2 == {}".format(args.square, answer)
# else:
# print answer
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y
if args.quiet:
print answer
elif args.verbose:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
print "{}^{} == {}".format(args.x, args.y, answer)
"""
How do you create an argument parser?
import argparse
parser.add_argument("-x". "--Xtra_log_name", action="store_true")
How do you find out the command line arguments an app using argparse takes?
run the script with a '--help' or '-h' flag
What is the difference between a positional and an optional argument?
a positional argument will run based on it's position in the command execution
an optional argument will execute 'optional' commands but do not have to be present
for the command line to run
How would you add an optional argument for receiving an integer?
add a type=int in the parser.add_argument line
What does the action parameter of add_argument do?
action lines change the value from Null to what is passed in.
How do you add a default value for an argument?
set a default=xxx in the parser.add_argument line
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.