text
stringlengths
37
1.41M
from typing import List class Solution: def isBipartite(self, graph: List[List[int]]) -> bool: W, R, B = range(3) N = len(graph) colors = [W] * N for vertex in range(N): if colors[vertex] != W: continue stack = [vertex] colors[vertex] = R while stack: curr = stack.pop() curr_color = colors[curr] for neig in graph[curr]: neig_color = colors[neig] if neig_color == W: stack.append(neig) colors[neig] = R if curr_color == B else B elif neig_color == curr_color: return False return True
""" T: O(N) S: O(N) Just do as the description says. Python's split correctly handles leading and trailing whitespace and properly splits on multiple whitespace chars. """ class Solution: def reverseWords(self, s: str) -> str: return ' '.join(reversed(s.split()))
""" T: O(N) S: O(N) Process every character, check if it is the same as the previous one. If so - don't put it into the stack and pop the last character in the stack. This way, our algorithm will work even when we have to do multiple removals in one go, i.e. for abba, because bb will never be added to the stack. """ from typing import List class Solution: def removeDuplicates(self, S: str) -> str: stack = [] # type: List[str] for char in S: if not stack or stack[-1] != char: stack.append(char) else: stack.pop() return "".join(stack)
""" T: O(N) S: O(N) The gist of the solution is to determine a correct index for each node. Since we are doing BFS, also known as level traversal, we can simply put the node to the appropriate bucket with the nodes of the same vertical index. In the end, we use recorded minimum and maximum indices to get a proper order. """ import collections from typing import Dict, List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def verticalOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] column_order = collections.defaultdict( list) # type: Dict[int, List[int]] curr_index = min_index = max_index = 0 nodes_queue = collections.deque([(root, curr_index)]) while nodes_queue: curr, index = nodes_queue.popleft() if not curr: continue min_index = min(min_index, index) max_index = max(max_index, index) column_order[index].append(curr.val) nodes_queue.append((curr.left, index - 1)) nodes_queue.append((curr.right, index + 1)) return [ column_order[index] for index in range(min_index, max_index + 1) ]
from typing import List class Solution: def colorBorder(self, grid: List[List[int]], r0: int, c0: int, color: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) bfs, component, border = [[r0, c0]], set([(r0, c0)]), set() for r0, c0 in bfs: for i, j in [[0, 1], [1, 0], [-1, 0], [0, -1]]: r, c = r0 + i, c0 + j if 0 <= r < m and 0 <= c < n and grid[r][c] == grid[r0][c0]: if (r, c) not in component: bfs.append([r, c]) component.add((r, c)) else: border.add((r0, c0)) for x, y in border: grid[x][y] = color return grid
from typing import List class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: target_count = 0 for num in nums: if num == target: target_count += 1 elif num > target: break return target_count > len(nums) // 2
import collections from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findMode(self, root: TreeNode) -> List[int]: result = [] if not root: return result values_count = collections.Counter() def traverse(node): if node: values_count[node.val] += 1 traverse(node.left) traverse(node.right) traverse(root) max_count = max(values_count.values()) for val, count in values_count.most_common(): if count == max_count: result.append(val) return result
from typing import List class Solution: def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool: ax_min, ay_min, ax_max, ay_max = rec1 bx_min, by_min, bx_max, by_max = rec2 right = min(ax_max, bx_max) left = max(ax_min, bx_min) if not right > left: return False bottom = max(ay_min, by_min) top = min(ay_max, by_max) if not top > bottom: return False return True
import requests print(""" ____ _ | _ \ ___ __ _ _ _ ___ ___| |_ ___ _ __ | |_) / _ \/ _` | | | |/ _ \/ __| __/ _ \ '__| | _ < __/ (_| | |_| | __/\__ \ || __/ | |_| \_\___|\__, |\__,_|\___||___/\__\___|_| |_| ------------------------------------------ | Developer: Muhammet Sahin Adibas | | Twitter: twitter.com/muhammetadibas | | Blog: muhammetsahinadibas.com.tr | | Github: github.com/muhammetsahinadibas | ------------------------------------------ """) url = input("Enter the URL you want to request: ") fuzz_url_question = input("\nDo you want to add a number increasing by the amount of the request into the URL ? (Yes=1 , No=2): ") if(fuzz_url_question == "1"): enter_fuzz_url_question = input(" |------> Enter FUZZ URL ( Example: https://example.com/user.php?id=FUZZ ): ") number_of_requests = int(input("\nEnter the number of requests: ")) content_question = input("\nDo you want the content of the site ? (Yes=1 , No=2): ") value_question = input("\nAre there any values you want the site to have in it ? (Yes=1 , No=2): ") if(value_question == "1"): enter_value_question = input(" |------> Enter the value you want to search: ") letters_value_question = input(" |------> Do you want to make all letters in the site uppercase or lowercase ? (Upper=1, Lower=2, Do not change=3): ") # ------------------------------------ Events ------------------------------------ print("\n \nStarted !! Please wait.") if(content_question == "1" and value_question == "2"): if(fuzz_url_question == "1"): for i in range(number_of_requests): new_url = enter_fuzz_url_question.replace("FUZZ",str(i)) r = requests.get(new_url) print("\n \n + |------> " + new_url + "\n" + r.text) if(fuzz_url_question == "2"): for i in range(number_of_requests): r = requests.get(url) print("\n \n + |------> " + url + "\n" + r.text) if(value_question == "1"): if(fuzz_url_question == "1"): for i in range(number_of_requests): new_url = enter_fuzz_url_question.replace("FUZZ",str(i)) r = requests.get(new_url) if(letters_value_question == "1"): data = r.text.upper() elif(letters_value_question == "2"): data = r.text.lower() elif(letters_value_question == "3"): data = r.text if enter_value_question in data: print("\n + " + "'" + enter_value_question + "'" + " Found! |------> " + new_url) if(fuzz_url_question == "2"): for i in range(number_of_requests): r = requests.get(url) if(letters_value_question == "1"): data = r.text.upper() elif(letters_value_question == "2"): data = r.text.lower() elif(letters_value_question == "3"): data = r.text if enter_value_question in data: print("\n + " + "'" + enter_value_question + "'" + " Found! |------> " + url) if(content_question == "2" and value_question == "2"): if(fuzz_url_question == "1"): for i in range(number_of_requests): new_url = enter_fuzz_url_question.replace("FUZZ",str(i)) r = requests.get(new_url) print("\n \nSuccessful!") if(fuzz_url_question == "2"): for i in range(number_of_requests): r = requests.get(url) print("\n \nSuccessful!")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 17 21:15:36 2017 @author: ranko """ import os import pandas as pd stats = pd.DataFrame(columns = ("language", "author", "title", "length","unique")) text = "This is my test text. We're keeping this text short to keep things managable." def count_words(text): """ Count the number of times each word occurs in text(str) """ text = text.lower() skips = [".", ",", ";", ":", "'", '"'] for ch in skips: text = text.replace(ch, "") word_counts = {} for word in text.split(" "): if word in word_counts: word_counts[word] += 1 else: word_counts[word] = 1 return word_counts def read_book(title_path): """ Reads a book and returns it as string """ with open(title_path, "r", encoding = "utf8") as current_file: text = current_file.read() text = text.replace("\n", "").replace("\r", "") return text def word_stats(word_counts): num_unique = len(word_counts) counts = word_counts.values() return(num_unique, counts) title_num = 1 book_dir = "./Books" for language in os.listdir(book_dir): for author in os.listdir(book_dir + "/" + language): for title in os.listdir(book_dir + "/" + language + "/" + author): inputfile = book_dir+"/"+language + "/"+author+"/"+title print(inputfile) text = read_book(inputfile) (num_unique, counts) = word_stats(count_words(text)) stats.loc[title_num] = language, author.capitalize(), title.replace(".txt",""), sum(counts),num_unique title_num += 1
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def printTree(self, root): """ :type root: TreeNode :rtype: List[List[str]] """ self.height = 0 self.find_height(root, 1) width = (1 << self.height) - 1 self.res = [["" for _ in range(width)] for _ in range(self.height)] self.rec(root, 0, 0, width - 1) return self.res def find_height(self, root, y): if not root: self.height = max(self.height, y-1) return self.find_height(root.left, y+1) self.find_height(root.right, y+1) def rec(self, node, y, start, end): if not node: return self.res[y][(start + end) / 2] = str(node.val) self.rec(node.left, y + 1, start, (start+end) / 2 - 1) self.rec(node.right, y + 1, (start+end) / 2 + 1, end)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def largestBSTSubtree(self, root): """ :type root: TreeNode :rtype: int """ self.ret = 1 if not root: return 0 self.rec(root) return self.ret def rec(self, root): if root.left and root.right: left_num, left_min, left_max = self.rec(root.left) right_num, right_min, right_max = self.rec(root.right) if left_min is not None and right_min is not None and root.val > left_max and root.val < right_min: self.ret = max(left_num + 1 + right_num, self.ret) return left_num + 1 + right_num, left_min, right_max else: return 1, None, None elif root.left: left_num, left_min, left_max = self.rec(root.left) if left_min is not None and root.val > left_max: self.ret = max(left_num + 1, self.ret) return left_num + 1, left_min, root.val else: return 1, None, None elif root.right: right_num, right_min, right_max = self.rec(root.right) if right_min is not None and root.val < right_min: self.ret = max(right_num + 1, self.ret) return right_num + 1, root.val, right_max else: return 1, None, None else: return 1, root.val, root.val
class Codec: def encode(self, strs): """Encodes a list of strings to a single string. :type strs: List[str] :rtype: str """ ret = [] num = [] for i in strs: ret.append(i) num.append(',' + str(len(i))) if len(num) > 0: num.append(',') ret.append(''.join(num)) ret.append(str(len(strs))) return ''.join(ret) def decode(self, s): """Decodes a single string to a list of strings. :type s: str :rtype: List[str] """ ret = [] if len(s) > 0: lenght = 0 for i in xrange(len(s)-1, -1, -1): if s[i] == ',': length = int(s[i+1:len(s)]) break else: return [] current = 0 sublength = [] count = 0 last_comma = len(s) for i in xrange(len(s) - 1, -1, -1): if s[i] == ',': count += 1 if last_comma != len(s): sublength.append(int(s[i+1:last_comma])) last_comma = i if count == length + 1: break sublength.reverse() for i in xrange(length): ret.append(s[current:current+sublength[i]]) current += sublength[i] return ret # Your Codec object will be instantiated and called as such: strings = ["1111111111111111111111111","2222222222222222222222222222222222222222222222222","333333333333333333333333333333","4444","555555555555555555555555555555555555555","666","777777777","8888888888888","99999999999999999999999999999999999999999999","U;P N[rokvXh(E9k2=?7`/ Cyc8!HM+av1AVNm5f=<.?ak+Sac>e?h8ob|h)U?bU{@;$a7w7Fr","y`g,n.Z1J81; ;VH!s`V5U?iAl)owoRc#UC2(~[x*Eoq|5vghwtbvq&lV?w nQv?s#&q6~d}@wM","O}r+9|M9u}x;VIn;Zmw{*Fj-CV,yaGa%Yg9-H|n=Saipfti4O(,n^#RLfhAE=%At[bRzNm$hIPQf=Vi }#kk8U7"] codec = Codec() print codec.decode(codec.encode(strings))
class Solution(object): def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ n = len(nums) k %= n self.reverse(0, n-1, nums) self.reverse(0, k-1, nums) self.reverse(k, n-1, nums) def reverse(self, start, end, nums): left, right = start, end while left < right: nums[left] = nums[left] ^ nums[right] nums[right] = nums[left] ^ nums[right] nums[left] = nums[left] ^ nums[right] left += 1 right -= 1
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return [] carry = self.checkCarry(head) if carry == 1: nh = ListNode(carry) nh.next = head return nh else: return head def checkCarry(self, head): if not head.next: ret = (head.val + 1) / 10 head.val = (head.val + 1) % 10 return ret else: carry = self.checkCarry(head.next) ret = (head.val + carry) / 10 head.val = (head.val + carry) % 10 return ret
class Solution(object): def threeSumSmaller(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ count = 0 nums.sort() for i in range(len(nums)): left, right, t = i + 1, len(nums) - 1, target - nums[i] while left < right: if nums[left] + nums[right] >= t: right -= 1 else: count += (right - left) left += 1 return count
class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ self.dic = dict() for w in dictionary: if len(w) >= 3: tmp = w[0] + str(len(w[1:-1])) + w[-1] if self.dic.has_key(tmp) and self.dic[tmp] != w: self.dic[tmp] = False else: self.dic[tmp] = w def isUnique(self, word): """ check if a word is unique. :type word: str :rtype: bool """ n = len(word) if n < 3: return True tmp = word[0] + str(len(word[1:-1])) + word[-1] print tmp if not self.dic.has_key(tmp): return True elif self.dic[tmp] == word: return True else: return False # Your ValidWordAbbr object will be instantiated and called as such: vwa = ValidWordAbbr(["hello", "heloo"]) print vwa.isUnique("heloo")
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ret = [] if not root: return ret queue = [(root, 0)] while len(queue): cur, level = queue.pop(0) if len(ret) <= level: ret.append([cur.val]) else: ret[level].append(cur.val) if cur.left: queue.append((cur.left, level+1)) if cur.right: queue.append((cur.right, level+1)) for i in xrange(1, len(ret),2): ret[i].reverse() return ret
class WordDistance(object): def __init__(self, words): """ initialize your data structure here. :type words: List[str] """ self.dic = dict() l = len(words) self.max = l for i in xrange(l): word = words[i] if word in self.dic: self.dic[word].append(i) else: self.dic[word] = [i] def shortest(self, word1, word2): """ Adds a word into the data structure. :type word1: str :type word2: str :rtype: int """ l1, l2 = self.dic[word1], self.dic[word2] n1, n2 = len(l1), len(l2) p1, p2 = 0, 0 ret = self.max while p1 < n1 and p2 < n2: i1, i2 = l1[p1], l2[p2] if i1 < i2: ret = min(i2-i1, ret) p1 += 1 else: ret = min(i1-i2, ret) p2 += 1 return ret # Your WordDistance object will be instantiated and called as such: # wordDistance = WordDistance(words) # wordDistance.shortest("word1", "word2") # wordDistance.shortest("anotherWord1", "anotherWord2")
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def longestConsecutive(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 self.longest = 1 self.rec(root) return self.longest def rec(self, root): inc, dec = 1, 1 if not root.left and not root.right: return (inc, dec) if root.left: sub_res = self.rec(root.left) if root.left.val == root.val - 1: dec = max(dec, 1 + sub_res[1]) elif root.left.val == root.val + 1: inc = max(inc, 1 + sub_res[0]) if root.right: sub_res = self.rec(root.right) if root.right.val == root.val - 1: dec = max(dec, 1 + sub_res[1]) elif root.right.val == root.val + 1: inc = max(inc, 1 + sub_res[0]) self.longest = max(self.longest, inc + dec - 1) return (inc, dec)
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 2: return nums[0] nums.sort() print left, right = 0, len(nums) - 1 while left < right: if left == right - 1: return nums[left] middle = left + (right - left) / 2 if nums[middle] <= middle: right = middle else: left = middle
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return "#" res = [] queue = [root] while len(queue) > 0: cur = queue.pop(0) if cur: res.append(str(cur.val)) queue.append(cur.left) queue.append(cur.right) else: res.append('#') for i in xrange(len(res)-1, -1, -1): if res[i] == "#" or res[i] == ',': res.pop() else: break return ','.join(res) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ data += "," root = None start = 0 l = len(data) res = [] last = None flag = True count = 0 for i in xrange(l): if data[i] == ',': cur = data[start:i] start = i + 1 if cur == '#': node = None else: node = TreeNode(int(cur)) if flag: root = node last = 0 res.append(node) flag = False else: res.append(node) if count == 0: res[last].left = node count += 1 else: res[last].right = node count = 0 last += 1 while last < len(res) and res[last] is None: last += 1 return root # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] ret = [] front = [root] while len(front) > 0: next_front = [] for node in front: if node.left: next_front.append(node.left) if node.right: next_front.append(node.right) ret.append(node.val) front = next_front return ret
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head or not head.next or not head.next.next: return p1 = p2 = head while p1 and p1.next: p1 = p1.next.next p2 = p2.next last = next = None while p2.next: next = p2.next p2.next = last if last else None last = p2 p2 = next p2.next = last p1 = head while p1.next and p2.next: next = p2.next p2.next = p1.next p1.next = p2 p1 = p2.next p2 = next
#Python program to solve the leetcode count-and-say sequence problem # Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. # You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit. #Function to solve the problem def countAndSay(n): """ :type n: int :rtype: str """ # base case if n == 1: return '1' par = countAndSay(n-1) ans = '' ii = 0 # print(par) while ii<len(par): jj = ii print(ii) while jj < len(par) and par[jj] == par[ii]: jj += 1 ans += str(len(par[ii:jj])) + str(par[ii]) ii = jj return ans #main function to run the program def main(): test_number_1 = 1 test_number_2 = 2 test_number_3 = 3 test_number_4 = 4 test_number_5 = 5 test_number_6 = 6 # print(countAndSay(test_number_1)) print(countAndSay(test_number_2)) # print(countAndSay(test_number_3)) # print(countAndSay(test_number_4)) print(countAndSay(test_number_5)) # print(countAndSay(test_number_6)) main()
#!/usr/bin/python # -*- coding: utf-8 -*- from random import * from statistics import * from collections import * def roulette_wheel_bad(): '''using choice() return: list: ['black', 'black', 'black', 'red', 'red', 'red'] counter = Counter({'black': 3, 'red': 3}) ''' population = ['red'] * 18 + ['black'] * 18 + ['green'] * 2 l1 = [choice(population) for i in range(6)] c1 = Counter(l1) '''using choices() return: same as choice() but easier''' l2 = choices(population, k=6) c2 = Counter(l2) def roulette_wheel_good(): '''using choices() with weight''' c = Counter(choices(['red', 'black', 'green'], [18, 18, 2], k=6)) print(c) def deal_card(): '''Deal 20 playing cards without replacement technique: counter, elements, sample, list.count ''' deck = Counter(tens=16, low=36) deck = list(deck.elements()) #change element to a list of integer deal = sample(deck, 20) # randomly select 20 element from an array c = Counter(deal) def bias_coin(): '''5 or more heads from 7 spins of a biased coin technique: lambda, choies, list.count ''' population = ['heads', 'tails'] cumwgt = [0.60 , 1.00] #bias by 60% trial = lambda : choices(population, cumwgt, k=7).count('heads') >= 5 n = 100000 print(sum(trial() for i in range(n))/n) if __name__ == '__main__': # roulette_wheel_good() # deal_card() bias_coin()
# array can also be used in this way but data type is not defined X = [5, 6, 8, 10, -11] n = len(X) for i in range(n): print(X[i], end=' ')
width = input("Podaj dł. podstawy: ") height = input("Podaj dł. wysokości: ") triangle_area = (width * height) / 2 print("Pole trójkąta wynosi {triangle_area} cm^2") print(f"Pole trójkąta wynosi {triangle_area} cm^2") print("Pole trójkąta wynosi", triangle_area, "cm^2")
birth = int(input("Podaj rok urodzenia: ")) age = 2021 - birth if age % 2 == 0: print("Twój wiek jest parzysty.") else: print("twój wiek jest nieparzysty.") if age > 60: print("Możesz się szczepić Pfizerem.") elif age > 70: print("Astra jest dla ciebie") elif age > 18: print("W ogóle to Sputnik 8") else: print(f"Jeszcze {18-age} lat do szczepienia") print(f"Masz {age} lat.")
import time import math import matplotlib as plt import numpy as np # Starting function for script. # Prints options for user input and runs another option. # Returns result to caller. def start(): print("Which formula would you like to use? ") print("1. Quadratic") print("2. Direct Proportions") print("3. Midpoint of coordinates") print("4. Distance") print("5. Derviatives") print("0. Quit") menuChoiceAns = int(input(" ")) return menuChoiceAns # quadratic function. # collects user input for values a,b and c # prints vertex of quadratic # prints x-intercepts of equation def quadratic(): a = int(input("Input ax^2+bx+c=0 of a: ")) b = int(input("Input ax^2+bx+c=0 of b: ")) c = int(input("Input ax^2+bx+c=0 of c: ")) now = time.time() x1 = (-b + math.sqrt(b ** 2 - 4 * a * c))/(2 * a) x2 = (-b - math.sqrt(b ** 2 - 4 * a * c))/(2 * a) print("x1 = " + str(x1) + " x2 = " + str(x2)) print("Seconds: " + str(time.time() - now)) # asks user for vertex point of parabola responseVertex = input("Would you like the vertex coordinates? (type yes or no)") if responseVertex == "yes" : h = -b/(2 * a) k = c print("vertex (h,k)/(x,y) = (" + str(h) + "," + str(k) + ")") # asks user for graph of equation inputed to be drawn responseGraph = input("Would you like a graph of it? (type yes or no)") if responseGraph == "yes" : x = np.arange(x2 - 10,x1 + 10,0.1) plt.plot (x, a * x ** 2 + b * x + c) plt.show() # direct proportions function def directproportions(): x = int(input("Input value of x (smaller number): ")) y = int(input("Input value of y (larger number): ")) now = time.time() k = y/x print("The proportionality constant is (value of k): " + str(k)) print("Seconds: " + str(time.time() - now)) # midpoint formula function def midpoint(): x1 = int(input("value of x1: ")) x2 = int(input("value of x2: ")) y1 = int(input("value of y1: ")) y2 = int(input("value of y2: ")) now = time.time() x = (x1 + x2)/2 y = (y1 + y2)/2 print("Midpoint coordinates are (x,y): (" + str(x) + "," + str(y) + ")") print("Seconds: " + str(time.time() - now)) # distance equation function def distance(): x1 = int(input("value of x1: ")) x2 = int(input("value of x2: ")) y1 = int(input("value of y1: ")) y2 = int(input("value of y2: ")) now = time.time() d = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) print("The distance is: " + str(d)) print("Seconds: " + str(time.time() - now)) #function for finding derviatives def derivatives(): dervivativeAns == -1 print("What kinda of function do you have?") print("1. ax^n") print("0. Quit") dervivativeAns = int(input("")) if dervivativeAns == 1 : derivativesAxn() #calculates derviative of a parabola def derivativesAxn(): x = int(input("value of x (the point you want the gradient)")) n = int(input("value of n (what power x is raised to)")) a = int(input("value of a (coefficent of x)")) now = time.time() d = n * a * x ** (n-1) print("the gradient of that point is " + str(d)) print("Seconds: " + str(time.time() - now)) #calculates inverse of a function that was derived from function nax^n-1 def inverseDerivativesAxn(): x = int(input("value of x (the point on the function)")) n = int(input("value of n (what power x is raised to)")) a = int(input("value of a (coefficent of x)")) iD = (a / (n+1)) * x ** (n+1) # while loop allowing user to use different formulas in one session menuChoiceAns = -1 while menuChoiceAns != 0 : menuChoiceAns = start() if menuChoiceAns == 1 : quadratic() elif menuChoiceAns == 2 : directproportions() elif menuChoiceAns == 3 : midpoint() elif menuChoiceAns == 4 : distance() elif menuChoiceAns == 5: derivatives() if menuChoiceAns != 0 : input("enter to continue")
# Clase de ejercicio 0003 import json from pprint import pprint class Ejercicio0003: """Esta es la clase del ejercicio 3""" def __init__(self, archivo): with open(archivo) as data_file: data = json.load(data_file) self.numeroevaluar = data['numeroevaluar'] self.resto = self.numeroevaluar self.listaprimos = [] self.divisores = [] def esPrimo(sefl, numero): for valor in range(2, numero): if numero % valor == 0: return False return True def buscaFactores(self, salida): while self.resto != 1: primomaximo = 1 for valor in self.listaprimos: if primomaximo < valor: primomaximo = valor if self.resto % valor == 0: self.divisores.append(valor) self.resto = self.resto / valor salir = False while not salir: primomaximo += 1 if self.esPrimo(primomaximo): self.listaprimos.append(primomaximo) if self.resto % primomaximo == 0: self.divisores.append(primomaximo) self.resto = self.resto / primomaximo salir = True data = {"Factores": self.divisores} with open(salida, 'w') as outfile: json.dump(data, outfile) return self.divisores def determinaMayor(seft, arreglo): mayor = 0 for valor in arreglo: if valor > mayor: mayor = valor return mayor clase = Ejercicio0003('./data.json') arreglo = clase.buscaFactores('./resultado.json') valor = clase.determinaMayor(arreglo) print("Los fatores son: " + str(arreglo)) print("El mayor factor es: " + str(format(valor, ',d')))
def solution(xs): ''' Finds the maximum product of a non empty subset of the array xs Args: a list of integers with 1 to 50 elements whose absolute values are no greater than 1000. Returns: the maximum product as a string ''' def remove_zeros_from_list(xs): return [i for i in xs if i != 0] def product(l): t = 1 for x in l: t = t * x return t # set the intial max product as the product of the entire array prod = product(xs) # create a list of all the negative numbers neg_nums = [i for i in xs if i < 0] # if there is an odd number of negative numbers, drop the negative number with the smallest absolute value from the array if len(neg_nums) > 0 and len(neg_nums) % 2 == 1: xs.remove(min(neg_nums, key=abs)) # remove all 0s from the array xs = remove_zeros_from_list(xs) # After dropping the 0s if the list is non empty update the maximum product if len(xs) > 0: prod = product(xs) return str(prod)
"""" 题号 127 单词接龙 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回 0。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。 示例 1: 输入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 输出: 5 解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的长度 5。 示例 2: 输入: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] 输出: 0 解释: endWord "cog" 不在字典中,所以无法进行转换。 参考:https://leetcode-cn.com/problems/word-ladder/solution/bfscong-wu-dao-you-by-powcai/ """ from typing import List class Solution: # BFS解法 def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: from collections import deque wordList = set(wordList) if endWord not in wordList: return 0 visited = set() # 看两个单词是否差一个字母 def is_one_letter(w, word): if len(w) != len(word): return False dif = 0 for i in range(len(w)): if w[i] != word[i]: dif += 1 if dif > 1: return False return True # 发现所有和word相差一个字母的单词 def find_only_one_letter(word): ans = [] for w in wordList: # print(is_one_letter(w, word)) if w not in visited and is_one_letter(w, word): ans.append(w) # print(ans) return ans queue = deque() queue.appendleft(beginWord) res = 1 # BFS while queue: n = len(queue) for _ in range(n): tmp = queue.pop() if tmp == endWord: return res visited.add(tmp) for t in find_only_one_letter(tmp): queue.appendleft(t) res += 1 return 0 def ladderLength2(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if endWord not in wordList: return 0 wordict = set(wordList) s1 = {beginWord} s2 = {endWord} n = len(beginWord) step = 0 wordict.remove(endWord) while s1 and s2: step += 1 if len(s1) > len(s2): s1, s2 = s2, s1 s = set() for word in s1: nextword = [word[:i] + chr(j) + word[i + 1:] for j in range(97, 123) for i in range(n)] for w in nextword: if w in s2: return step + 1 if w not in wordict: continue wordict.remove(w) s.add(w) s1 = s return 0 if __name__ == '__main__': beginWord = "hit" endWord = "cog" wordList = ["hot", "dot", "dog", "lot", "log", "cog"] solution = Solution() print(solution.ladderLength(beginWord,endWord,wordList))
#compreensao de listas x = [1,2,3,4,5] y = [] #metodo basico for i in x: y.append(i**2) print(x) print(y) print("Ideal") z = [i**2 for i in x] print(z) a = [i for i in x if i%2==1] print(a)
nota1 = int(input("Digite a nota 1: ")) nota2 = int(input("Digite a nota 2: ")) if nota1 and nota2 >= 6: print("Aprovados") else: print("reprovado")
#grafico de dispersao import matplotlib.pyplot as plt x = [1,3,5,7,9] y = [2,3,7,1,0] titulo = "scatterplot: grafico de dispersao" eixox = "Eixo X" eixoy = "Eixo Y" plt.title(titulo) plt.xlabel(eixox) plt.ylabel(eixoy) plt.scatter(x, y, label="Meus pontos", color="r",marker = ".", s = 200) plt.plot(x, y, color ="k", linestyle=":") plt.legend() plt.show()
#visualizacao de um grafico simples import matplotlib.pyplot as plt x = [1,2,5] y = [2,3,7] #titulo plt.title("Grafico simples em python") #eixos plt.xlabel("Eixo X") plt.ylabel("Eixo Y") plt.plot(x, y) plt.show()
# 列表去重 def get_unique_list(origin_list): result = [] for item in origin_list: if item not in result: result.append(item) return result origin_list = [10, 20, 30, 10, 20] print( f"origin_list: {origin_list}, unique_list: {get_unique_list(origin_list)}") # 利用 set print( f"origin_list: {origin_list}, unique_list: {list(set(origin_list))}")
# 复杂列表排序 students = [ {"sno": 101, "sname": "小赵", "sgrade": 88}, {"sno": 104, "sname": "小钱", "sgrade": 77}, {"sno": 102, "sname": "小孙", "sgrade": 99}, {"sno": 103, "sname": "小李", "sgrade": 66}, ] result = sorted(students, key=lambda x: x["sgrade"], reverse=False) print(f"students: {students}") print(f"students: {result}")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Module of tasks Hackerrank # Copyright (C) 2021 # Salavat Bibarsov <Bibarsov.Salavat@gmail.com> # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # https://www.hackerrank.com/challenges/whats-your-name/problem """ Task You are given the firstname and lastname of a person on two different lines. Your task is to read them and print the following: Hello firstname lastname! You just delved into python. """ def print_full_name(first, last): print(f"Hello {first} {last}! You just delved into python.") if __name__ == '__main__': first_name = input() last_name = input() print_full_name(first_name, last_name)
#!/bin/python3 # Day 4: Class vs. Instance # https://www.hackerrank.com/challenges/30-class-vs-instance/problem """ Objective In this challenge, we're going to learn about the difference between a class and an instance; because this is an Object Oriented concept, it's only enabled in certain languages. Check out the Tutorial tab for learning materials and an instructional video! Task Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print "Age is not valid, setting age to 0.". In addition, you must write the following instance methods: 1. yearPasses() should increase the age instance variable by 1. 2. amIOld() should perform the following conditional actions: - If age < 13, print "You are young.". - If age >= 13 and age < 18, print "You are a teenager.". - Otherwise, print "You are old.". To help you learn by example and complete this challenge, much of the code is provided for you, but you'll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don't worry if you don't understand it all quite yet! Note: Do not remove or alter the stub code in the editor. Input Format Input is handled for you by the stub code in the editor. The first line contains an integer, T (the number of test cases), and the T subsequent lines each contain an integer denoting the age of a Person instance. Constraints 1 <= T <= 4; -5 <= age <= 30; Output Format Complete the method definitions provided in the editor so they meet the specifications outlined above; the code to test your work is already in the editor. If your methods are implemented correctly, each test case will print 2 or 3 lines (depending on whether or not a valid initialAge was passed to the constructor). Sample Input >>> 4 >>> -1 >>> 10 >>> 16 >>> 18 Sample Output <<< Age is not valid, setting age to 0. <<< You are young. <<< You are young. <<< You are young. <<< You are a teenager. <<< You are a teenager. <<< You are old. <<< You are old. <<< You are old. The extra line at the end of the output is supposed to be there and is trimmed before being compared against the test case's expected output. If you're failing this challenge, check your logic and review your print statements for spelling errors. """ class Person: def __init__(self, initialAge: int) -> None: # Add some more code to run some checks on initialAge if initialAge >= 0 : self.age = initialAge else: print("Age is not valid, setting age to 0.") self.age = 0 def amIOld(self) -> None: # Do some computations in here and print out the correct statement to the console if self.age < 13: print("You are young.") elif self.age < 18: print("You are a teenager.") else: print("You are old.") def yearPasses(self) -> None: # Increment the age of the person in here self.age += 1 t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("")
# -*- coding: utf-8 -*- """ Created on Fri Oct 15 12:59:50 2021 @author: Robert Morton """ from enum import Enum class CoordPair: """ A single coordinate pair. """ def __init__(self, x, y): self.x = x self.y = y self._hash = x<<16 ^ y def __eq__(self, other): if not isinstance(other, CoordPair): return False return self.x == other.x and self.y == other.y def __neq__(self, other): return not(self == other) def __hash__(self): return self._hash def __str__(self): return '({}, {})'.format(self.x, self.y) __repr__ = __str__ class Direction(Enum): RIGHT='RIGHT', UP='UP', LEFT='LEFT', DOWN='DOWN' OPPOSITES = {Direction.RIGHT: Direction.LEFT, Direction.LEFT: Direction.RIGHT, Direction.UP: Direction.DOWN, Direction.DOWN: Direction.UP} class Tile: """ A tile. """ def __init__(self, right, up, left, down): self.sections = {Direction.RIGHT: right, Direction.UP: up, Direction.LEFT: left, Direction.DOWN: down} # self._hash = 17 # self._hash = (self._hash + hash(right)) * 31 # self._hash = (self._hash + hash(up)) * 31 # self._hash = (self._hash + hash(left)) * 31 # self._hash = (self._hash + hash(down)) * 31 def __eq__(self, other): if not isinstance(other, Tile): return False for direction in Direction: if self.sections[direction] != other.sections[direction]: return False return True def __neq__(self, other): return not(self == other) def __hash__(self): _hash = 17 _hash = (_hash + hash(self.sections[Direction.RIGHT])) * 31 _hash = (_hash + hash(self.sections[Direction.UP])) * 31 _hash = (_hash + hash(self.sections[Direction.LEFT])) * 31 _hash = (_hash + hash(self.sections[Direction.DOWN])) * 31 return _hash def __str__(self): return '({} {} {} {})'\ .format(self.sections[Direction.RIGHT], self.sections[Direction.UP], self.sections[Direction.LEFT], self.sections[Direction.DOWN]) __repr__ = __str__ def rotated(self, rotation): """ Return this tile, rotated 90 degrees counterclockwise rotation times. """ rotation = rotation % 4 sections = [self.sections[Direction.RIGHT], self.sections[Direction.UP], self.sections[Direction.LEFT], self.sections[Direction.DOWN]] sections = sections[-rotation:] + sections[:-rotation] return Tile(*sections) def matches(self, other, side): """ Return whether the side of this tile indicate by side matches the opposite side of the other tile. """ return self.sections[side] == other.sections[OPPOSITES[side]] def copy(self): return Tile(self.sections[Direction.RIGHT], self.sections[Direction.UP], self.sections[Direction.LEFT], self.sections[Direction.DOWN]) ADJ_DISPS = {Direction.RIGHT: CoordPair( 1, 0), Direction.UP: CoordPair( 0, -1), Direction.LEFT: CoordPair(-1, 0), Direction.DOWN: CoordPair( 0, 1)} #Displacement functions def boundless_disp(coords, disp): """ The displacement for a bound unbounded in both directions. """ return CoordPair(coords.x + disp.x, coords.y + disp.y) def torus_disp(coords, disp, width, height): """ The displacement for a toroidal board. """ unwrapped = boundless_disp(coords, disp) return CoordPair(unwrapped.x % width, unwrapped.y % height) def get_torus_disp(width, height): #You can't have a width or a height of one #tiles being adjacent to themselves isn't supported if width <= 1: raise ValueError('width: {}'.format(width)) if height <= 1: raise ValueError('width: {}'.format(height)) return lambda coords, disp: torus_disp(coords, disp, width, height) class TileMap: """ A map of tiles. """ def __init__(self, disp_function): self.tiles = dict() self.disp_function = disp_function def in_direction(self, coords, direction): c_disp = ADJ_DISPS[direction] return self.disp_function(coords, c_disp) def fits(self, coords, tile): #For all the adjacent tiles, check whether this tile matches for direction in ADJ_DISPS: #Get the coordinates in this direction other_coords = self.in_direction(coords, direction) #If there are no coords in that direction, continue if other_coords is None: continue if not other_coords in self.tiles: continue other_tile = self.tiles[other_coords] #It doesn't match if not tile.matches(other_tile, direction): return False return True def add_tile(self, coords, tile): if coords in self.tiles: raise ValueError('coords in self.tiles: {}'.format(coords)) if not self.fits(coords, tile): raise ValueError('tile doesn\'t fit: {}, {}'.format(coords, tile)) self.tiles[coords] = tile def at(self, coords): return self.tiles[coords]
class Car(object): def __init__(self, color, make, speed_limit): self.color = color self.make = make self.speed_limit = speed_limit def accelerate(self, speed): if speed <= self.speed_limit: return "now driving at " + str(speed) + " MPH" else: return "that is too fast for me!" def park(self, parking_spot_type): if parking_spot_type == "parallel": return "parallel parking...good luck!" else: return "parking car!" class Tesla(Car): def __init__(self, color, make, speed_limit, battery_level): super().__init__(color, make, speed_limit) self.battery_level = battery_level my_car = Car("blue", "VW", 120) print(my_car.color) # print(my_car.battery_level) your_car = Tesla("black", "Tesla", 160, 100) print(your_car.color) print(your_car.battery_level) print(my_car.accelerate(140)) print(your_car.accelerate(140))
from Person import Person class Student(Person): def __init__(self, name, age, year): super().__init__(name, age) self.year = year self.courses = [] def introduce_self(self): """This method prints out the name and age attributes""" print( f"My name is {self._name} and my age is {self._age}. I am a {self.year}") def get_courses(self): print(f"{self._name} is taking CS1.1, Web1.1, SPD1.2, and S&L")
from random import randint import copy import string import queue class Map(): """ The map search(self); searchit(self, x, y, next); searchback(self); findback(self, x, y) are used for the finding show(self) print actuall state of map sector(self, x, y) does nothing, yet """ def __init__(self, y, x): self.x, self.y = x, y self.pole = [] for i in range(y): self.pole.append([]) self.pole[i].extend([" "]*x) self.done, self.znaky = False, ["A"] self.q = queue.Queue() self.index = 0 def show(self, X = False):## if X: ## pole = copy.copy(self.cpole) else: pole = copy.copy(self.pole) for i in range(len(pole)): pole[i] = "".join(pole[i]) print("\n".join(pole)) print("v"*self.x) def search(self): while not self.done: if not self.q.empty(): me, x, y = self.q.get() poss = [[x, y - 1], [x + 1, y], [x, y + 1], [x - 1, y]] for pos in poss: self.searchit(pos[0], pos[1], me + 1) else: break def searchit(self, x, y, next): place = self.pole[y][x] if place == " ": self.pole[y][x] = self.znaky[next] self.q.put((next, x, y)) elif place == "B": self.done = True self.destin, self.destx, self.desty = next, x, y def searchback(self): for i in range(self.destin - 1): for e in [[self.destx, self.desty - 1], [self.destx + 1, self.desty], [self.destx, self.desty + 1], [self.destx - 1, self.desty]]: self.findback(e[0], e[1]) return self.destx, self.desty def findback(self, x, y): place = self.pole[y][x] if place == self.znaky[self.destin - 1]: self.pole[y][x] = "X" self.cpole[y][x] = "X" ## self.destin, self.destx, self.desty = self.destin - 1, x, y def addthing(self, obj): self.cpole = obj def into_sector(self, x, y): pass def sector(self, x, y): pass #divide map into sectors 'big tiles' for easier searching #it will have it's own map (n times smaller that the original one) #in this map it will search like in normal one #so way from A to B is thrue your tile to sector tile wich leads to other sector tile that in the end leads to final sector #sector will have entrace for example: # 111111 111111 # 1....1 1....1 # 1....1 1....1 # 1....1 1...@@ # 1....1 1..@.2 # 111111 111@22 #which could change into # 1 1 # 1.1 1.12 # 1 12 #patcs? mapa = Map(79, 77) #kameny a body #kameny = randint(int(mapa.x*mapa.y/20), int(mapa.x*mapa.y/2)) #for i in range(kameny): # mapa.pole[randint(0, mapa.y-1)][randint(0, mapa.x-1)] = "@" mapa.pole.append(["@"]*mapa.x) mapa.pole.insert(0, ["@"]*mapa.x) mapa.x, mapa.y = mapa.x + 2, mapa.y + 2 for i in range(mapa.y): mapa.pole[i].append("@") mapa.pole[i].insert(0, "@") c, d = randint(1, mapa.y-2), randint(1, mapa.x-2) mapa.pole[c][d] = "A" mapa.q.put((0, d, c)) print(d, c) while True: a, b = randint(1, mapa.y-2), randint(1, mapa.x-2) if mapa.pole[a][b] != "A": mapa.pole[a][b] = "B" break mapa.addthing(copy.deepcopy(mapa.pole)) #znaky k hledání mapa.znaky.extend(list(string.ascii_lowercase)) for i in range(mapa.x*mapa.y): mapa.znaky.append(str(i)) #samotné spuštění mapa.show() mapa.search() mapa.show() if mapa.done: print(mapa.searchback()) else: print("Runrand") mapa.show(X = True) print(mapa.destx, mapa.desty) input()
a=[0] b=a[:] b[0]+=1 print(a) print(b) print() x=[0] y=x y[0]+=1 print(x) print(y)
def ctverec(velky,maly): x,y=[0]*2 if velky < 3: x+=3*velky elif velky < 6: x+=3*(velky-3) y+=3 else: x+=3*(velky-6) y+=6 if maly < 3: x+=maly elif maly < 6: x+=maly-3 y+=1 else: x+=maly-6 y+=2 return x,y def zobrazit(vse): for sudoku in vse: for i in [sudoku]: zobrazitL=[] for i2 in range(9): zobrazitL.append("".join(i[i2])) zobrazitL="\n".join(zobrazitL) print(zobrazitL,end="\n\n") def resitel(sudoku): Mlinie=[[str(x+1) for x in range(9)] for i in range(9)] Mctverec=[[str(x+1) for x in range(9)] for i in range(9)] Msloup=[[str(x+1) for x in range(9)] for i in range(9)] Mvsechny=[] for i in range(9): a=[] for i2 in range(9): a.append([]) Mvsechny.append(a) for i in range(9): for i2 in range(9): if sudoku[i][i2] in Mlinie[i]: del Mlinie[i][Mlinie[i].index(sudoku[i][i2])] for i in range(9): for i2 in range(9): if sudoku[i2][i] in Msloup[i]: del Msloup[i][Msloup[i].index(sudoku[i2][i])] for i in range(9): for i2 in range(9): x,y=ctverec(i,i2) if sudoku[y][x] in Mctverec[i]: del Mctverec[i][Mctverec[i].index(sudoku[y][x])] for i in range(9): for i2 in range(len(Mlinie[i])): for i3 in range(9): if sudoku[i][i3]=="#": if Mlinie[i][i2] in Msloup[i3]: x,y=ctverec(i,i3) if Mlinie[i][i2] in Mctverec[y]: Mvsechny[i][i3].append(Mlinie[i][i2]) for i in range(9): for i2 in range(9): if sudoku[i][i2]=="#" and len(Mvsechny[i][i2])==0: return(["nic"]) for i in range(9): for i2 in range(9): if len(Mvsechny[i][i2])==1: sudoku[i][i2]=Mvsechny[i][i2][0] return([sudoku]) elif len(Mvsechny[i][i2])>1: more=[] for i3 in range(len(Mvsechny[i][i2])): sudoku[i][i2]=Mvsechny[i][i2][i3] more.append([[], [], [], [], [], [], [], [], []]) for i4 in range(9): more[i3][i4].extend(sudoku[i4]) return(more) return([sudoku])
from socket import * import threading import argparse def scan_TCP_port(ip, port): sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(0.5) try: sock.connect((ip, port)) print(f"TCP Port: {port} Open") except: print(f"TCP Port: {port} CLOSED") def scan_UDP_port(ip, port): try: connect_sock = socket(AF_INET, SOCK_STREAM) connect_sock.connect((ip, port)) print(f"UDP Port: {port} Open") except: print(f"UDP Port: {port} CLOSED") def check(ip, ports, is_udp): for port in ports: if not is_udp: thread = threading.Thread(target=scan_TCP_port, args=(ip, int(port))) else: thread = threading.Thread(target=scan_UDP_port, args=(ip, int(port))) thread.start() def main(): print("Welcome To Port Scanner!\n") try: parser = argparse.ArgumentParser("Ports Scanner") parser.add_argument("-a", "--address", type=str, help="Enter the ip address to scan") parser.add_argument("-p", "--port", type=str, help="Enter The ports to scan") parser.add_argument("-u", "--udp", action="store_true") args = parser.parse_args() ip = args.address port = args.port.split(',') is_udp = args.udp check(ip, port, is_udp) except: print("format error\n example: python scan.py -a 127.0.0.1 -p 21,22,80") if __name__ == "__main__": main()
def can_make_note(note, mag): note = list(note.replace(" ", "")) mag = list(mag.replace(" ", "")) for c in note: if c in mag: mag.remove(c) else: return False return True def main(): note = "He old" mag = "Hllo World" print(str(can_make_note(note, mag))) if __name__ == "__main__": main()
# -*- coding: UTF-8 -*- import geopandas as gpd from shapely.geometry import Point, Polygon shapefile = '/home/tudor/Documents/GitHub/building_resilience/models/top_to_bottom/resources/data_resources/shapes/ne_110m_admin_0_countries.shp' #Read shapefile using Geopandas gdf = gpd.read_file(shapefile)[['ADMIN', 'ADM0_A3', 'geometry']] #Rename columns. gdf.columns = ['country', 'country_code', 'geometry'] polygons = list(gdf['geometry']) countries = gdf['country_code'].values def get_polygon_index(point, polygons=polygons): for i, polygon in enumerate(polygons): if Point(point).within(polygon): return i return None def whichCountry(point, polygons=polygons): ''' Finding the country from coordinates Parameters: ---------- coords (tuple): (latitude,longitude) Returns: -------- UN_code (string): Three letter UN country code ''' point = (point[1],point[0]) # the function is actually asking for (lon,lat) if (point[0] >= 180): point = (-(360 - point[0]), point[1]) i = get_polygon_index(point, polygons) if i == None: return None else: return countries[i]
from tkinter import ttk from tkinter import * class Desk: def _init_(self, window): # Initializations #ancho ancho = 800 #alto alto = 600 # asignamos la ventana a una variable de la clase llamada wind self.wind = window #le asignamos el ancho y el alto a la ventana con la propiedad geometry self.wind.geometry(str(ancho)+'x'+str(alto)) #centramos el contenido self.wind.columnconfigure(0, weight=1) #le damos un titulo a la ventana self.wind.title('Aplicación con interface gráfica en Python - By Ing. Gerson Altamirano') # creamos un contenedor frame = LabelFrame(self.wind, text = 'Examen') frame.grid(row = 0, column = 0, columnspan = 3, pady = 20) # creamos un etiqueta Label(frame, text = 'valor1: ').grid(row = 1, column = 0) #creamos un input donde ingresar valores self.var1 = Entry(frame) self.var1.focus() self.var1.grid(row = 1, column = 1) # igual que arriba una etiqueta y un campo input para ingresar valores Label(frame, text = 'valor 2: ').grid(row = 2, column = 0) self.var2 = Entry(frame) self.var2.grid(row = 2, column = 1) Label(frame, text = 'valor 3: ').grid(row = 3, column = 0) self.var3 = Entry(frame) self.var3.grid(row = 2, column = 1) #Creamos un boton para ejecutar la suma Button(frame, text = 'Button1', command = self.operacion).grid(row = 3, columnspan =2, sticky = W + E) #designamos un área para mensajes self.message = Label(text = '', fg = 'red') self.message.grid(row = 3, column = 0, columnspan = 2, sticky = W + E) # creamos una función para validar que los campos no esten en blanco def validation(self): return len(self.var1.get()) != 0 and len(self.var2.get()) != 0 # esta es la función que ejecuta la suma def operacion(self): if self.validation(): if(self.var1 > self.var3): multi = int(self.var1) * int(self.var2) * int(self.var1) self.message['text'] = 'El var 1 es mayor al valor3 el resultado de multiplicacion de los tres valores es: {}'.format(multi) if(self.var1 == self.var3 and self.var2 == self.var3 ): suma = int(self.var1) + int(self.var2) + int(self.var1) self.message['text'] = 'Todos los valores son iguales la operacion es una suma que es: {}'.format(suma) if(self.var2 == 0 ): if(self.var1 < self.var3): resta = int(self.var3) - int(self.var1) self.message['text'] = 'el valor2 es o se restara el menor al mayor que es: {}'.format(resta) else: resta = int(self.var1) - int(self.var2) self.message['text'] = 'el valor2 es o se restara el menor al mayor que es: {}'.format(resta) else: self.message['text'] = 'los campos son requeridos' #validamos si estamos en la aplicación inicial if _name_ == '_main_': #asignamos la propiedad de tkinter a la variable window window = Tk() #en la variable app guardamos la clase Desk y le enviamos como parametro la ventana app = Desk(window) #ejecutamos un mainloop para que se ejecute la ventana window.mainloop()
#!/usr/bin/python2.7 #pokerdice.py import random from itertools import groupby nine = 1 ten = 2 jack = 3 queen = 4 king = 5 ace = 6 names = { nine: "9", ten: "10", jack: "J", queen : "Q", king = "K", ace = "A" } player_score = 0 computer_score = 0 def start(): print "Let's play a game of Poker Dice." while game(): pass scores() def game(): print "The computer will help you throw your five dice." throws() return play_again() def throws(): roll_number = 5 dice = roll(roll_number) dice.sort() for i in range(len(dice)): print "Dice ", i + 1, ": ", names[dice[i]] result = hand(dice) print "You currently have", result while True: rerolls = raw_input("How many dice do you want to throw again?") try: if rerolls in (1, 2, 3, 4, 5): break except ValueError: pass print "That wasn't a valid answer. Please enter 1, 2, 3, 4 or 5." if rerolls == 0: print "You finish with ", result else: roll_number = rerolls dice_rerolls = roll(roll_number) dice_changes = range(rerolls) print "Enter the number of a dice to reroll: " iterations = 0 while iterations < rerolls: iterations += 1 while True: selection = raw_input("") try: if selection in (1, 2, 3, 4, 5): break except ValueError: pass print "That wasn't a valid answer. Please enter 1, 2, 3, 4 or 5." dice_changes[iterations-1] = selection-1 print "You have changed dice ", selection iterations = 0 while iterations < rerolls: iterations += 1 replacement = dice
n1,n2,n3=int(input('Enter your first number')),int(input('Enter your second number')),int(input('Enter your third number')) smaller=('first number is smaller'if n2>n1<n3 else'second number is smaller'if n1>n2<n3 else'third number is smaller'if n1>n3<n2 else 'all are equal'if n1==n2==n3 else'first and second are equal and smaller'if n1==n2<n3 else 'second and third are equal and smaller'if n2==n3<n1 else'first and third are equal and smaller') print(smaller)
southheros=['Rajini','Naga Arjun','Chiranjiv','Mahesh Babu','Junior NTR','Ram Charan','Allu Arjun','Naga Chaitanya','Gopi Chand','Pavan Kalyan','Yash','Ravi Teja','Ram Pothenin'] n=input('Enter the name of your favorite south hero :') if n in southheros: print('It was there in the list') southheros.remove(n) print('You removed the name of your favorite south hero and the final list is given below-') for i in southheros: print(i) else: print('It is not there in the list') southheros.append(n) print('You have added the name of your favorite south hero and the final list is given below-') for i in southheros: print(i) ''' WWESuperstars=['Undertaker','Batista','Kane','Tripple H','Shawn Michaels','Randy Orton','Roman Reigns','John Cena','Brock Lesner','Seth Rollins','Edge'] n=input('Enter the name of your favorite WWE Superstar :') if n in WWESuperstars: print('It is there in the list') WWESuperstars.remove(n) print('You removed the name of your favorite WWE Superstar and the final list is given below-') for i in WWESuperstars: print(i) else: print('It is not there in the list') WWESuperstars.append(n) print('You have added the name of your favorite south hero and the final list is given below-') for i in WWESuperstars: print(i) '''
""" This set of classes is going to be used for easy HTML generation for Watson to read. Syntax is as follows: <html> <body> <div class="Story" id="Game Name"> <div class="Page" value=0> TEXT OR SOMETHING <div class="Choice" value=0> Go to Castle </div> <div class="Choice" value=1> Go Home </div> </div> <div class="Page" value=1> .... <div> .... <div> <body> <html> """ import unicodedata from BeautifulSoup import BeautifulSoup as bs from html import HTML class Page: def __init__(self, text, number=0, choices=[]): self.text = text self.num = number self.choices = choices def __str__(self): print self.text def __repr__(self): print "\n\n\n\n********************what*********************\n\n\n\n" class Story: """ Class for containing each story in an orderly way. Primarily going to be used for writing the information out to an HTML format that's readable to Watson """ def __init__(self, title=""): self.title = title self.pages = [] # List of Page objects def write_story(self): #This is where we add the tags h = HTML() h.html() h.body() h.div(klass="Story",id=self.title) for (x, p) in enumerate(self.pages): # print x, p.text, p.choices # exit() h.div(klass="Page",value=str(x)) if isinstance(p.text,unicode): h+=HTML(text=unicodedata.normalize('NFKD', p.text).encode('ascii','ignore')) else: h+=HTML(text=p.text) for (k, choice) in enumerate(p.choices): if isinstance(choice, unicode): choice = unicodedata.normalize('NFKD', choice).encode('ascii','ignore') h.div(choice,klass="Choice", value=str(k)) h+=HTML('/div') pass h += HTML('/div') h += HTML('/body') h += HTML('/html') soup = bs(str(h)) return soup.prettify() # Example of what the input looks like # p1 = Page("hello", 0,["Go Away","Go to Castle"]) # p2 = Page("Goodbye", 1,["Leave"]) # p3 = Page("I died ;_;", 2, []) # s = Story("Bitches") # Appends p1, p2, and p3 to the end of the pages array # [s.pages.append(x) for x in (p1,p2,p3)] # what = s.write_story() # soup = bs(str(what)) # pretty = soup.prettify() # with open("test.html","w+") as f: # f.write(s.write_story())
''' Author:Israel Flannery Date:15/10/2020 Description:right Room 2 Version:6.0 ''' #--------Libraries-------# import sqlite3 from sqlite3 import Error import random #------Functions--------# def introduction(): conn = None db_file = "quiz.db" try: conn = sqlite3.connect(db_file) except Error as e: print(e) c = conn.cursor() print(''' Welcome to this RPG game, select your race and explore through this dungeon ''') loop = True while loop: choice1 = input('Would you like to start a [n]ew game: ') if choice1 == 'n' or choice1 == 'new': loop = False builder() else: print('please enter a valid response') def builder(): loop = True while loop: newuser = input('Please enter your username: ') if newuser == '' or newuser == ' ': print('Please input a valid response') else: loop = False loop = True while loop: newpass = input('Please enter your password: ') if newpass == '' or newpass == ' ': print('Please input a valid response') else: loop = False race_list = ['[G]oose', '[H]uman', '[O]rc', '[E]lf', '[D]ragonkin'] loop = True print(""" Welcome""",newuser, """to the character builder, here you can pick from an available race or class to help you in your quest """) while loop: print('Here are the avaliable races') print(race_list) global user_race global race_skill global skillcount user_race = input(''' please select from one of the races by entering the name or the the first letter of the name: ''').lower() if user_race == 'g' or user_race == 'goose': print(''' You are a goose, the special ability is Honk, Honk allows you to do a random damge effect ranging from massive damage to healing. Uses:2 ''') skillcount = 2 race_skill = skillcount loop = False elif user_race == 'h' or user_race == 'human': print(''' You are a Human, the special ability is Strength Of The Weak This lets you do double your base damage. Uses:1 ''') skillcount = 1 race_skill = skillcount loop = False elif user_race == 'o' or user_race == 'orc': print(""" You are an Orc, the special ability is called Warcry, Warcry lets you do a basic attack without fail. uses:3 """) skillcount = 3 race_skill = skillcount loop = False elif user_race == 'e' or user_race == 'elf': print(""" You are a Elf, the special ability is Elven Knowledge, Elven knowlodge lets you attack with magic without fail. Uses:2 """) skillcount = 2 race_skill = skillcount loop = False elif user_race == 'd' or user_race == 'dragonkin': print(""" You are a Dragonkin, the special ability is Dragons Breath Dragonic Foresight lets you do double the usual amount of magic damage. uses:1 """) skillcount = 1 race_skill = skillcount loop = False else: loop = True print('please input a valid response') print('Now that you have built your character its time to name them') character_name = input('Please insert their name here:') conn = None db_file = "quiz.db" try: conn = sqlite3.connect(db_file) except Error as e: print(e) c = conn.cursor() user_list = [(newuser, newpass, character_name)] c.executemany("INSERT INTO players VALUES(?,?,?)",user_list) user_player = [character_name, user_race] story() def story(): conn = None db_file = "quiz.db" try: conn = sqlite3.connect(db_file) except Error as e: print(e) c = conn.cursor() print(''''You are an adventurer, with no adventure to go on. No quest to do, no monsters to slay, you feel meanignless. The start of the day is like any other day, sulking in the back of the tavern. However it ended up being different. A strange man in black robes approaches you.''') print('''"Greetings young adventurer" The strange man says, "I know of something that might interest you". You look at the man, confused, yet interested to hear more. "Theres an ancient dungeon that has been unexplored, I have been tasked by the King to hire an adventurer to explore it" the strange man says, holding out his arm.''') looptwo = True while looptwo: strangeman = input('Do you accept his deal [y]es or [n]o: ').lower() if strangeman == 'y' or strangeman == 'yes': looptwo = False print('''"Excellent, follow me and I shall lead you to the dungeon" the strange man says, "Please follow me to the dungeon and we can talk about a reward for clearing the dungeon".''') print('''You follow the strange man to the dungeon. When you arrive the dungeon resembles something of an old castle. "Now that we are here lets talk about a reward, I say 10 gold pieces" the strange man says. "10 Gold Pieces" you think to yourself, "Thats hardly enough, but if i try to push my luck it could end badly"''') print('you decide to leave it be') print('''The strange man guides you into the first room and leaves. You look around the room and notice this is nothing but an entrance hall. You notice a door.''') nextroom() elif strangeman == 'n' or strangeman == 'no': print('''"Well thats a shame, I guess no one does want to risk their life in an unexplored dungeon, good day" the strange man walks off to find someone else. You sit there alone, and in the next passing days you die of boredom...THE END''') looptwo = False score() else: print('"Your wasting my time, please answer the question" the strange man says') def nextroom(): loopthree = True while loopthree: progress = input('Would you like to open the door and go to the next room [y]es or [n]o: ').lower() if progress == 'y' or progress == 'yes': print('you open the door and head into the next room') loopthree = False story1() elif progress == 'n' or progress == 'no': print('You decide to have one more look around the room and find nothing, you head onto the next room') loopthree = False story1() else: print('You think a bit more') def story1(): print('''The second room is a massive hall, looking around there are multiple doors you can take...''') loop = True while loop: hlook = input('You have some options look [a]round, take the [l]eft door or the [r]ight door: ').lower() if hlook == 'a' or hlook == 'look around': loop = False print('''You look around the room some more and discover a dusty crate, you look inside the crate and find some useful things, you look on the side of the crate and read the sign "Crate of Useful Things". {Acquired "Useful Things?"}''') print('''You approach the right door and spot a monster!!! Upon further inspection the monster is an overgrown bat!!! "Bleh Bleh" it says. Your not scared and ready your weapon to battle the overgrown bat...''') rightroomfight() elif hlook == 'l' or hlook == 'left door': loop = False print('''You approach the left door and spot a monster!!! Upon further inspection the monster is a little green slime!!! "I'm not a bad slime SLURP" it says. You suddenly are filled with guilt in needing to battle this small green slime...''') leftroomfight() elif hlook == 'r' or hlook == 'right door': loop = False print('''You approach the right door and spot a monster!!! Upon further inspection the monster is an overgrown bat!!! "Bleh Bleh" it says. Your not scared and ready your weapon to battle the overgrown bat...''') rightroomfight() else: print('You sit around and do nothing') print('.....') print('Time to go') def rightroomfight(): playerhp = 100 overgrownbat = 10 playerweapon = 'Sword' print('You engage the Overgrown Bat') print('Your Health', playerhp) print('Overgrown Bat Health', overgrownbat) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and overgrownbat > 0: playerattack = random.randint(3,5) playermagic = random.randint(1,6) batattack = random.randint(1,4) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) if stunchance == 1: overgrownbat = overgrownbat - playerattack print('you deal', playerattack, 'to the Overgrown Bat', overgrownbat) playerhp = playerhp - batattack print('the Overgrown Bat attacks you dealing', batattack, 'to your', playerhp) elif stunchance == 2: overgrownbat = overgrownbat - playerattack print('you attack the Overgrown Bat and stun it dealing', playerattack, 'damage, Overgrown Bat hp', overgrownbat) elif move == 'b' or move == 'block': deflectchance = random.randint(1,2) if deflectchance == 1: overgrownbat = overgrownbat - playerattack print('you deflect the attack, you deal', playerattack, 'to the Overgrown Bats health', overgrownbat) elif deflectchance == 2: playerhp = playerhp - batattack print('you attempt to deflect the attack but fail, he deals', batattack, 'to your hp',playerhp) elif move == 'm' or move == 'magic': fuzzlechance = random.randint(1,2) if fuzzlechance == 1: overgrownbat = overgrownbat - playermagic print('you casted a spell dealing', playermagic, 'to the Overgrown Bat', overgrownbat) elif fuzzlechance == 2: playerhp = playerhp - batattack print('your spell failed and the Overgrown Bat attacked dealing', batattack, 'to your hp', playerhp,) elif move == 's' or 'skill': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) overgrownbat = overgrownbat - honk print('you honk at the Overgrown dealing a random amount of damage leaving the Overgrown Bat with', overgrownbat) race_skill = race_skill - 1 else: playerhp = playerhp - batattack print('you cannot use that anymore') print('you stand still and get hit by the Overgrown Bat, he deals', batattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') overgrownbat = overgrownbat - playerattack*2 print('you strike at the Overgrown bat dealing massive damage leaving the Overgrown Bat with', overgrownbat) race_skill = race_skill - 1 else: playerhp = playerhp - batattack print('you cannot use that anymore') print('you stand still and get hit by the Overgrown Bat, he deals', batattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') overgrownbat = overgrownbat - playerattack print('you scream at the Overgrown bat allowing you to gain the upper hand and attack for free', overgrownbat) race_skill = race_skill - 1 else: playerhp = playerhp - batattack print('you cannot use that anymore') print('you stand still and get hit by the Overgrown Bat, he deals', batattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') overgrownbat = overgrownbat - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Overgrown Bat', overgrownbat) race_skill = race_skill - 1 else: playerhp = playerhp - batattack print('you cannot use that anymore') print('you stand still and get hit by the Overgrown Bat, he deals', batattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') overgrownbat = overgrownbat - playermagic*2 print('you breath fire at the Overgrown Bat dealing massive damage leaving the Overgrown Bat with', overgrownbat) race_skill = race_skill - 1 else: playerhp = playerhp - batattack print('you cannot use that anymore') print('you stand still and get hit by the Overgrown Bat, she deals', batattack, 'to your hp', playerhp) else: playerhp = playerhp - batattack print('you stand still and get hit by the Overgrown Bat, he deals', batattack, 'to your hp', playerhp) if playerhp < 1: print('you died...THE END') score() elif overgrownbat < 1: print('you killed the Overgrown Bat') storyrightroom() def leftroomfight(): playerhp = 100 greenslime = 15 playerweapon = 'Sword' print('You engage the Little Green Slime') print('Your Health', playerhp) print('Little Green Slime Health', greenslime) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and greenslime > 0: #everything below this is the battle system playerattack = random.randint(3,5) playermagic = random.randint(1,6) slimeattack = random.randint(2,5) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) #stunning is a chance that can happen to help the player if stunchance == 1: greenslime = greenslime - playerattack print('you deal', playerattack, 'to the Little Green Slime', greenslime) playerhp = playerhp - slimeattack print('the Little Green Slime attacks you dealing', slimeattack, 'to your', playerhp) elif stunchance == 2: greenslime = greenslime - playerattack print('you attack the Little Green Slime and stun it dealing', playerattack, 'damage, Little Green Slime hp', greenslime) elif move == 'b': deflectchance = random.randint(1,2) #you have a chance to deflect the attack dealing damage back to the enemy if deflectchance == 1: greenslime = greenslime - playerattack print('you deflect the attack, you deal', playerattack, 'to the Little Green Slimes health', greenslime) elif deflectchance == 2: playerhp = playerhp - slimeattack print('you attempt to deflect the attack but fail, it deals', slimeattack, 'to your hp',playerhp) elif move == 'm': fuzzlechance = random.randint(1,2) #Fuzzling is a mechanic where the spell fails if fuzzlechance == 1: greenslime = greenslime - playermagic print('you casted a spell dealing', playermagic, 'to the Little Green Slime', greenslime) elif fuzzlechance == 2: playerhp = playerhp - slimeattack print('your spell failed and the Little Green Slime attacked dealing', slimeattack, 'to your hp', playerhp,) elif move == 's': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) greenslime = greenslime - honk print('you honk at the Little Green Slime dealing a random amount of damage leaving the Little Green Slime with', greenslime) race_skill = race_skill - 1 else: playerhp = playerhp - slimeattack print('you cannot use that anymore') print('you stand still and get hit by the Little Green Slime, she deals', slimeattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') greenslime = greenslime - playerattack*2 print('you strike at the Overgrown bat dealing massive damage leaving the Little Green Slime with', greenslime) race_skill = race_skill - 1 else: playerhp = playerhp - slimeattack print('you cannot use that anymore') print('you stand still and get hit by the Little Green Slime, she deals', slimeattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') greenslime = greenslime - playerattack print('you scream at the Little Green Slime allowing you to gain the upper hand and attack for free', greenslime) race_skill = race_skill - 1 else: playerhp = playerhp - slimeattack print('you cannot use that anymore') print('you stand still and get hit by the Little Green Slime, she deals', slimeattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') greenslime = greenslime - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Little Green Slime', greenslime) race_skill = race_skill - 1 else: playerhp = playerhp - slimeattack print('you cannot use that anymore') print('you stand still and get hit by the Little Green Slime, she deals', slimeattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') greenslime = greenslime - playermagic*2 print('you breath fire at the Little Green Slime dealing massive damage leaving the Little Green Slime with', greenslime) race_skill = race_skill - 1 else: playerhp = playerhp - slimeattack print('you cannot use that anymore') print('you stand still and get hit by the Little Green Slime, she deals', slimeattack, 'to your hp', playerhp) else: playerhp = playerhp - batattack print('you stand still and get hit by the Little Green Slime, she deals', slimeattack, 'to your hp', playerhp) if playerhp < 1: print('you died...THE END') score() elif greenslime < 1: print('you killed the Little Green Slime') storyleftroom def storyrightroom(): print('''You look down at the overgrown bat and decide to continue on past and head through the right door, on the other side is just a long hallway with a door at the end''') loop = True while loop: hlook = input('You have some options look [a]round, head to the [d]oor: ').lower() if hlook == 'a' or hlook == 'look around': print('''You look around and find nothing of note, no secret passages, no secret items, no secret doors, its just a regular hallway''') elif hlook == 'd' or hlook == 'door': loop = False print('''You approach the door and spot a monster!!! Upon further inspection the monster is a Goat!!! "MEEEEEEEAH" it says dinging its bell threateningly. You have never seen a creature like this before, but surely its not that hard, right?''') goatfight() else: print('You sit around and do nothing') print('.....') print('Time to go') def goatfight(): playerhp = 100 goat = 15 playerweapon = 'Sword' print('You engage the Goat') print('Your Health', playerhp) print('Goat Health', goat) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and goat > 0: playerattack = random.randint(6,8) playermagic = random.randint(6,12) goatattack = random.randint(6,10) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) if stunchance == 1: goat = goat - playerattack print('you deal', playerattack, 'to the Goat', goat) playerhp = playerhp - goatattack print('the Goat attacks you dealing', goatattack, 'to your', playerhp) elif stunchance == 2: goat = goat - playerattack print('you attack the Goat and stun it dealing', playerattack, 'damage, Goat hp', goat) elif move == 'b': deflectchance = random.randint(1,2) if deflectchance == 1: goat = goat - playerattack print('you deflect the attack, you deal', playerattack, 'to the Goats health', goat) elif deflectchance == 2: playerhp = playerhp - goatattack print('you attempt to deflect the attack but fail, he deals', goatattack, 'to your hp',playerhp) elif move == 'm': fuzzlechance = random.randint(1,2) if fuzzlechance == 1: goat = goat - playermagic print('you casted a spell dealing', playermagic, 'to the Goat', goat) elif fuzzlechance == 2: playerhp = playerhp - goatattack print('your spell failed and the Goat attacked dealing', goatattack, 'to your hp', playerhp,) elif move == 's': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) goat = goat - honk print('you honk at the Goat dealing a random amount of damage leaving the Goat with', goat) race_skill = race_skill - 1 else: playerhp = playerhp - goatattack print('you cannot use that anymore') print('you stand still and get hit by the Goat, it deals', goatattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') goat = goat - playerattack*2 print('you strike at the Goat dealing massive damage leaving the Goat with', goat) race_skill = race_skill - 1 else: playerhp = playerhp - goatattack print('you cannot use that anymore') print('you stand still and get hit by the Goat, it deals', goatattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') goat = goat - playerattack print('you scream at the Goat allowing you to gain the upper hand and attack for free', goat) race_skill = race_skill - 1 else: playerhp = playerhp - goatattack print('you cannot use that anymore') print('you stand still and get hit by the Goat, she deals', goatattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') goat = goat - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Goat', goat) race_skill = race_skill - 1 else: playerhp = playerhp - goatattack print('you cannot use that anymore') print('you stand still and get hit by the Goat, it deals', goatattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') goat = goat - playermagic*2 print('you breath fire at the Goat dealing massive damage leaving the Goat with', goat) race_skill = race_skill - 1 else: playerhp = playerhp - goatattack print('you cannot use that anymore') print('you stand still and get hit by the Goat, she deals', goatattack, 'to your hp', playerhp) else: playerhp = playerhp - goatattack print('you stand still and get hit by the Goat, it deals', goatattack, 'to your hp', playerhp) if playerhp < 1: print('you died...THE END') score() elif goat < 1: print('you killed the Goat') bedchamber() def storyleftroom(): print('''You look down at the Little Green Slime and you begin to be filled with sadness... after having a good cry you decide to continue on past and headthrough the left door, on the other side is just a long hallway with a door at the end''') loop = True while loop: hlook = input('You have some options look [a]round, head to the [d]oor: ').lower() if hlook == 'a' or hlook == 'look around': print('''You look around and find nothing of note, no secret passages, no secret items, no secret doors, its just a regular hallway, except for a strangley out of place wooden chair.''') elif hlook == 'd' or hlook == 'door': loop = False print('''You approach the door and spot a monster!!! Upon further inspection its just a wooden chair... "CREEEEEAK" the chair says as you sit down on it? What, the chair reveals itself to be a chair mimic and you engage in combat.''') chairfight() else: print('You sit around and do nothing') print('.....') print('Time to go') def chairfight(): playerhp = 100 chair = 15 playerweapon = 'Sword' print('You engage the Chair Mimic') print('Your Health', playerhp) print('Chair Mimic Health', chair) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and chair > 0: playerattack = random.randint(4,8) playermagic = random.randint(6,7) chairattack = random.randint(8,12) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) if stunchance == 1: chair = chair - playerattack print('you deal', playerattack, 'to the Chair Mimic', chair) playerhp = playerhp - chairattack print('the Chair Mimic attacks you dealing', chairattack, 'to your', playerhp) elif stunchance == 2: chair = chair - playerattack print('you attack the Chair Mimic and stun it dealing', playerattack, 'damage, Chair Mimic hp', goat) elif move == 'b': deflectchance = random.randint(1,2) if deflectchance == 1: chair = chair - playerattack print('you deflect the attack, you deal', playerattack, 'to the Chair Mimic health', goat) elif deflectchance == 2: playerhp = playerhp - chairattack print('you attempt to deflect the attack but fail, he deals', chairattack, 'to your hp',playerhp) elif move == 'm': fuzzlechance = random.randint(1,2) if fuzzlechance == 1: chair = chair - playermagic print('you casted a spell dealing', playermagic, 'to the Chair Mimic', chair) elif fuzzlechance == 2: playerhp = playerhp - chairattack print('your spell failed and the Chair Mimic attacked dealing', chairattack, 'to your hp', playerhp,) elif move == 's': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) chair = chair - honk print('you honk at the Chair Mimic dealing a random amount of damage leaving the Chair Mimic with', chair) race_skill = race_skill - 1 else: playerhp = playerhp - chairattack print('you cannot use that anymore') print('you stand still and get hit by the Chair Mimic, it deals', chairattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') chair = chair - playerattack*2 print('you strike at the Chair Mimic dealing massive damage leaving the Chair Mimic with', chair) race_skill = race_skill - 1 else: playerhp = playerhp - chairattack print('you cannot use that anymore') print('you stand still and get hit by the Chair Mimic, it deals', chairattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') chair = chair - playerattack print('you scream at the Chair Mimic allowing you to gain the upper hand and attack for free', chair) race_skill = race_skill - 1 else: playerhp = playerhp - chairattack print('you cannot use that anymore') print('you stand still and get hit by the Goat, she deals', chairattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') chair = chair - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Chair Mimic', chair) race_skill = race_skill - 1 else: playerhp = playerhp - chairattack print('you cannot use that anymore') print('you stand still and get hit by the Chair Mimic, it deals', chairattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') chair = chair - playermagic*2 print('you breath fire at the Chair Mimic dealing massive damage leaving the Chair Mimic with', chair) race_skill = race_skill - 1 else: playerhp = playerhp - chairattack print('you cannot use that anymore') print('you stand still and get hit by the Chair Mimic, it deals', chairattack, 'to your hp', playerhp) else: playerhp = playerhp - chairattack print('you stand still and get hit by the Chair Mimic, it deals', chairattack, 'to your hp', playerhp) if playerhp < 1: print('you died..THE END') score() elif chair < 1: print('you killed the Chair Mimic') kitchen() def bedchamber(): print('''you look down at the dead goat and wonder if its gonna come back. Upon entering the room you reach a bed chamber, at the end is a door''') loop = True while loop: hlook = input('You have some options look [a]round or head to the [d]oor: ').lower() if hlook == 'a' or hlook == 'look around': print('''You look around the bed chamber, its hard to imagine something this beautiful being in a dirty old dungeon like this, you look at the bed and notice it is neatly made, you decide to jump on it and rest a bit.''') elif hlook == 'd' or hlook == 'door': loop = False print('''You approach the door and spot a monster!!! Upon further inspection the monster is a Imp!!! "Oi get out of my room Im playing Blockcraft." he says. The Imp readys a strange device with lightning sparking off it...''') impfight() else: print('You sit around and do nothing') print('.....') print('Time to go') def impfight(): playerhp = 100 imp = 20 playerweapon = 'Sword' print('You engage the Imp') print('Your Health', playerhp) print('Imp Health', imp) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and imp > 0: playerattack = random.randint(6,8) playermagic = random.randint(6,10) impattack = random.randint(14,21) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) if stunchance == 1: imp = imp - playerattack print('you deal', playerattack, 'to the Imp', imp) playerhp = playerhp - impattack print('the Imp attacks you dealing', impattack, 'to your', playerhp) elif stunchance == 2: imp = imp - playerattack print('you attack the imp and stun it dealing', playerattack, 'damage, Imp hp', imp) elif move == 'b': deflectchance = random.randint(1,2) if deflectchance == 1: imp = imp - playerattack print('you deflect the attack, you deal', playerattack, 'to the Imps health', imp) elif deflectchance == 2: playerhp = playerhp - impattack print('you attempt to deflect the attack but fail, he deals', impattack, 'to your hp',playerhp) elif move == 'm': fuzzlechance = random.randint(1,2) if fuzzlechance == 1: imp = imp - playermagic print('you casted a spell dealing', playermagic, 'to the Imp', imp) elif fuzzlechance == 2: playerhp = playerhp - impattack print('your spell failed and the Imp attacked dealing', impattack, 'to your hp', playerhp,) elif move == 's': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) imp = imp - honk print('you honk at the Imp dealing a random amount of damage leaving the Imp with', imp) race_skill = race_skill - 1 else: playerhp = playerhp - impattack print('you cannot use that anymore') print('you stand still and get hit by the Imp, it deals', impattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') imp = imp - playerattack*2 print('you strike at the Imp dealing massive damage leaving the Imp with', imp) race_skill = race_skill - 1 else: playerhp = playerhp - impattack print('you cannot use that anymore') print('you stand still and get hit by the Imp, it deals', impattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') imp = imp - playerattack print('you scream at the Imp allowing you to gain the upper hand and attack for free', imp) race_skill = race_skill - 1 else: playerhp = playerhp - impattack print('you cannot use that anymore') print('you stand still and get hit by the Imp, it deals', impattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') imp = imp - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Imp', imp) race_skill = race_skill - 1 else: playerhp = playerhp - impattack print('you cannot use that anymore') print('you stand still and get hit by the Imp, it deals', impattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') imp = imp - playermagic*2 print('you breath fire at the Imp dealing massive damage leaving the Imp with', imp) race_skill = race_skill - 1 else: playerhp = playerhp - impattack print('you cannot use that anymore') print('you stand still and get hit by the Imp, it deals', impattack, 'to your hp', playerhp) else: playerhp = playerhp - impattack print('you stand still and get hit by the Imp, he deals', impattack, 'to your hp', playerhp) if playerhp < 1: print('you died...THE END') score() elif imp < 1: print('you killed the Imp') bosschamber() def kitchen(): print('''you look down at the remains of the chair mimic, it looked just like a regular chair. Upon entering the room you reach a dining hall, at the end is a door''') loop = True while loop: hlook = input('You have some options look [a]round or head to the [d]oor: ').lower() if hlook == 'a' or hlook == 'look around': print('''You look around the dining room, its hard to imagine something this beautiful being in a dirty old dungeon like this, you look at the table and see freshly made food, roasted chicken, hamburgers, fried chips and more. You take a bite of everything on the table.''') elif hlook == 'd' or hlook == 'door': loop = False print('''You approach the door and spot a monster!!! Upon further inspection the monster is a Gremlin Granny!!! "You better eat your brussel sprouts sonny." she says. The Gremlin Granny readys what looks to be a brussel sprout into her laddle to toss it at you...''') grannyfight() else: print('You sit around and do nothing') print('.....') print('Time to go') def grannyfight(): playerhp = 100 granny = 25 playerweapon = 'Sword' print('You engage the Gremlin Granny') print('Your Health', playerhp) print('Gremlin Granny Health', granny) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and granny > 0: playerattack = random.randint(3,5) playermagic = random.randint(3,12) granattack = random.randint(14,21) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) if stunchance == 1: granny = granny - playerattack print('you deal', playerattack, 'to the Gremlin Granny', granny) playerhp = playerhp - granattack print('the Gremlin Granny attacks you dealing', granattack, 'to your', playerhp) elif stunchance == 2: granny = granny - playerattack print('you attack the Gremlin Granny and stun it dealing', playerattack, 'damage, Gremlin Granny hp', granny) elif move == 'b': deflectchance = random.randint(1,2) if deflectchance == 1: granny = granny - playerattack print('you deflect the attack, you deal', playerattack, 'to the Gremlin Grannys health', granny) elif deflectchance == 2: playerhp = playerhp - granattack print('you attempt to deflect the attack but fail, she deals', granattack, 'to your hp',playerhp) elif move == 'm': fuzzlechance = random.randint(1,2) if fuzzlechance == 1: granny = granny - playermagic print('you casted a spell dealing', playermagic, 'to the Gremlin Granny', granny) elif fuzzlechance == 2: playerhp = playerhp - granattack print('your spell failed and the Gremlin Granny attacked dealing', granattack, 'to your hp', playerhp,) elif move == 's': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) granny = granny - honk print('you honk at the Gremlin Granny dealing a random amount of damage leaving the Gremlin Granny with', granny) race_skill = race_skill - 1 else: playerhp = playerhp - granattack print('you cannot use that anymore') print('you stand still and get hit by the Gremlin Granny, she deals', granattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') granny = granny - playerattack*2 print('you strike at the Gremlin Granny dealing massive damage leaving the Gremlin Granny with', granny) race_skill = race_skill - 1 else: playerhp = playerhp - granattack print('you cannot use that anymore') print('you stand still and get hit by the Gremlin Granny, she deals', granattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') granny = granny - playerattack print('you scream at the Gremlin Granny allowing you to gain the upper hand and attack for free', granny) race_skill = race_skill - 1 else: playerhp = playerhp - granattack print('you cannot use that anymore') print('you stand still and get hit by the Gremlin Granny, it deals', granattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') granny = granny - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Gremlin Granny', granny) race_skill = race_skill - 1 else: playerhp = playerhp - granattack print('you cannot use that anymore') print('you stand still and get hit by the Gremlin Granny, it deals', granattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') granny = granny - playermagic*2 print('you breath fire at the Gremlin Granny dealing massive damage leaving the Gremlin Granny with', granny) race_skill = race_skill - 1 else: playerhp = playerhp - granattack print('you cannot use that anymore') print('you stand still and get hit by the Gremlin Granny, it deals', granattack, 'to your hp', playerhp) else: playerhp = playerhp - granattack print('you stand still and get hit by the Gremlin Granny, she deals', granattack, 'to your hp', playerhp) if playerhp < 1: print('you died...THE END') elif granny < 1: print('you killed the Gremlin Granny') bosschamber() def bosschamber(): print('''you open the grandoise door and enter, its a massive chamber and inside is a massive pile of gold''') loop = True while loop: hlook = input('You have some options look [a]round, head to the [g]old or check the [d]oor: ').lower() if hlook == 'a' or hlook == 'look around': loop = False print('''You look around the massive chamber and spot a piece of paper on the ground... you pick it up and read it... "The L__h _as go__ and d_s_u__ed _ims_lf to fool the s_rface __ m__t _e s___p__" The note is smudged and hard to read... You head towards the pile of gold.''') bossfight() elif hlook == 'd' or hlook == 'door': print('''You try to reopen the door but fail, you kick the door a couple of times and still nothing.''') elif hlook == 'g' or hlook == 'gold': print('''you walk down towards the pile of gold...''') loop = False bossfight() else: print('You sit around and do nothing') print('.....') print('Time to go') def bossfight(): playerhp = 100 dragon = 50 playerweapon = 'Sword' print('''You walk around on the pile of gold when you start to hear light breathing. You look down and an eye opens... You jump back in panic and a massive Ancient Gold Dragon rises from the pile.''') print('You engage the Ancient Gold Dragon') print('Your Health', playerhp) print('Ancient Gold Dragon Health', dragon) global skillcount global user_race global race_skill race_skill = skillcount while playerhp > 0 and dragon > 0: playerattack = random.randint(3,5) playermagic = random.randint(3,12) goldattack = random.randint(20,30) move = input("""Select an action [a]ttack with """ +playerweapon+ """ [b]lock the attack [m]agic attack [s]kill """).lower() if move == "a" or move == "attack": stunchance = random.randint(1,2) if stunchance == 1: dragon = dragon - playerattack print('you deal', playerattack, 'to the Ancient Gold Dragon', dragon) playerhp = playerhp - goldattack print('the Ancient Gold Dragon attacks you dealing', goldattack, 'to your', playerhp) elif stunchance == 2: dragon = dragon - playerattack print('you attack the Ancient Gold Dragon and stun it dealing', playerattack, 'damage, Ancient Gold Dragon hp', dragon) elif move == 'b': deflectchance = random.randint(1,2) if deflectchance == 1: dragon = dragon - playerattack print('you deflect the attack, you deal', playerattack, 'to the Ancient Gold Dragons health', dragon) elif deflectchance == 2: playerhp = playerhp - goldattack print('you attempt to deflect the attack but fail, he deals', goldattack, 'to your hp',playerhp) elif move == 'm': fuzzlechance = random.randint(1,2) if fuzzlechance == 1: dragon = dragon - playermagic print('you casted a spell dealing', playermagic, 'to the Ancient Gold Dragon', dragon) elif fuzzlechance == 2: playerhp = playerhp - goldattack print('your spell failed and the Ancient Gold Dragon attacked dealing', goldattack, 'to your hp', playerhp,) elif move == 's': if user_race == 'g' or user_race == 'goose': if race_skill > 0: #skills can only be used a set number of times resulting in it haveing none left print('You use your skill, HONK!') honk = random.randint(-20,30) dragon = dragon - honk print('you honk at the Ancient Gold Dragon dealing a random amount of damage leaving the Ancient Gold Dragon with', dragon) race_skill = race_skill - 1 else: playerhp = playerhp - goldattack print('you cannot use that anymore') print('you stand still and get hit by the Ancient Gold Dragon, it deals', goldattack, 'to your hp', playerhp) elif user_race == 'h' or user_race == 'human': if race_skill > 0: print('You use your skill, Strength of the Weak') dragon = dragon - playerattack*2 print('you strike at the Ancient Gold Dragon dealing massive damage leaving the Ancient Gold Dragon with', dragon) race_skill = race_skill - 1 else: playerhp = playerhp - goldattack print('you cannot use that anymore') print('you stand still and get hit by the Ancient Gold Dragon, it deals', goldattack, 'to your hp', playerhp) elif user_race == 'o' or user_race == 'orc': if race_skill > 0: print('You use your skill, Warcry') dragon = dragon - playerattack print('you scream at the Ancient Gold Dragon allowing you to gain the upper hand and attack for free', dragon) race_skill = race_skill - 1 else: playerhp = playerhp - goldattack print('you cannot use that anymore') print('you stand still and get hit by the Ancient Gold Dragon, it deals', goldattack, 'to your hp', playerhp) elif user_race == 'e' or user_race == 'elf': if race_skill > 0: print('You use your skill, Elven Knowlodge') dragon = dragon - playermagic print('you use your knowlodge of magic to cast a spell without fail to the Ancient Gold Dragon', dragon) race_skill = race_skill - 1 else: playerhp = playerhp - goldattack print('you cannot use that anymore') print('you stand still and get hit by the Ancient Gold Dragon, it deals', goldattack, 'to your hp', playerhp) elif user_race == 'd' or user_race == 'dragonkin': if race_skill > 0: print('You use your skill, Dragons Breath') dragon = dragon - playermagic*2 print('you breath fire at the Ancient Gold Dragon dealing massive damage leaving the Ancient Gold Dragon with', dragon) race_skill = race_skill - 1 else: playerhp = playerhp - goldattack print('you cannot use that anymore') print('you stand still and get hit by the Ancient Gold Dragon, it deals', goldattack, 'to your hp', playerhp) else: playerhp = playerhp - goldattack print('you stand still and get hit by the Ancient Gold Dragon, he deals', goldattack, 'to your hp', playerhp) if playerhp < 1: print('you died...THE END') score() elif dragon < 1: print('you defeated the Ancient Gold Dragon') ending() def ending(): print('''You watch as the Ancient Gold Dragon falls to the ground, "Please Adventurer, spare my life and I will tell you the truth behind your quest" The Ancient Gold Dragon says weakly''') ending = input('Will you -[s]pare the dragon, or will you [k]ill it to fulfil your quest').lower() if ending == 's' or ending == 'spare': print('You spare the dragon as it recovers its strength') print('"Thank you adventurer, the truth behind your quest is that the man who hired you is an evil lich, together we shall defeat him"') print('''You hop on the dragons back and ride it out of the dungeon. The Strange Man sees this and starts cursing at you, the Ancient Gold Dragon lands on the strange man killing him... THE END''') score() elif ending == 'k' or ending == 'kill': print('You raise your sword up high and slash down on the dragon...') print('You return to the strange old man and recieve the 10 gold pieces') print('"HAHAHAHAHAHAHA, you dumb cretin, you absolute bufoon, you fell for my trick" The strange old man says') print('''The world is plunged into darkness... THE END''') score() else: print('''The dragon eats you... THE END''') score() def score(): conn = None db_file = "quiz.db" try: conn = sqlite3.connect(db_file) except Error as e: print(e) c = conn.cursor() print('You wake up in a room with a singular chest and open it, it shows information of previous heros, including unique codes') c.execute("SELECT rowid,* FROM players") #showing row id and other fields results = c.fetchall() #you can use fetchone if you want just one result conn.commit() for i in results: # this will display the tuples in the list print(i) #--------Main--------# user_race = None race_skill = None skillcount = None introduction()
#自分が何日間いきているか計算 import datetime import math #今日 today = datetime.date.today() #誕生日 birthday = datetime.date(1998,2,25) life = today - birthday print(str(life.days) + "日間生きています!") #現在の年齢 age = math.floor(life.days / 365) print(str(age) + "歳です") #曜日ごとにメッセージを変える #0は月曜日、6は日曜日 # 月曜日 if today.weekday() == 0: print("一週間の幕開け!!") # 火曜 ~ 木曜日 elif today.weekday() < 4: print("がんばれ!!!") # 金曜日 elif today.weekday() == 4: print("金曜日だ!!あとちょっと!") # 土日 else: print("死ぬほど楽しめ!!!") # 好きになる有名人の年齢平均 agelist = [37, 35, 40, 33, 39] # 合計値を要素数でわる ave = sum(agelist) / len(agelist) # 平均値 print(str(math.floor(ave)) + "歳あたりの方を好きになる傾向があります") # 平均値でメッセージ変える if ave <= 30: print("若い男性がタイプです") elif ave <= 40: print("イケオジがタイプです") else: print("おじさんが可愛いと思うタイプです")
from multiprocessing import Pool, Manager def get_word(que): word_list = ["Life", "is", "short"] for word in word_list: que.put(word) def print_word(que): for i in range(3): print(que.get(), end=" ") def main(): process_pool = Pool(2) word_que = Manager().Queue() process_pool.apply_async(print_word, args=(word_que,)) process_pool.apply_async(get_word, args=(word_que,)) process_pool.close() process_pool.join()
words = "Life is short" def print_before(func): # it is almost a trap to print here, words will be printed while decorating instead of calling foo # Be aware that @ is just syntactic sugar, decorating is equivalent to `print_before(foo)` print(words) def wrapper(*args, **kw): return func(*args, **kw) return wrapper @print_before def foo(): pass
word_list = ["Life", "is", "short"] it = iter(word_list) while True: try: print(next(it), end=" ") except StopIteration: break
quantApl = int(input("How many apple do you want to buy? \n> ")) quantOrng = int(input("How many orange do you want to buy? \n> ")) aplPrice = quantApl * 20 orngPrice = quantOrng * 25 overallTtl = aplPrice + orngPrice print(f'Apple: 20 pesos * {quantApl} piece/s = {aplPrice}') print(f'Orange: 25 pesos * {quantOrng} piece/s = {orngPrice}') print(f'The total amount is {overallTtl} pesos.')
# Source: https://leetcode.com/problems/swap-nodes-in-pairs/ # # Level: Medium # # Date: 29th July 2019 """ Given a linked list, swap every two adjacent nodes and return its head. You may not modify the values in the list's nodes, only nodes itself may be changed. Example: Given 1->2->3->4, you should return the list as 2->1->4->3. """ # Solution # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head firstNode = head secondNode = head.next newHead = head.next.next secondNode.next = firstNode firstNode.next = self.swapPairs(newHead) return secondNode
# Source: https://leetcode.com/problems/rotting-oranges/ # # Date: 23rd August 2019 """ In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. Example 1: Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. Note: 1 <= grid.length <= 10 1 <= grid[0].length <= 10 grid[i][j] is only 0, 1, or 2. """ # Solution import collections from typing import List class Solution: def orangesRotting(self, arrayInput: List[List[int]]) -> int: rowSize, colSize = len(arrayInput), len(arrayInput[0]) # queue - all starting cells with rotting oranges queue = collections.deque() for rowIndex, row in enumerate(arrayInput): for colIndex, colValue in enumerate(row): if colValue == 2: queue.append((rowIndex, colIndex, 0)) def neighbors(row, col): for currentRow, currentCol in ((row - 1, col), (row, col - 1), (row + 1, col), (row, col + 1)): if 0 <= currentRow < rowSize and 0 <= currentCol < colSize: yield currentRow, currentCol minutes = 0 while queue: row, col, minutes = queue.popleft() for currentRow, currentCol in neighbors(row, col): if arrayInput[currentRow][currentCol] == 1: arrayInput[currentRow][currentCol] = 2 queue.append((currentRow, currentCol, minutes + 1)) if any(1 in row for row in arrayInput): return -1 return minutes
# Source: https://leetcode.com/problems/subarrays-with-k-different-integers/ # # Date: 19th August 2019 """ Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K. (For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.) Return the number of good subarrays of A. Example 1: Input: A = [1,2,1,2,3], K = 2 Output: 7 Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2, 1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]. Example 2: Input: A = [1,2,1,3,4], K = 3 Output: 3 Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4]. Note: 1 <= A.length <= 20000 1 <= A[i] <= A.length 1 <= K <= A.length """ # Solution import collections from typing import List class Solution: def subarraysWithKDistinct(self, arrayInput: List[int], K: int) -> int: return subarraysWithAtMostKDistinct(arrayInput, K) - subarraysWithAtMostKDistinct(arrayInput, K - 1) def subarraysWithAtMostKDistinct(subArray, k): lookup = collections.defaultdict(int) left, right, counter, res = 0, 0, 0, 0 while right < len(subArray): lookup[subArray[right]] += 1 if lookup[subArray[right]] == 1: counter += 1 right += 1 while left < right and counter > k: lookup[subArray[left]] -= 1 if lookup[subArray[left]] == 0: counter -= 1 left += 1 res += right - left return res
# Source: https://leetcode.com/problems/search-in-a-binary-search-tree/ # Level: Easy # # Date: 07th August 2019 """ Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. For example, Given the tree: 4 / \ 2 7 / \ 1 3 And the value to search: 2 You should return this subtree: 2 / \ 1 3 In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL. Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null. """ # Solution # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def searchBST(self, rootNode: TreeNode, val: int) -> TreeNode: currentNode = rootNode while currentNode is not None: if currentNode.val == val: return currentNode elif currentNode.val > val: currentNode = currentNode.left else: currentNode = currentNode.right return currentNode
# Source: 2020 Goldman Sachs Engineering Code test # Level: Medium # Date: 17th July 2019 def analyzeInvestments(stringInput): # O(n^2) hashMap = {} count = 0 for index, value in enumerate(stringInput): if index + 3 > len(stringInput): break hashMap[value] = index for index2, otherValues in enumerate(stringInput[index + 1:]): if otherValues in hashMap: continue hashMap[otherValues] = index2 + index + 1 if 'A' in hashMap and 'B' in hashMap and 'C' in hashMap: count += len(stringInput) - max(hashMap['A'], hashMap['B'], hashMap['C']) break hashMap = {} return count def analyzeInvestments2(stringInput): # O(n) count = 0 companiesIndexes = [[], [], [], []] for index, value in enumerate(stringInput): if value == 'A': companiesIndexes[0].append(index) elif value == 'B': companiesIndexes[1].append(index) elif value == 'C': companiesIndexes[2].append(index) else: companiesIndexes[3].append(index) while True: if len(companiesIndexes[0]) == 0 or len(companiesIndexes[1]) == 0 or len(companiesIndexes[2]) == 0: return count minIndexA = companiesIndexes[0][0] minIndexB = companiesIndexes[1][0] minIndexC = companiesIndexes[2][0] minIndexOthers = float('inf') if len(companiesIndexes[3]) != 0: minIndexOthers = companiesIndexes[3][0] minVal = min(minIndexA, minIndexB, minIndexC, minIndexOthers) else: minVal = min(minIndexA, minIndexB, minIndexC) if minVal == minIndexOthers: count += 1 else: count += len(stringInput) - max(minIndexA, minIndexB, minIndexC) if minVal == minIndexA: companiesIndexes[0].pop(0) if minVal == minIndexB: companiesIndexes[1].pop(0) if minVal == minIndexC: companiesIndexes[2].pop(0) if minIndexOthers and minVal == minIndexOthers: companiesIndexes[3].pop(0) print(analyzeInvestments('ABCCBA'), analyzeInvestments2('ABCCBA'))
# Source: https://leetcode.com/problems/powx-n/submissions/ # # Level: Easy # # Date: 30th July 2019 """ Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree. Example : Input: root = [4,2,6,1,3,null,null] Output: 1 Explanation: Note that root is a TreeNode object, not an array. The given tree [4,2,6,1,3,null,null] is represented by the following diagram: 4 / \ 2 6 / \ 1 3 while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2. Note: The size of the BST will be between 2 and 100. The BST is always valid, each node's value is an integer, and each node's value is different. This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/ """ # Solution # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDiffInBST(self, root: TreeNode) -> int: if root is None or isLeaf(root): return 0 treeElements = minDiff(root, [float('inf')]) if len(treeElements) == 3: if abs(treeElements[1] - treeElements[2]) < treeElements[0]: treeElements[0] = abs(treeElements[1] - treeElements[2]) treeElements.pop(1) return treeElements[0] def minDiff(currentNode, treeElements): if currentNode.left is not None: minDiff(currentNode.left, treeElements) if len(treeElements) == 3: if abs(treeElements[1] - treeElements[2]) < treeElements[0]: treeElements[0] = abs(treeElements[1] - treeElements[2]) treeElements.pop(1) treeElements.append(currentNode.val) if currentNode.right is not None: minDiff(currentNode.right, treeElements) return treeElements def isLeaf(currentNode): return currentNode.left is None and currentNode.right is None
# Source: https://leetcode.com/problems/reverse-words-in-a-string/ # # Level: Medium # # Date: 31st July 2019 """ Given an input string, reverse the string word by word. Example 1: Input: "the sky is blue" Output: "blue is sky the" Example 2: Input: " hello world! " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces. Example 3: Input: "a good example" Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. Note: A word is defined as a sequence of non-space characters. Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. You need to reduce multiple spaces between two words to a single space in the reversed string. Follow up: For C programmers, try to solve it in-place in O(1) extra space. """ # Solution class Solution: def reverseWords(self, stringInput: str) -> str: stringInput = stringInput.strip().split(' ') stringInput = stringInput[::-1] i = 0 while i < len(stringInput): prev = i if stringInput[i] == '': while i < len(stringInput) and stringInput[i] == '': i += 1 stringInput = stringInput[:prev] + stringInput[i:] i = prev i += 1 return ' '.join(stringInput)
# Source: https://leetcode.com/problems/intersection-of-two-arrays-ii/ # # Date: 22nd August 2019 """ Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? """ # Solution from typing import List class Solution: def intersect(self, firstArray: List[int], secondArray: List[int]) -> List[int]: if len(firstArray) == 0 or len(secondArray) == 0: return [] hashMap = {} if len(firstArray) < len(secondArray): for num in firstArray: hashMap[num] = hashMap.get(num, 0) + 1 main = secondArray else: for num in secondArray: hashMap[num] = hashMap.get(num, 0) + 1 main = firstArray output = [] for num in main: if num in hashMap and hashMap[num] > 0: output.append(num) hashMap[num] -= 1 return output
# Source: https://leetcode.com/problems/can-place-flowers/ # Level: Easy # Date: 12th July 2019 # Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot # be planted in adjacent plots - they would compete for water and both would die. # # Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), # and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule. # # Example 1: # Input: flowerbed = [1,0,0,0,1], n = 1 # Output: True # Example 2: # Input: flowerbed = [1,0,0,0,1], n = 2 # Output: False # Note: # The input array won't violate no-adjacent-flowers rule. # The input array size is in the range of [1, 20000]. # n is a non-negative integer which won't exceed the input array size. from typing import List class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: possiblePlacements = 0 if len(flowerbed) == 1: if flowerbed[0] == 0: return n <= 1 else: return n == 0 for index, flower in enumerate(flowerbed): if index == len(flowerbed) - 1: if flower == 0 and flowerbed[index-1] == 0: possiblePlacements += 1 break if index == 0: if flower == 0 and flowerbed[index+1] == 0: possiblePlacements += 1 flowerbed[index] += 1 continue if flower == 0 and flowerbed[index-1] == 0 and flowerbed[index+1]== 0: possiblePlacements+= 1 flowerbed[index] = 1 if n <= possiblePlacements: return True return False
# Source: https://leetcode.com/problems/search-insert-position/ # Level: Easy # Date: 13th July 2019 # Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. # # You may assume no duplicates in the array. # # Example 1: # # Input: [1,3,5,6], 5 # Output: 2 # Example 2: # # Input: [1,3,5,6], 2 # Output: 1 # Example 3: # # Input: [1,3,5,6], 7 # Output: 4 # Example 4: # # Input: [1,3,5,6], 0 # Output: 0 from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left = 0 right = len(nums) - 1 while True: middle = int((left + right) / 2) if target == nums[middle]: return middle if target < nums[middle]: right = middle - 1 if right < 0: return 0 if target > nums[right]: return right + 1 if target > nums[middle]: left = middle + 1 if left >= len(nums): return left if target < nums[left]: return left
# Source: https://leetcode.com/problems/odd-even-linked-list/ # Level: Medium # Date: 24th July 2019 # Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are # talking about the node number and not the value in the nodes. # # You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. # # Example 1: # # Input: 1->2->3->4->5->NULL # Output: 1->3->5->2->4->NULL # Example 2: # # Input: 2->1->3->5->6->4->7->NULL # Output: 2->3->6->7->1->5->4->NULL # Note: # # The relative order inside both the even and odd groups should remain as it was in the input. # The first node is considered odd, the second node even and so on ... # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head): if head is None or head.next is None: return head oddNode = head evenNode = head.next firstEven = evenNode while True: if oddNode.next is None or oddNode.next.next is None: break else: newOdd = oddNode.next.next oddNode.next = newOdd oddNode = newOdd if evenNode.next is None or evenNode.next.next is None: break else: newEven = evenNode.next.next evenNode.next = newEven evenNode = newEven oddNode.next = firstEven evenNode.next = None return head
''' Source: https://leetcode.com/problems/longest-palindrome/ Level: Easy Date: 06th July 2019 ''' ''' Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. ''' class Solution: def longestPalindrome(self, stringInput): hashTable = {} for element in stringInput: hashTable[element] = hashTable.get(element, 0) + 1 output = 0 possible = False for element in hashTable: value = hashTable[element] if value % 2 == 0: output += value else: output += (2*(value//2)) possible = True if possible: output += 1 return output
# Source: https://leetcode.com/problems/set-mismatch/ # Level: Easy # Date: 13th July 2019 # The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in # the set got duplicated to another number in the set, which results in repetition of one number and loss of another # number. # # Given an array nums representing the data status of this set after the error. Your task is to firstly find the # number occurs twice and then find the number that is missing. Return them in the form of an array. # # Example 1: # Input: nums = [1,2,2,4] # Output: [2,3] # Note: # The given array size will in the range [2, 10000]. # The given array's numbers won't have any order. from typing import List class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: hashMap = {} highestNumber = len(nums) for num in nums: if hashMap.get(num) is not None: duplicate = num hashMap[num] = 1 for num in range(1, highestNumber+1): if num not in hashMap: missing = num break return [duplicate, missing]
# Source: https://leetcode.com/problems/ugly-number/ # # Date: 17th August 2019 """ Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example 1: Input: 6 Output: true Explanation: 6 = 2 × 3 Example 2: Input: 8 Output: true Explanation: 8 = 2 × 2 × 2 Example 3: Input: 14 Output: false Explanation: 14 is not ugly since it includes another prime factor 7. Note: 1 is typically treated as an ugly number. Input is within the 32-bit signed integer range: [−231, 231 − 1]. """ # Solution class Solution: def isUgly(self, num: int) -> bool: if num == 1: return True ugly = [1] t1, t2, t3 = 0, 0, 0 while ugly[-1] < num: # print(t1, t2, t3) u1 = 2 * ugly[t1] u2 = 3 * ugly[t2] u3 = 5 * ugly[t3] umin = min(u1, u2, u3) if umin == num: return True if umin == u1: t1 += 1 if umin == u2: t2 += 1 if umin == u3: t3 += 1 ugly.append(umin) return False
# Source: https://leetcode.com/problems/average-of-levels-in-binary-tree/ # Level: Easy # Date: 28th July 2019 """ Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. Note: The range of node's value is in the range of 32-bit signed integer. """ # Solution # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: currentNode = root queue = [currentNode] output = [] while len(queue) > 0: currentSum = 0 currentCount = 0 currentLevel = [] while len(queue) > 0: currentNode = queue.pop(0) if currentNode.left is not None: currentLevel.append(currentNode.left) if currentNode.right is not None: currentLevel.append(currentNode.right) currentSum += currentNode.val currentCount += 1 queue = currentLevel output.append(currentSum / currentCount) return output
# Source: https://leetcode.com/problems/brick-wall/ # Level: Medium # Date: 21st July 2019 # There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the # same height but different width. You want to draw a vertical line from the top to the bottom and cross the least # bricks. # # The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each # brick in this row from left to right. # # If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how # to draw the line to cross the least bricks and return the number of crossed bricks. # # You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously # cross no bricks. # # # # Example: # # Input: [[1,2,2,1], # [3,1,2], # [1,3,2], # [2,4], # [3,1,2], # [1,3,1,1]] # # Output: 2 # # Explanation: # # # # Note: # # The width sum of bricks in different rows are the same and won't exceed INT_MAX. The number of bricks in each row # is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won't exceed # 20,000. from typing import List class Solution: def leastBricks(self, walls: List[List[int]]) -> int: hashMap = {} totalWidth = sum(walls[0]) for wall in walls: currentSum = 0 for index, num in enumerate(wall): currentSum += num if currentSum == totalWidth: break hashMap[currentSum] = hashMap.get(currentSum, 0) + 1 if not len(hashMap): return len(walls) maxSize = float('-inf') for size in hashMap: if hashMap[size] > maxSize: maxSize = hashMap[size] return len(walls) - maxSize
#!/usr/bin/env python # HW06_ex09_05.py # (1) # Write a function named uses_all that takes a word and a string of required # letters, and that returns True if the word uses all the required letters at # least once. # - write uses_all # (2) # How many words are there that use all the vowels aeiou? How about # aeiouy? # - write functions(s) to assist you # - # of words that use all aeiou: # - # of words that use all aeiouy: ############################################################################## # Imports # Body def uses_all(word, letters): """Fuction to test if a string contains all of the required letters""" for char in letters: if char not in word: return False return True def how_many_words(fin, letters): count = 0 for word in fin: if uses_all(word, letters): count += 1 return count ############################################################################## def main(): print "Words that use all aeiou: " + str(how_many_words(open("words.txt"),"aeiou")) print "Words that use all aeiouy: " + str(how_many_words(open("words.txt"),"aeiouy")) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- # @Time : 2021/10/19 14:33 # @Author : Ruby # @FileName: 603random.py # @Software: PyCharm price = 12 # 每次乘车票价 days = 22 # 每月乘车天数 times = 2 # 每天乘车次数 MountCost = 0 # 累计消费 # range 会产生从1开始到 days*times + 1 之间的连续整数 for i in range(1, days*times + 1): # f+{} 打印变量 print(f'第{i}天') if MountCost < 100: MountCost = price + MountCost elif MountCost < 150: MountCost = price * 0.8 + MountCost elif MountCost < 300: MountCost = price * 0.5 + MountCost else: MountCost = MountCost + price print(f'当前累计消费{MountCost}') print(MountCost)
from random import randint my_crazy_list = [randint(10, 20) for i in range(10)] print(my_crazy_list) for i in range(1, len(my_crazy_list)): if my_crazy_list[i] > my_crazy_list[i - 1]: print(my_crazy_list[i])
#!/usr/bin/python3 """test the airbnb project""" import unittest from models.place import Place A = Place() class TestClassMethods(unittest.TestCase): """test the Airbnb project""" def test_State_Place(self): self.assertEqual(type(A.city_id), str) self.assertEqual(type(A.user_id), str) self.assertEqual(type(A.name), str) self.assertEqual(type(A.description), str) self.assertEqual(type(A.number_rooms), int) self.assertEqual(type(A.number_bathrooms), int) self.assertEqual(type(A.max_guest), int) self.assertEqual(type(A.price_by_night), int) self.assertEqual(type(A.latitude), float) self.assertEqual(type(A.longitude), float) self.assertEqual(type(A.amenity_ids), list)
''' Created on Mar 1, 2013 @author: Jimmy ''' def countall(words): firstLetters = [w[0].lower() for w in words] print firstLetters alliterations = 0 for i in range(0,len(firstLetters)): if len(firstLetters) == 1: return 0 if i > 0 and i != len(firstLetters) - 1: if firstLetters[i] == firstLetters[i-1] and firstLetters[i] != firstLetters[i+1]: alliterations += 1 if i == len(firstLetters) - 1 and firstLetters[i] == firstLetters[i-1]: alliterations += 1 return alliterations
''' Created on Feb 23, 2012 @author: ola ''' import Tools, random, operator, copy _DEBUGisON = False def change_knowledge(guess, secret, knowledge): """ Changes the knowledge that is shown to the player For example changes _ e _ _ e to t e _ _ e when t is guessed. """ for i, ch in enumerate(secret): if ch == guess and knowledge[i] == '_': knowledge[i] = ch return knowledge def display(guesses, knowledge): """ This function print information to the human player. """ print "Guesses so far:", guesses print "Your knowledge so far:" print ' '.join(knowledge) def play_game(): global _DEBUGisON while True: try: sec_length = int(raw_input("Please enter the number of letters you would like in your word:")) whole_list = Tools.get_words("lowerwords.txt", sec_length) secret = random.choice(whole_list) break except ValueError: print "Please enter a valid number." except IndexError: print "Sorry there are no words of that length. Please try another number." knowledge = ["_"] * len(secret) guesses = [] # letters guessed so far misses = 0 # misses made so far while True: try: misses_allowed = int(raw_input("Please enter the number of guesses you would like:")) if misses_allowed > 0 and misses_allowed < 27: break else: print "Please enter a number between 1 and 26." except ValueError: print "Please enter a valid number." while misses < misses_allowed: display(guesses, knowledge) print "Guesses left: ", misses_allowed - misses if _DEBUGisON: print " (Secret word is", secret.upper(), ")" + " # words possible:",len(whole_list) while True: try: guess = raw_input("Please guess a letter:").lower() if guess in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']: pass if guess not in guesses: break else: print "" print "You already guessed that!" display(guesses, knowledge) else: print "" print "Please enter a valid letter." display(guesses, knowledge) except None: pass print "" new_whole_list = [] new_whole_list2 = [] d = {} for word in whole_list: if guess in word: new_whole_list.append(word) if guess not in word: new_whole_list2.append(word) if len(new_whole_list) > len(new_whole_list2): knowledgeCopy = knowledge[:] for word in new_whole_list: for i in range(0, sec_length): if word[i] == guess: knowledgeCopy[i] = guess d["".join(knowledgeCopy)] = d.get("".join(knowledgeCopy), []) d.get("".join(knowledgeCopy), []).append(word) knowledgeCopy = knowledge[:] new_whole_list = sorted(d.items(), key=lambda x: len(x[1]), reverse=True)[0][1] if len(new_whole_list) > len(new_whole_list2): print "You guessed a letter!" whole_list = new_whole_list secret = random.choice(whole_list) knowledge = change_knowledge(guess, secret, knowledge) else: print "Sorry, there are no " + guess + "'s." misses = misses + 1 whole_list = new_whole_list2 secret = random.choice(whole_list) guesses.append(guess) if not '_' in knowledge: print "Congratulations. You guessed my word:",secret break if misses == misses_allowed: print "Game over. You lose. The secret word was", secret + "." break if __name__ == '__main__': play_game()
''' Created on Jan 31, 2013 @author: Jimmy ''' def reverse(dna): reverselist = [] result = "" for i in range(0,len(dna)): reverselist.append(dna[i]) reverselist.reverse() for i in range(0,len(reverselist)): result += reverselist[i] return result
def get_second_lowest_score(sorted_records): idx = 0 for _ in sorted_records: if idx > 0: if sorted_records[idx - 1][1] != sorted_records[idx][1]: return sorted_records[idx][1] idx += 1 return 0 studentRecords = [] for _ in range(int(input())): name = input() score = float(input()) studentRecords.append([name, score]) sorted_records = sorted(studentRecords, key=lambda l: l[1], reverse=False) second_lowest_score = get_second_lowest_score(sorted_records) for x in reversed(sorted_records): if x[1] == second_lowest_score: print(x[0])
################################################## # This script shows an example of a header section. This sections is a group of commented lines (lines starting with # the "#" character) that describes general features of the script such as the type of licence (defined by the # developer), authors, credits, versions among others ################################################## # ################################################## # Author: Marta Galdys # Copyright: Copyright 2020, IAAC # Credits: [Institute for Advanced Architecture of Catalonia - IAAC, Advanced Architecture group] # License: Apache License Version 2.0 # Version: 1.0.0 # Maintainer: Diego Pajarito # Email: marta.maria.galdys@students.iaac.net # Status: development ################################################## # End of header section city_name = 'Bielsko-Biala' country = 'Poland' city_area = 125 city_population = 171000 city_density = city_population/city_area print ('My city name is '+ city_name) print (city_name + ' is located in ' + country) print ('The area of the city is: ' + str(city_area) + 'km²') print ('The number of inhabitants is: ' + str(city_population)) print ('\n') print('Population Density:' + str(city_density) + ' inhabitants per km²' ) print ('\n') mayor_of_city ='Jaroslaw Klimaszewski' print ('The mayor of the city Bielsko-Biala is: ' + mayor_of_city) print ('\n') highest_elevation = 1117 lowest_elevation = 262 elevation_difference= highest_elevation - lowest_elevation print('The highest elevation is: ' +str(highest_elevation) ) print('The lowest elevation is: ' +str(lowest_elevation) ) print('Elevation difference:') print( str(elevation_difference) + 'm')
# mean # The mean tool computes the arithmetic mean along the specified axis. # import numpy # my_array = numpy.array([ [1, 2], [3, 4] ]) # print numpy.mean(my_array, axis = 0) #Output : [ 2. 3.] # print numpy.mean(my_array, axis = 1) #Output : [ 1.5 3.5] # print numpy.mean(my_array, axis = None) #Output : 2.5 # print numpy.mean(my_array) #Output : 2.5 # By default, the axis is None. Therefore, it computes the mean of the flattened array. # var # The var tool computes the arithmetic variance along the specified axis. # import numpy # my_array = numpy.array([ [1, 2], [3, 4] ]) # print numpy.var(my_array, axis = 0) #Output : [ 1. 1.] # print numpy.var(my_array, axis = 1) #Output : [ 0.25 0.25] # print numpy.var(my_array, axis = None) #Output : 1.25 # print numpy.var(my_array) #Output : 1.25 # By default, the axis is None. Therefore, it computes the variance of the flattened array. # std # The std tool computes the arithmetic standard deviation along the specified axis. # import numpy # my_array = numpy.array([ [1, 2], [3, 4] ]) # print numpy.std(my_array, axis = 0) #Output : [ 1. 1.] # print numpy.std(my_array, axis = 1) #Output : [ 0.5 0.5] # print numpy.std(my_array, axis = None) #Output : 1.11803398875 # print numpy.std(my_array) #Output : 1.11803398875 # By default, the axis is None. Therefore, it computes the standard deviation of the flattened array. # Task # You are given a 2-D array of size N X M. # Your task is to find: # The mean along axis # The var along axis # The std along axis # Input Format # The first line contains the space separated values of N and M. # The next lines contains space separated integers. # Output Format # First, print the mean. # Second, print the var. # Third, print the std. # Sample Input # 2 2 # 1 2 # 3 4 # Sample Output # [ 1.5 3.5] # [ 1. 1.] # 1.11803398875 import numpy numpy.set_printoptions(legacy='1.13') N,M=map(int,input().split()) my_array=numpy.array([list(map(int,input().split())) for i in range(N)]) print (numpy.mean(my_array, axis = 1)) print (numpy.var(my_array, axis = 0)) print (numpy.std(my_array))
import random def rolls (): counter = 1 all_rolls = [] while counter == 1: var1 = random.randint(1,6) var2 = random.randint(1,6) var3 = random.randint(1,6) all_rolls += [((var1 , var2, var3))] if var1 > var2 > var3 or var2 > var3 > var1 or var3 > var2 > var1 or var2 > var1 > var3 or var3 > var1 > var2 or var1 > var3 > var2: print (var1, var2, var3) print 'you win' gumbo = raw_input ('again ') counter = 1 if "yes or no": if gumbo == 'yes': counter = 1 if gumbo =='no': counter = 0 print (all_rolls) else: print (var1,var2,var3) counter = 0 gumbo = raw_input ('again ') if "yes or no": if gumbo =='yes': counter = 1 if gumbo == 'no': counter = 0 print all_rolls
from __future__ import print_function import random def guess(): secret = random.randint(1, 20) print('I have a number between 1 and 20.') while True: guess = int(raw_input('Guess: ')) if guess != secret: print('Wrong, not my number') if guess > secret: print ('too high') if guess < secret: print ('too low') else: print('Right, my number is', guess, end='!\n') break
""" Advent of Code 2020 - Day 10 Pieter Kitslaar """ from pathlib import Path from collections import Counter from functools import reduce example_a = """\ 16 10 15 5 1 11 7 19 6 12 4""" def parse(txt): values = list(map(int, txt.splitlines())) values.sort() return values def compute_diffs(txt): values = parse(txt) values.append(max(values)+3) prev = 0 differences = [] for v in values: differences.append(v - prev) prev = v return differences def compute_combinations(differences): """ Here we compute the number of consecutive '1' difference. Each number of consecutive '1's can be substituted for a number of combinations of 1,2 and 3 jolt difference adapters. These can be easily used to define a multiplier for each of these difference groups which when multiplied provide the total number of combinations. 2: 1,1 => 2 2 3: 1,1,1 => 4 1,2 2,1 3 4: 1,1,1,1 => 7 2,1,1 2,2 1,2,1 1,1,2 3,1 1,3 """ prev_diff = 0 diff_runs = [] for d in differences: if d == 1: if d != prev_diff: diff_runs.append(1) else: diff_runs[-1] += 1 prev_diff = d diff_runs = [dr for dr in diff_runs if dr > 1] # see doc string multiplier = {1:1, 2:2, 3:4, 4:7} return reduce(lambda a,b:a*multiplier[b],diff_runs, 1) def test_example_a(): differences = compute_diffs(example_a) diff_count = Counter(differences) assert(diff_count[1] == 7) assert(diff_count[3] == 5) num_combinations = compute_combinations(differences) assert(8 == num_combinations) example_b = """\ 28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3""" def test_example_b(): differences = compute_diffs(example_b) diff_count = Counter(differences) assert(diff_count[1] == 22) assert(diff_count[3] == 10) num_combinations = compute_combinations(differences) assert(19208 == num_combinations) def get_input(): with open(Path(__file__).parent / 'input.txt', 'r') as f: return f.read() def test_puzzle(): differences = compute_diffs(get_input()) diff_count = Counter(differences) answer = diff_count[1]*diff_count[3] print('Part 1:', answer) assert(1980 == answer) num_combinations = compute_combinations(differences) print('Part 2:', num_combinations) assert(4628074479616 == num_combinations) if __name__ == "__main__": test_example_a() test_example_b() test_puzzle()
""" Advent of Code 2020 - Day 21 Pieter Kitslaar """ from pathlib import Path example="""\ mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish)""" def parse(txt): foods = [] for line in txt.splitlines(): ingredients_txt, _, contains_txt = line.partition('(contains') ingredients = set([i.strip() for i in ingredients_txt.split()]) known_allergens = set([a.strip() for a in contains_txt[:-1].split(',')]) foods.append({'ingredients': ingredients, 'allergens': known_allergens}) return foods def solve1(food_list): all_ingredients = set([i for f in food_list for i in f['ingredients']]) all_allergens = set([a for f in food_list for a in f['allergens']]) # Find all possible options by looping over all # ingredients and assume they contain the allergen # if the allergen is mentioned in a food, than # it should contain the ingredient ingredient_to_allergen_options = {} for ing in all_ingredients: options = ingredient_to_allergen_options[ing] = {} for allergen in all_allergens: this_option = options[allergen] = [] found_mismatch = False # assume ing contains allergen # so if the allergen is listed, the ingredient should be # in the list for i, f in enumerate(food_list): if allergen in f['allergens'] and ing not in f['ingredients']: found_mismatch = True this_option.clear() break else: this_option.append(i) # Find ingredients that don't have any allergen option non_allergens = set() for ing, options in ingredient_to_allergen_options.items(): if all(len(o)==0 for o in options.values()): non_allergens.add(ing) # compute how often this 'non_allergen' ingredients are mentioned num_times = 0 for f in food_list: this_non_allergens = f['ingredients'].intersection(non_allergens) num_times += len(this_non_allergens) return num_times, non_allergens def solve2(food_list, non_allergens): # remove non_allergens for f in food_list: f['ingredients'] = f['ingredients'] - non_allergens # Keep looping over all ingredient options # and keep removing options that are not possible # After each search find ingredients with only a single # options and store this in the 'known_ingredients'. # Next clear the known ingredients and allergens from the # food list. Continue until all options have been found. known_ingredients = {} removed_options = True while removed_options: removed_options = False ingredient_options = {} for f in food_list: for ing in f['ingredients']: ingredient_options.setdefault(ing, set()).update(f['allergens']) for ing, options in ingredient_options.items(): non_options = set() for opt in options: # assum for f in food_list: if opt in f['allergens'] and ing not in f['ingredients']: #print(ing, "is NOT", opt) non_options.add(opt) for opt in non_options: options.remove(opt) for ing, opt in ingredient_options.items(): if len(opt) == 1: known_ingredients[ing] = list(opt)[0] removed_options = True known_ing_names = set(known_ingredients) known_allergen_names = set(known_ingredients.values()) new_food_list = [] for f in food_list: new_ing = f['ingredients'] - known_ing_names if new_ing: new_allerg = f['allergens'] - known_allergen_names new_food_list.append({'ingredients': new_ing, 'allergens': new_allerg}) food_list = new_food_list sorted_ingredients = [t[0] for t in sorted(known_ingredients.items(), key=lambda t: t[1])] return ",".join(sorted_ingredients) def test_example(): food_list = parse(example) answer, non_allergens = solve1(food_list) assert(5 == answer) answer2 = solve2(food_list, non_allergens) assert("mxmxvkd,sqjhc,fvjkl" == answer2) def get_input(name='input.txt'): with open(Path(__file__).parent / name, 'r') as f: return f.read() def test_puzzle(): food_list = parse(get_input()) answer, non_allergens = solve1(food_list) print('Part 1:', answer) assert(1958 == answer) answer2 = solve2(food_list, non_allergens) print('Part 2:', answer2) assert("xxscc,mjmqst,gzxnc,vvqj,trnnvn,gbcjqbm,dllbjr,nckqzsg" == answer2) if __name__ == "__main__": test_example() test_puzzle()
import random x=22/7 print(x) suit = ("hearts" , "diamonds" , "spades" , "clubs") value = ("two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" , "ten" , "jack" , "queen" , "king" , "ace") val = {"two" : 2 , "three" : 3 , "four" : 4 , "five" : 5 , "six" : 6 , "seven" : 7 , "eight" : 8 , "nine" : 9 , "ten" : 10 , "jack" : 10 , "queen" : 10 , "king" : 10 , "ace" : 11} cards = [ ] class Card ( ) : suit = "" value = 0 def __init__(self , suit , value) : self.suit = suit self.value = value def __str__(self) : return self.suit + " " + str ( self.value ) for i in suit : for j in value : cards.append ( Card ( i , val [ j ] ) ) def play_again(): pl=input("Want to play again y/n? : ") if(pl=="y"): return True else: return False def play_the_game(chp) : chip=chp print("You have {} chips ".format(chip)) print() if chip==0: yn=input("You have no chip left, want to reset? y/n : ") if yn=="y": chip=100 else: print("No? Do you want to play without chip? No chip No game ") print() exit(0) bet=int(input("How much do you want to bet? : ")) while bet>chip: print("You don't have enough chip ") print() bet=int(input("How much do you want to bet? : ")) player = cards.pop ( ) print ( "Player card " + str ( player.suit ) ) print() print ( "Card points " + str ( player.value ) ) print() count_player = player.value player = cards.pop ( ) print ( "Player card " + str ( player.suit ) ) print() print ( "Card points " + str ( player.value ) ) print("-------------------------------------------") count_player = count_player + player.value print ( "Player points " + str ( count_player ) ) print("-------------------------------------------") computer = cards.pop ( ) print ( "Computer card " + str ( computer.suit ) ) print() print ( "Card value " + str ( computer.value ) ) print("-------------------------------------------") count_comp = computer.value print ( "Computer points " + str ( count_comp ) ) print("-------------------------------------------") play = True while play==True: count=0 move=input("Enter your move : hit/stop : ") print() while move=="hit": player = cards.pop ( ) count_player = count_player + player.value print ( "Player card " + str ( player.suit ) ) print() print ( "Card points " + str ( player.value ) ) print("-------------------------------------------") print ( "Player points " + str ( count_player ) ) print("-------------------------------------------") if count_player==21: print("Player won") print() chip=chip+bet print("You have now {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) elif count_player>21: print("Player lose") print() chip=chip-bet print("You have now {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) move=input("Enter your move : hit/stop : ") print() if count>0: if count_player>count_comp: print("player won") print() chip=chip+bet print("You have now {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) computer=cards.pop() print ( "Computer card " + str ( computer.suit ) ) print() print ( "Card value " + str ( computer.value ) ) print("-------------------------------------------") count_comp = count_comp+computer.value print ( "Computer points " + str ( count_comp ) ) print("-------------------------------------------") count=count+1 while count_comp<17: computer=cards.pop() print ( "Computer card " + str ( computer.suit ) ) print() print ( "Card value " + str ( computer.value ) ) print("-------------------------------------------") if computer.value==11: if count_comp+computer.value <=21: count_comp = count_comp+computer.value else: count_comp = count_comp+1 else: count_comp = count_comp+computer.value print ( "Computer points " + str ( count_comp ) ) print("-------------------------------------------") if count_comp==21: print("computer won") print() chip=chip-bet play=play_again() if play==False: exit(0) else : play_the_game(chip) elif count_comp>21: print("computer lose") print() chip=chip+bet print("You have now {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) elif count_comp>count_player: print("computer won") print() chip=chip-bet print("You have now {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) elif count_comp<count_player: print("Player won") print() chip=chip+bet print("You have now {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) elif count_comp==count_player: print("It's a tie! You still have {} chips ".format(chip)) print() play=play_again() if play==False: exit(0) else : play_the_game(chip) class Implement(): chip=100 random.shuffle ( cards ) play_the_game(chip) t = Implement()
# ---------------------------------------------------PROBLEM STATEMENT------------------------------------------------------------------ # # # You visit a doctor on a date given in the format yyyy:mm:dd. Your doctor suggests you to take pills every alternate day # starting from that day. You being a forgetful person are pretty sure wont be able to remember the last day you took the medicine # and would end up in taking the medicines on wrong days. So you come up with the idea of taking medicine on the dates whose day # is odd or even depending on whether dd is odd or even. Calculate the number of pills you took on right time before messing # up for the first time. # # Note: # Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; # the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; # the year 2000 is a leap year. def get_day(month): if month==1:return 31 elif month == 2 : if year%4==0: return 29 else: return 28 elif month == 3 : return 31 elif month == 4 : return 30 elif month == 5 : return 31 elif month == 6 : return 30 elif month == 7 : return 31 elif month == 8 : return 31 elif month == 9 : return 30 elif month == 10 : return 31 elif month == 11 : return 30 elif month == 12 : return 31 t = int(input("Number of test cases : ")) while t>=1: date = input("Enter in format yyyy:mm:dd : ") date = date.split(":") year = int(date[0]) month = int(date[1]) day_of_med = int(date[2]) no_of_days=0 med_count=0 while True: till_day = get_day(month) cur_day=0 for i in range(day_of_med,till_day+1,2): cur_day=i med_count+=1 if day_of_med%2==0: day_of_med=2 if month!=12: month+=1 else: month=1 if(2+(till_day-cur_day)==2): pass else: break; else: day_of_med=1 if month!=12: month+=1 else: month=1 if(1+(till_day-cur_day)==2): pass else: break; print(med_count) t-=1
''' This program let one compute all different parameters of the credit. This program calculate the annuity payment which are fixed during the whole credit term, and the differentiated payment where the part of reducing the credit prinsipal is constant. Also the interest repayment part of the credit calculator, it reduces under the credit term. Asking the user which parameter it wanna use from calculating the count of periods, monthly payment or credit payment. When choosing an option, the user need to fill inn the remaining values such as; credit principal, monthly payment, credit interest, count of periods and interest. And compute and output the value the user wanted credit principal is the original money on the credit, while the interest is a charge for borrowed money. ''' import math import argparse import sys # Initialize the parser parser = argparse.ArgumentParser(description="Credit Calculator") # Add the parameters or optional: parser.add_argument("--type", help= " choose between 'annuity' or 'diff'(differentiated) payment") parser.add_argument("--payment", help= "monthly payment", type=int) parser.add_argument("--principal", help= "calculation of both types e.g the total loan", type=int) parser.add_argument("--periods", help= "denotes the number of months/or years needed to repay", type=int) parser.add_argument("--interest", help= "convert the interest rate into a float", type=float) args = parser.parse_args() arguments = len(sys.argv) - 1 if arguments != 4: print("Incorrect parameters") elif args.type not in ("diff", "annuity"): print("Incorrect parameters") elif args.type is None: print("Incorrect parameters") elif args.type == 'diff' and args.payment != None: print('Incorrect Parameters') elif (args.payment or args.principal or args.periods or args.interest) <= 0: print("Incorrect parameters") elif arguments != 4: print("Incorrect parameters") elif args.type == "diff": if args.principal is None or args.periods is None or args.interest is None: print("Incorrect parameters") elif args.periods < 0: print("Incorrect parameters") elif args.payment is not None: print("Incorrect parameters") else: nominal_interest_rate = args.interest / (12 * 100) differentiated_payments = [] for month in range(1, args.periods + 1): d = math.ceil((args.principal / args.periods) + nominal_interest_rate * (args.principal - args.principal * (month - 1) / args.periods)) differentiated_payments.append(d) print(f"Month {month}: paid out {d}") overpayment = int(sum(differentiated_payments) - args.principal) print() print(f"Overpayment = {str(math.ceil(overpayment))}") elif args.type == "annuity": if (args.principal is None or args.periods is None or args.interest is None) and args.payment is None: print("Incorrect parameters") else: if args.payment is not None and args.periods is not None and args.interest is not None: nominal_interest_rate = args.interest / (12 * 100) annuity_payment = args.payment / ((nominal_interest_rate * (1 + nominal_interest_rate) ** args.periods) / (((1 + nominal_interest_rate) ** args.periods) - 1)) overpayment = args.payment * args.periods - annuity_payment print(f"Your credit principal = {str(math.floor(annuity_payment))}!") print(f"Overpayment = {str(math.ceil(overpayment))}") elif args.principal is not None and args.periods is not None and args.interest is not None: nominal_interest_rate = args.interest / (12 * 100) annuity_payment = args.principal * ((nominal_interest_rate * (1 + nominal_interest_rate) ** args.periods) / (((1 + nominal_interest_rate) ** args.periods) - 1)) overpayment = (math.ceil(annuity_payment) * args.periods) - args.principal print(f"Your annuity payment = {str(math.ceil(annuity_payment))}!") print(f"Overpayment = {str(math.ceil(overpayment))}") elif args.principal is not None and args.interest is not None and args.payment is not None: nominal_interest_rate = args.interest / (12 * 100) count_of_periods = math.ceil(math.log(args.payment / (args.payment - nominal_interest_rate * args.principal), 1 + nominal_interest_rate)) month_converter = count_of_periods % 12 year_converter = count_of_periods // 12 overpayment = int((math.ceil(count_of_periods) * args.payment) - args.principal) if year_converter >= 2 and month_converter >= 2: print(f"You need {str(year_converter)} years and {str(month_converter)} months to repay this credit") print(f"Overpayment = {str(math.ceil(overpayment))}") elif year_converter == 0: print(f"You need {str(month_converter)} months to repay this credit") print(f"Overpayment = {str(math.ceil(overpayment))}") elif year_converter >= 1 and month_converter == 0: print(f"You need {str(year_converter)} years to repay this credit") print(f"Overpayment = {str(math.ceil(overpayment))}") else: print(f"You need {str(year_converter)} year and {str(month_converter)} month to repay this credit") print(f"Overpayment = {str(math.ceil(overpayment))}")
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error data = pd.read_csv('C:/Users/nikhil.goyal/Desktop/itbodhi/LinerarRegdataset/student.csv') print(data.shape) data.head() math = data['Math'].values read = data['Reading'].values write = data['Writing'].values m = len(math) X = np.array([math, read]).T print(X[0]) Y = np.array(write) # Model Intialization reg = LinearRegression() # Data Fitting reg = reg.fit(X, Y) # Y Prediction Y_pred = reg.predict(X) # Model Evaluation rmse = np.sqrt(mean_squared_error(Y, Y_pred)) r2 = reg.score(X, Y) print("RMSE") print(rmse) print("R2 Score") print(r2) Nikhil=X.reshape(-1, 1)[0][0] print(reg.predict([[79,80]]))
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def toint(self, node): return node.val + 10 * self.toint(node.next) if node else 0 def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ num1 = num2 = '' head1 = l1 head2 = l2 while head1: num1 += str(head1.val) head1 = head1.next while head2: num2 += str(head2.val) head2 = head2.next sum = int(num1[::-1]) + int(num2[::-1]) sum = str(sum)[::-1] res = ListNode(sum[0]) head = res for i in range(1, len(sum)): head.next = ListNode(sum[i]) head = head.next return res l1 = ListNode(1) l1.next = ListNode(2) l2 = ListNode(4) l2.next = ListNode(5) print Solution().toint(l1) # res = Solution().addTwoNumbers(l1, l2) # head = res # while head: # print head.val # head = head.next
""" Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 """ # Definition for singly-linked list. import random class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1 or not l2: return l1 or l2 dummy = head = ListNode(0) while l1 and l2: if l1.val < l2.val: head.next = l1 l1 = l1.next else: head.next = l2 l2 = l2.next head = head.next head.next = l1 or l2 return dummy.next def mergeTwoLists_2(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: return l2 if not l2: return l1 res = head = l1 while l1 and l2: l1 = l1.next head.next = l2 if l2 else l1 l2 = l2.next head = head.next head.next = l1 if l1 else l2 head = head.next return res l1 = tmp1 = ListNode(0) l2 = tmp2 = ListNode(1) for i in range(1, 9): if i < 6: tmp1.next = ListNode(2*i) tmp1 = tmp1.next tmp2.next = ListNode(2*i+1) tmp2 = tmp2.next t = l1 while t: print t.val t = t.next print '#############' t = l2 while t: print t.val t = t.next print '#############' head = Solution().mergeTwoLists(l1, l2) while head: print head.val head = head.next
#PARA EXECUTAR O PROGRAMA NO TERMINAL BASTA DIGITAR: python3 main.py ''' Para o entendimento da lógica do programa é necessário que entenda-se o que está atribuido a algumas variáveis: "dicionario_pontuacao": associa as letras a seus valores; "banco_palavras": inicialmente é uma lista que representa o banco de palavras que foi fornecido na especificação, apenas está tratado para as palavras estarem em letras minúsculas e sem acentos (o código utilizado para o tratamento do banco também está disponível, contudo esse tratamento não é realizado aqui, pois, considerando que o banco de palavras é imutável, ganha-se performance ao executar esse tratamento em um código externo e apenas colar o resultado aqui. O código está no arquivo "converter_texto.py"). Esse banco, no entanto, é modificado através da função "modifica_banco_palavras" do módulo "modificacao_banco_palavras" e passa a ser um dicionário que tem como chave as palavras do banco_palavras original e, como valor, instâncias da classe "ValorBancoPalavras", também definida no módulo "modificacao_banco_palavras". Informações sobre essa função e essa classe estão disponíveis no módulo "modificacao_banco_palavras"; "letras_validas": dicionário que tem, como chave, as letras digitadas pelo usuário na rodada que são chaves válidas no "dicionario_pontuacao" e, como valor, o número de vezes que essas letras ocorrem. A lógica do programa se baseia em percorrer as palavras do banco de palavras e verificar se é possível formá-las com os caracteres inseridos pelo usuário. Essa verificação é feita utilizando-se dos caracteres únicos de cada palavra, assim como, quantos de cada um deles são necessários em uma palavra. Compare-se esses valores com as chaves da variável "letras_validas" e o valor associado a essas chaves, sendo uma palavra possível quando todos os seus caracteres únicos são chaves válidas para a variável "letras_validas" e o número de ocorrências desses caracteres é menor ou igual ao valor associado a "letras_validas" quando usa-se como chave para ela os respectivos caracteres. É IMPORTANTE RESSALTAR QUE NEM TODAS AS PALAVRAS DO BANCO TEM SEUS CARACTERES COMPARADOS E, TAMBÉM, QUE NÃO OBRIGATORIAMENTE TODOS OS CARACTERES DE UMA PALAVRA SERÃO COMPARADOS. Ignoram-se palavras com mais caracteres que o número máximo de caracteres validos na rodada e, ignoram-se também, palavras que tem pontuação de valor inferior ao da pontuação da(s) palavra(s) que no momento da iteração ocupam o lugar de melhor palavra. Além disso, as comparações entre os caracteres de uma palavra e dos caracteres disponiveis na rodada são interrompidas no caso de um caracter da palavra não estar presente na lista de letras da rodada, ou, quando esse caracter está presente, porém não em quantidade suficiente. A função responsável por percorrer o banco de palavras e identificar qual a melhor palavra é a função "calcula_melhor_palavra" do módulo "logica_melhor_palavra", para mais detalhes sobre essas exceções, por favor, acesse o módulo citado. A contagem dos pontos é feita, inicialmente, quando chama-se a função "modifica_banco_palavras". Para não ser necessário calcular a pontuação de uma palavra toda vez que ela for usada para uma comparação, a classe "ValorBancoPalavras" possui um campo responsável por armazenar a pontuação de cada palavra. Contudo, como foi implementado o artigo extra da especificação, "bônus de posição", a pontuação das palavras são recalculadas sempre que uma nova posição de pontuação bônus for definida pelo usuário e esse novo valor será armazenado pela variável "pontuacao" da classe "ValorBancoPalavras". ''' import string import tratamento_entrada import logica_melhor_palavra import modificacao_banco_palavras import printa_resultado dicionario_pontuacao = {"a" : 1, "b" : 3, "c" : 3, "d" : 2, "e" : 1, "f" : 5, "g" : 2, "h" : 5, "i" : 1, "j" : 8, "l" : 1, "m" : 3, "n" : 1, "o" : 1, "p" : 3, "q" : 13, "r" : 1, "s" : 1, "t" : 1, "u" : 1, "v" : 5, "x" : 8, "z" : 13} banco_palavras = ['abacaxi', 'manada', 'mandar', 'porta', 'mesa', 'dado', 'mangas', 'ja', 'coisas', 'radiografia', 'matematica', 'drogas', 'predios', 'implementacao', 'computador', 'balao', 'xicara', 'tedio', 'faixa', 'livro', 'deixar', 'superior', 'profissao', 'reuniao', 'predios', 'montanha', 'botanica', 'banheiro', 'caixas', 'xingamento', 'infestacao', 'cupim', 'premiada', 'empanada', 'ratos', 'ruido', 'antecedente', 'empresa', 'emissario', 'folga', 'fratura', 'goiaba', 'gratuito', 'hidrico', 'homem', 'jantar', 'jogos', 'montagem', 'manual', 'nuvem', 'neve', 'operacao', 'ontem', 'pato', 'pe', 'viagem', 'queijo', 'quarto', 'quintal', 'solto', 'rota', 'selva', 'tatuagem', 'tigre', 'uva', 'ultimo', 'vituperio', 'voltagem', 'zangado', 'zombaria', 'dor'] banco_palavras = modificacao_banco_palavras.modifica_banco_palavras(banco_palavras, dicionario_pontuacao) # O banco passa a associar as palavra com suas pontuações e a quantidade de cada letra única que as formam. # Mais informações sobre essa modificação podem ser obtidas acessando o módulo "modificacao_banco_palavras". print("---------------------------------------------------------------------------------") print("\nPara finalizar o programa digite 'SAIR' como as letras disponíveis na jogada.\n") print("---------------------------------------------------------------------------------\n") letras_rodada = input("Digite as letras disponíveis nesta jogada: ") posicao_bonus_antiga = 0 while (letras_rodada != "SAIR"): posicao_bonus = int(input("Digite a posição bônus: ")) if posicao_bonus_antiga != posicao_bonus: if posicao_bonus >= 0: posicao_bonus_antiga = posicao_bonus for palavra in banco_palavras: banco_palavras[palavra].set_pontuacao_bonus(palavra, dicionario_pontuacao, posicao_bonus) # Modifica a pontuação de cada palavra do banco de acordo com a posição bônus fornecida. elif posicao_bonus < 0: print("Posição inválida!") continue letras_validas, letras_nao_usadas, num_letras_validas = tratamento_entrada.trata_entrada(letras_rodada, dicionario_pontuacao) # Separa e formata a entrada da maneira necessária para ser usada no cálculo da melhor palavra. # Mais informações sobre esse tratamento estão disponíveis no módulo "tratamento_entrada" melhor_palavra = logica_melhor_palavra.calcula_melhor_palavra(banco_palavras, letras_validas, num_letras_validas) # Cálculo da melhor palavra possível é realizado aqui. Informações sobre o funcionamento desse função são encontradas # no módulo "logica_melhor_palavra". if melhor_palavra != '': printa_resultado.imprime_resultado(melhor_palavra, banco_palavras[melhor_palavra].pontuacao, letras_validas, letras_nao_usadas) else: print("\nNenhuma palavra encontrada.") print("Sobraram:", str.upper(letras_rodada)) print("\n---------------------------------------------------------------------------------\n") letras_rodada = input("Digite as letras disponíveis nesta jogada: ") if letras_rodada == "SAIR": print("Programa finalizado!")
from typing import List import random import sys def menu(entries : List) -> int: maxLen = len(entries) + 1 while True: print('\nMENU') print('----') for num, label in enumerate(entries): print(f'{num + 1:2} - {label}') print(' 0 - Quitter') try: choice = int(input('\nVotre choix :')) if choice < 0 or choice > maxLen: raise Exception() return choice except: print('Choix invalide !') def dice(n : int) -> int: print(f'Résultat : {random.randint(1, n)}') if __name__ == '__main__': print('Petit script de test !') while True: n = menu(('Lancer un D4', 'Lancer un D6', 'Lancer un D8', 'Lancer un D12', 'Lancer un D20')) if n == 0: print('Au revoir') sys.exit(0) if n == 1: dice(4) elif n == 2: dice(6) elif n == 3: dice(8) elif n == 4: dice(12) elif n == 5: dice(20)
import sqlite3 def schema(dbpath = "schema_designer.db"): with sqlite3.connect(dbpath) as connection: c = connection.cursor() #drop tables if they exist dropsql = "DROP TABLE IF EXISTS {};" for table in ["snacks", "students", "teachers", "classes", "class1"]: c.execute(dropsql.format(table)) #snacks table c.execute("""CREATE TABLE snacks ( pk INTEGER PRIMARY KEY AUTOINCREMENT, brand VARCHAR, type VARCHAR, price FLOAT, available_quantity INTEGER );""") #students and teachers table c.execute("""CREATE TABLE students ( pk INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR );""") c.execute("""CREATE TABLE teachers ( pk INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR );""") c.execute("""CREATE TABLE classes ( pk INTEGER PRIMARY KEY AUTOINCREMENT, class_num INTEGER, teachers_pk INTEGER, FOREIGN KEY(teachers_pk) REFERENCES teachers(pk) );""") c.execute("""CREATE TABLE class1 ( pk INTEGER PRIMARY KEY AUTOINCREMENT, student_pk INTEGER, classes_pk INTEGER, FOREIGN KEY(student_pk) REFERENCES students(pk), FOREIGN KEY(classes_pk) REFERENCES classes(pk), );""") #employees table c.execute("""CREATE TABLE employees ( pk INTEGER PRIMARY KEY AUTOINCREMENT, ssn VARCHAR(11), salary VARCHAR, phone_number VARCHAR(12) );""") c.execute("""CREATE TABLE departments ( pk INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, budget FLOAT );""") c.execute("""CREATE TABLE department1 ( pk INTEGER PRIMARY KEY AUTOINCREMENT, departments_pk INTEGER, employees_pk INTEGER FOREIGN KEY(departments_pk) REFERENCES departments(pk) FOREIGN KEY(employees_pk) REFERENCES employees(pk) );""") #subreddit c.execute("""CREATE TABLE reddit_users ( pk INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR );""") c.execute("""CREATE TABLE menu ( pk INTEGER PRIMARY KEY AUTOINCREMENT, subscribe BOOL, submit_a_post VARCHAR, submit_a_comment VARCHAR upvote_or_downvote BOOL );""") c.execute("""CREATE TABLE subreddit_member ( pk INTEGER PRIMARY KEY AUTOINCREMENT, reddit_users_pk INTEGER, FOREIGN KEY(reddit_users_pk) REFERENCES reddit_users(pk) );""") c.execute("""CREATE TABLE subreddit_posts ( pk INTEGER PRIMARY KEY AUTOINCREMENT, post VARCHAR, subreddit_member_pk INTEGER, votes INTEGER, comments VARCHAR, FOREIGN KEY (subreddit_member_pk) REFERENCES subreddit_member(pk) );""") #Art Gallery c.execute("""CREATE TABLE artist ( pk INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, birthplace VARCHAR, age INTEGER, style VARCHAR );""") c.execute("""CREATE TABLE artwork ( pk INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, artist_pk INTEGER, year_made INTEGER, type VARCHAR, price FLOAT, FOREIGN KEY (artisit_pk) REFERENCES artist(pk) );""") c.execute("""CREATE TABLE works by picasso ( pk INTEGER PRIMARY KEY AUTOINCREMENT, artwork_pk INTEGER FOREIGN KEY (artwork_pk) REFERENCES artwork(pk) );""")