text
stringlengths
37
1.41M
def items(x,y): return x*y print(items('gg',5)) first_list = [21,234,13,345,56,234,6,34,12] second_list = [234,13,235,123,56,23,1,6,12,56,123] def same_values(x,y): rezult = [] # local value for key in x: if key in y: rezult.append(key) rezult.sort() return(rezult) print(same_values(first_list,second_list)) # same res = [x for x in first_list if x in second_list] print(res)
import re my_text = 'This is my text, created by kindix' # find with match = re.match('This is my text, created by (.*)', my_text) #print(match.group(1)) my_list = [[1,2,3], [4,5,6], [7,8,9]] my_list.append(2) #print(my_list) #col2 = [] #for row in my_list: # col2 = row[1] #print(col2) diag = [] for i in range(3): diag = my_list[i][i] print(diag) #for word in my_text.split(' '): # print(word) a = {} for i in range(3): a = {i:my_list[i]} print(a) my_hesh = {'a': 1, 'b': 2, 'c': 3} my_keys = list(my_hesh.keys()) my_keys.sort() print(my_keys) for key in my_keys: print(key,'=>', my_hesh[key])
import curses from curses.textpad import Textbox, rectangle #make an input box for user to prompt when options are too long for command line #this uses the curses library that is only inclueded in linux so windows users will need to use alternatives #such as Cygwin class TextInput(object): @classmethod def show(cls, message, content=None): return curses.wrapper(cls(message, content)._show) def __init__(self, message, content): self._message = message self._content = content def _show(self, stdscr): #set reasonable size for input box lines, cols = curses.LINES - 10, curses.COLS - 40 y_begin, x_begin = (curses.LINES - lines) / 2, (curses.COLS - cols) / 2 editwin = curses.newwin(lines, cols, y_begin, x_begin) editwin.addsr(0, 1, "{}: Hit ctrl-G to submit)".format(self._message)) rectangle(editwin, 1, 0, lines-2, cols-1) editwin.refresh() inputwin = curses.newwin(lines-4, cols-2, y_begin+2, x_begin+1) box = Textbox(inputwin) self._load(box, self._content) return self._edit(box) def load(self, box, text): if not text: return for c in text: box._insert_printable_char(c) def _edit(self, box): while True: ch = box.win.getch() if not ch: continue if ch == 127: ch = curses.KEY_BACKSPACE if not box.do_command(ch): break box.win.refresh() return box.gather() if __name__ == "__main__": result = TextInput._show('enter your name', 'please') print(f'your name is {result}')
import requests from bs4 import BeautifulSoup a = '#' * 80 planet_url = "http://0.0.0.0/planets.html" html = requests.get(planet_url) soup = BeautifulSoup(html.text, "lxml") #print the html as string print(str(soup)[:100]) print(a) #navigate to the div element print(str(soup.html.body.div.table)[:100]) # retreive the first <tr> element print(a) print(str(soup.html.body.div.table.tr)) # Each node has both children and descendants. # Descendants are all the nodes underneath a given node # (event at further levels than the immediate children), while children are those that are a first level descendant. # The following retrieves the children of the table, which is actually a list_iterator object: print(a) print(soup.html.body.div.table.children) #we can create a list of all the children print(a) children = [str(c)[:45] for c in soup.html.body.div.table.children] print(children) for c in children: print('child:') print(c) # We can also get parent elements print(a) print(str(soup.html.body.div.table.tr.parent)[:200])
a = int(input("Give me a number 1")) b = int(input("Give me a number 2")) c = int(input("Give me a number 3")) if a+b > c and a+c > b and b+c > a: if a==b==c: print("This traingle is equilateral") elif a==b or a==c or b==c: print("This traingle is isosceles") else: print("This is traingle") else: print("I can't build traingle from this number")
class TV(): def __init__(self, inch, hz, fhd ): self.inch = inch self.hz = hz self.fhd = fhd def __str__(self): if self.fhd == True: return f"Your Tv has {self.inch}', {self.hz}Hz and is FullHd" else: return f"Your Tv has {self.inch}', {self.hz}Hz and isn't FullHd" def turn_on(self): return "Your TV is turn on" def turn_off(self): return "Your TV is turn off"
# ZADANKO 1 var = input("Give me 9 characters o or x") # sprawdzamy piony if var[0] == var[3] == var[6] or var[2] == var[5] == var[8]: print("WIN!!!!") # sprawdzam rząd elif var[0:3] =="xxx" or var[0:3] =="ooo" or var[3:6] =="xxx" or var[3:6] =="ooo" or var[6:9]=="xxx" or var[6:9]=="ooo": print("WIN!!!") #sprawdzam skos elif var[0] == var[4] == var[8] or var[2] == var[4] == var[6]: print("WIN") else: print("LOSE")
#Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. name = input("Give me your name") age = int(input("Give me your age")) lack = 100 - age year_when_user_100yearold = 2019 + (100 - age) print(f"{name} you will be 100 year old in {year_when_user_100yearold}")
# This program print the change from available coins: # available_coins: 5,2,1,0.5, 0.2, 0.1 change = float(input("How many change you have")) available_coins = [0.05, 5, 2, 1, 0.5, 0.2, 0.1] available_coins.sort(reverse=True) change_in_coins = [] while (change > 0.1): for coin in available_coins: if coin <= change: change_in_coins.append(coin) #Adding coin to the list for client change = change - coin break #without break it will not start from begging ask = input("Can I Keep the change?") if ask.lower() == 'no': change_in_coins.append(0.1) print(f"This is ypu change in coins: {change_in_coins}")
""" ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▀▀▀▀█░█▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌ ▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▄▄▄▄█░█▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ github: brandonskerritt """ import argparse from requests import get from collections import OrderedDict import links import title import words parser = argparse.ArgumentParser(description='Blog') parser.add_argument('-f','--file', help='Blog post as a .md [Markdown] file', required=False) parser.add_argument('-u','--url', help='Url of your blog [required for UTM tags]', required=False) parser.add_argument('-g','--ghost', help='Your ghost blogs content API', required=False) parser.add_argument('-c','--capitalselinks', help='Capitalise all links. You will be presented with each link and get to decide which ones to capitalise', required=False) parser.add_argument('-ct','--capitalsetitles', help='Capitalise all titles. You will be presented with each link and get to decide which ones to capitalise', required=False) args = vars(parser.parse_args()) if len(args) <= 1: print("error no arguments supplied. Use --help for help") exit(1) if args['ghost'] != None: # uses Ghost's content api to get the posts and parses them r = get("") responseJson = r.json() # creates an ordered dict of title: id so we can easily ask the user what post they want to edit titlesValue = {} for number, titles in enumerate(responseJson['posts']): titlesValue[titles['title']] = number titlesValue = OrderedDict(titlesValue) # just prints the ordered dict and makes it look pretty print("ID ---- Title") print("-------------") for k in titlesValue: print(titlesValue[k], " ---- ", k) whatBlogPost = int(input(("What blog post would you like to use? Enter it in the ID number "))) # gets the blog post title from the ID for title, num in titlesValue.items(): if whatBlogPost == num: titleOfPost = title z # TODO next: get the HTML info in and actually start editign this biatttchh :) if args['file'] != None: f = open("{}".format(args['file']), "r") text = f.read() f.close() newLinksobj = links.linksServant(text, mdorhtml="md", websiteurl="skerritt.blog") newLinksobj.getLinksMark() newLinksobj.addUTMTags() newLinksobj.check404() tc = title.titleServant(text, ) def mainCode(newLinksobj): newLinksobj.getLinksMark() newLinksobj.addUTMTags() newLinksobj.check404() if args['capitalselinks'] != None: print("yeet")
#!/usr/bin/env python3 """ Author : Johan Runesson <info@johanrunesson.se> Date : 2020-08-03 Purpose: Jump the Five """ import argparse # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Jump the Five', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('number', metavar='str', help='A number') return parser.parse_args() # -------------------------------------------------- def main(): """Start things up""" args = get_args() number = args.number jumper = { '1': '9', '2': '8', '3': '7', '4': '6', '5': '0', '6': '4', '7': '3', '8': '2', '9': '1', '0': '5' } for char in number: print(jumper.get(char, char), end='') print() # To get rid of the %-character at the end (not sure why it gets printed) # print(number.translate(number.maketrans(jumper))) # -------------------------------------------------- if __name__ == '__main__': main()
# Creating star pyramid print("Star pyramid\n") limit = int(input("Enter pyramid hight limit\n")) x = 0 y = 0 while x < limit: z = x while z < limit: print(" ", end="") z = z + 1 y = x while y >= 0: print("* ", end="") y = y - 1 print("\n") x = x + 1
# Here look for how to add unlimited arguments in python print("Unlimited Argument function in python") def names(*values): print("first value = " + values[0] + "\nSecond Value = " + str(values[1]) + "\nThird value = " + values[2]) names("Muhammed Ajmal y", 25, "Android Developer") x = 1 def jf(): print(x) # x = x + 1 This line is error in here i.e. cant assign global variable in functions same variable # Without argument order we can pass parameters def sample(a, b, c): print("first value : " + a + "\nSecond Value : " + b + "\nThird value :" + c) sample(b="Ajmal", a="Muhammed", c="Yousuf")
from collections import deque def bfs(node): queue = deque() visited = [] queue += node while len(queue) != 0: node = queue.popleft() if node not in visited: visited.append(node) queue += graph[node] print(node, "-") if __name__ == '__main__': graph = {} graph["A"] = ["B", "D"] graph["B"] = ["C", "D"] graph["C"] = ["F"] graph["D"] = ["E"] graph["E"] = ["C", "G"] graph["F"] = ["G"] graph["G"] = [] bfs("A")
class Matrix: """ A class used to represent a Matrix ... Attributes ---------- matrix_string : str string with embedded newlines like: "9 8 7\n5 3 2\n6 6 7" Methods ------- row(index) returns the number "index" row as a list of integers column(index) return the number "index" column as a list of integers """ def __init__(self, matrix_string): """ Parameters ---------- matrix_string : str The string rappresentig a matrix """ # splitting the string in double-levelled lists of string self.matrix_string = [row.split() for row in matrix_string.strip().split("\n")] def row(self, index): """ Parameters ---------- index : int The row number to be returned (1 --> first row) """ # converting each element of "index"th row to "int" and returning it as list return [int(j) for j in self.matrix_string[index - 1]] def column(self, index): """ Parameters ---------- index : int The column number to be returned (1 --> first column) """ # converting each "index"th element of each row in int and returning as list return [int(k[index - 1]) for k in self.matrix_string]
class Animal: def __init__(self, name): self.name = name # ABSTRACT METHOD def speak(self): raise NotImplementedError("Subclass must will implement this abstract method") class Dog(Animal): # ABSTRACT METHOD IS OVERRIDDEN HERE def speak(self): return self.name + " says woof" class Cat(Animal): # ABSTRACT METHOD IS OVERRIDDEN HERE def speak(self): return self.name + " says meow" myDog = Dog("Jimmy") print(myDog.speak()) myCat = Cat("Tom") print(myCat.speak())
import sqlite3 import sys #checking for wrong usage if len(sys.argv) != 2: print("Wrong usage") sys.exit() #getting the house name provided house = sys.argv[1] #connecting to our database db = sqlite3.connect("students.db") #the db.execute (as opposed to some documentation I read, returns a list of tuples) students = db.execute("SELECT * FROM students WHERE house = (?) ORDER BY last ASC, first ASC", (house,)) for student in students: #checking for the student's middle name if student[2] != None: print("{} {} {}, born {}".format(student[1], student[2], student[3], student[5])) else: print("{} {}, born {}".format(student[1], student[3], student[5])) db.close()
# A RouteTrie will store our routes and their associated handlers # A RouteTrieNode will be similar to our autocomplete TrieNode... with one additional element, a handler. import os class RouteTrieNode: def __init__(self, handler): # Initialize the node with children as before, plus a handler self.is_path = False self.handler = handler self.children = {} def insert(self, partpath): # Insert the node as before self.children[partpath] = RouteTrieNode() class RouteTrie: def __init__(self): # Initialize the trie with an root node and a handler, this is the root path or home page node self.handler = None self.root = RouteTrieNode(self.handler) def insert(self, path, handler): # Similar to our previous example you will want to recursively add nodes # Make sure you assign the handler to only the leaf (deepest) node of this path current_node = self.root for partpath in path: if partpath not in current_node.children: current_node.children[partpath] = RouteTrieNode(self.handler) current_node = current_node.children[partpath] current_node.is_path = True #current_node.is_handler = True current_node.handler = handler def find(self, path): # Starting at the root, navigate the Trie to find a match for this path # Return the handler for a match, or None for no match current_node = self.root for partpath in path: #print("1----") if partpath in current_node.children: current_node = current_node.children[partpath] else: return None #else: # print("2----") # return None return current_node.handler # The Router class will wrap the Trie and handle class Router: def __init__(self, handler): # Create a new RouteTrie for holding our routes # You could also add a handler for 404 page not found responses as well! #self.routerName = routerName self.routes = RouteTrie() self.handler = handler self.routes.insert("/", self.handler) def add_handler(self, route, handler): # Add a handler for a path # You will need to split the path and pass the pass parts # as a list to the RouteTrie path = self.split_path(route) self.routes.insert(path, handler) def lookup(self, route): # lookup path (by parts) and return the associated handler # you can return None if it's not found or # return the "not found" handler if you added one # bonus points if a path works with and without a trailing slash # e.g. /about and /about/ both return the /about handler path = self.split_path(route) handler = self.routes.find(path) return handler def split_path(self, route): # you need to split the path into parts for # both the add_handler and loopup functions # so it should be placed in a function here part_ret = [] partpath = route.split('/') for ijk in partpath: if ijk != '': part_ret.append(ijk) return part_ret # Here are some test cases and expected outputs you can use to test your implementation # create the router and add a route router = Router("root handler") #, "not found handler") # remove the 'not found handler' if you did not implement this router.add_handler("/home/about", "about handler") # add a route # some lookups with the expected output print(router.lookup("/")) # should print 'root handler' print(router.lookup("/home")) # should print 'not found handler' or None if you did not implement one print(router.lookup("/home/about")) # should print 'about handler' print(router.lookup("/home/about/")) # should print 'about handler' or None if you did not handle trailing slashes print(router.lookup("/home/about/me")) # should print 'not found handler' or None if you did not implement one r1 = Router("root 1") r1.add_handler("/home/markus/ubuntu/linux/OS/run", "Run Ubuntu") print("------------------------------------------------------") print(r1.lookup("/")) print(r1.lookup("/home")) print(r1.lookup("/home/markus")) print(r1.lookup("/home/markus/markus/ubuntu")) print(r1.lookup("/home/markus/ubuntu/linux/OS/run")) print(r1.lookup("/home/markus/ubuntu/linux/OS/run/")) r2 = Router("root 1") r2.add_handler("/home/markus/ubuntu", "Run Ubuntu") r2.add_handler("/home/markus/ubuntu/linux", "Run your Linux") r2.add_handler("/home/markus/ubuntu/linux/OS/run", "Run your OS") r2.add_handler("/home/markus/ubuntu/linux/OS/run", "Only Run") print("------------------------------------------------------") print(r2.lookup("/")) print(r2.lookup("/home")) print(r2.lookup("/home/markus")) print(r2.lookup("/home/markus/ubuntu")) print(r2.lookup("/home/markus/ubuntu/linux")) print(r2.lookup("/home/markus/ubuntu/linux/OS/run")) print(r2.lookup("/home/markus/ubuntu/linux/OS/run/")) # None # None # about handler # about handler # None # ------------------------------------------------------ # None # None # None # None # Run Ubuntu # Run Ubuntu # ------------------------------------------------------ # None # None # None # Run Ubuntu # Run your Linux # Only Run # Only Run
#https://www.youtube.com/watch?v=eSOJ3ARN5FM&t=842s #https://en.wikipedia.org/wiki/A*_search_algorithm import numpy as np class Vertex(object): def __init__(self, origin=None, position=None): self.origin = origin self.position = position self.f = 0 self.g = 0 self.h = 0 def calculate_distance(pos_1, pos_2): x1 = pos_1[0] y1 = pos_1[1] x2 = pos_2[0] y2 = pos_2[1] delta_x = x2 - x1 delta_y = y2 - y1 return np.sqrt(delta_x**2 + delta_y**2) def check_path(current_vertex, goal): shortest_path = [] if current_vertex.position == goal: current = current_vertex while current is not None: shortest_path.insert(0,current.position) current = current.origin return shortest_path return None def find_k_min(open_list): value_min = 0 k_min = '' for key in open_list.keys(): if k_min == '': k_min = key value_min = open_list[k_min].f if open_list[key].f < value_min: value_min = open_list[key].f k_min = key return k_min def shortest_path(M,start,goal): start_vertex = Vertex(None, start) start_vertex.g = 0 start_vertex.h = 0 start_vertex.f = 0 end_vertex = Vertex(None, goal) end_vertex.g = 0 end_vertex.h = 0 end_vertex.f = 0 open_list = dict() closed_list = set() open_list[start_vertex.position] = start_vertex #** WIKI: #** while openSet is not empty while len(open_list) > 0: #** current := the vertex in openSet having the lowest fScore[] value k_min = find_k_min(open_list) current_vertex = open_list[k_min] #** if current = goal #** return check_path(cameFrom, current) shortest_path = check_path(current_vertex, end_vertex.position) if shortest_path: return shortest_path #** closeSet.add(current) #** openSet.Remove(current) del open_list[current_vertex.position] closed_list.add(current_vertex.position) #** openSet.Remove(current) #**for each neighbor of current #** // d(current,neighbor) is the weight of the edge from current to neighbor #** // tentative_gScore is the distance from start to the neighbor through current #** tentative_gScore := gScore[current] + d(current, neighbor) #** if tentative_gScore < gScore[neighbor] #** // This path to neighbor is better than any previous one. Record it! #** cameFrom[neighbor] := current #** gScore[neighbor] := tentative_gScore #** fScore[neighbor] := gScore[neighbor] + h(neighbor) #** if neighbor not in closeSet #** openSet.add(neighbor) for neighbor in M.roads[current_vertex.position]: neighbor_vertex = Vertex(current_vertex, neighbor) #do not analyse neighbor if on closed list if neighbor_vertex.position in closed_list: continue # return to beginning (top of loop) neighbor_vertex.g = current_vertex.g + calculate_distance(M.intersections[current_vertex.position], M.intersections[neighbor_vertex.position]) neighbor_vertex.h = calculate_distance(M.intersections[neighbor_vertex.position], M.intersections[end_vertex.position]) neighbor_vertex.f = neighbor_vertex.g + neighbor_vertex.h #check if new computed value is lower than existing. If so update if neighbor_vertex.position in open_list: if neighbor_vertex.g > open_list[neighbor_vertex.position].g : continue #go on the top because the new value is higher the existing - no update for this vertex open_list[neighbor_vertex.position]= neighbor_vertex # update return
print('This program turns a sentance into camel case') userInputSentance = input("Enter a sentance to convert:") #x = 0 #while x < len(userInputSentance): #if userInputSentance[x] == ' ': #takes the string and capitalizes each word using title function userInputSentance = userInputSentance.title() #joining the words together and getting rid of spaces # can also use replace() function #list comprehention # can also use replace() function #no_space = test.replace(' ', '') userInputSentance = ''.join(x for x in userInputSentance if not x.isspace()) #http://stackoverflow.com/questions/3840843/how-to-downcase-the-first-character-of-a-string-in-python userInputSentance = userInputSentance[0].lower() + userInputSentance[1:] print(userInputSentance)
# Day 2 100 days of code # Variables # You do not have to specify a variable type x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 print(x) print(y) print("Variable z is ", z)
#get information ask_user = float(input("Please give me a number")) #do calculation #give output print(ask_user+2)
#Write a program that prints out the first n triangular numbers. n=int(input("Pick a number")) count=0 for i in range(1,n+1): print(i, "\t", i+count ) count+=i
a=float(input("Length of the first shorter side")) b=float(input("Length of the second shorter side")) y=float(input("Length of the longest side")) x=(a**2+b**2)**0.5 threshold = 1e-7 if abs(x-y) < threshold: print("TRUE") else: print("FALSE")
import string def remove_punctuation(phrase,): phrase_sans_punct = "" for letter in phrase: if letter not in string.punctuation: phrase_sans_punct += letter x=len(phrase_sans_punct.split()) count=0 for word in phrase_sans_punct.split(): if "e" in word: count +=1 return(print("Your text contains", x ,"words, of which", count, "({0:.3f}".format(count/x*100), "%) contain an \"e\"" )) #Your text contains 243 words, of which 109 (44.8%) contain an "e". text = """ And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream. I have a dream that one day this nation will rise up and live out the true meaning of its creed: "We hold these truths to be self-evident, that all men are created equal." I have a dream that one day on the red hills of Georgia, the sons of former slaves and the sons of former slave owners will be able to sit down together at the table of brotherhood. I have a dream that one day even the state of Mississippi, a state sweltering with the heat of injustice, sweltering with the heat of oppression, will be transformed into an oasis of freedom and justice. I have a dream that my four little children will one day live in a nation where they will not be judged by the color of their skin but by the content of their character. I have a dream today!""" remove_punctuation(text)
# Take user input of a string user_input = input('Give me a word. ') # Make a dictionary dictionary = {} # dictionary contains how many times each letter was used in word # work through each character in input, count how many times it exists in string, # then counts how many each appears, then adds them to dictionary for character in user_input: character_count = user_input.count(character) dictionary[character] = character_count # Thought I was going to have to add an if statement for multiple characters # but, each time you have character, will just update the value to the same thing print(dictionary)
def function1(x): # here im defining the function and making x the var. convert = (x * 1.6) #converting miles to kilometers print ('km :') print (convert) function1(11) #doing the function over and over with different inputs function1(22) #22 miles function1(45) #45 miles # this function converts miles to kilometers with x representing miles
""" @param: A: An integer array @return: A list of integers includes the index of the first number and the index of the last number """ def FindMaxArray(A, st, ed): if st==ed: return (A[st], st, ed) if st>ed: return (-1000, st, ed) mid = int((st + ed)/2) # print("call", (st, mid-1), (mid+1,ed)) (left, st1, ed1) = FindMaxArray(A, st, mid-1) (right, st2, ed2) = FindMaxArray(A, mid+1, ed) # print("return", (st, ed)) if left<right: res = (right, st2, ed2) else: res = (left, st1, ed1) right = 0 left = 0 i = mid + 1 ed3 = mid s = 0 while i <= ed: s = s + A[i] if s > right: right = s ed3 = i i = i + 1 i = mid - 1 st3 = mid s = 0 while i >= st: s = s + A[i] if s > left: left = s st3 = i i = i - 1 s = right + left + A[mid] if res[0]<s: res = (s, st3, ed3) # print((st, ed),"res",res) return res def continuousSubarraySum(A): length = len(A) res = FindMaxArray(A, 0, length-1) print([res[1],res[2]]) if __name__ == "__main__": A = [-3, 1, 3, -3, 4] continuousSubarraySum(A)
#!/usr/bin/env python3 # state memory = [] pc = 0 opcode = 0 modes = [] halt = False # read program into memory as integers with open("input.txt") as F: for line in F: for i in line.strip().split(','): memory.append(int(i)) def opcode0102(): # opcode01 = add # opcode02 = multiply # three parameters global memory global pc global opcode global modes global halt params = 3 p = [] for i in range(params): p.insert(i, memory[pc+1+i]) print("*", pc, ":", opcode, modes, "->", p) # parameters 1 and 2 can be immediate or positional for i in [0,1]: # positional if modes[i] == 0: p[i] = memory[p[i]] print("*", pc, ":", opcode, modes, "->", p) # parameter 3 is always positional pos = p[2] print("* [", pos, "] =", memory[pos]) # add if opcode == '01': print("* ADD",p[0],p[1],"> [", pos, "]") memory[pos] = int(p[0] + p[1]) # multiply if opcode == '02': print("* MULT",p[0],p[1],"> [", pos, "]") memory[pos] = int(p[0] * p[1]) print("* [", pos, "] =", memory[pos]) pc += params + 1 def opcode03(): # opcode03 = input # one parameter global memory global pc global opcode global modes global halt params = 1 p = [] for i in range(params): p.insert(i, memory[pc+1+i]) print("*", pc, ":", opcode, modes, "->", p) # always positional pos = p[0] value = input("input? ") print("* [", pos, "] =", memory[pos]) memory[pos] = int(value) print("* [", pos, "] =", memory[pos]) pc += params + 1 def opcode04(): # opcode04 = output # one parameter global memory global pc global opcode global modes global halt params = 1 p = [] for i in range(params): p.insert(i, memory[pc+1+i]) print("*", pc, ":", opcode, modes, "->", p) value = p[0] if modes[0] == 0: value = memory[p[0]] print("output:", value) pc += params + 1 def opcode99(): # opcode99 = halt # no parameters global memory global pc global opcode global modes global halt p = [] print("*", pc, ":", opcode, p) halt = True execute = { '01': opcode0102, '02': opcode0102, '03': opcode03, '04': opcode04, '99': opcode99 } while not halt: instruction = memory[pc] print("*", pc, ":", instruction) opcode = instruction % 100 opcode = "{:02d}".format(opcode) modes = instruction // 100 modes = "{:03d}".format(modes) modes = [ int(n) for n in modes ] modes.reverse() print("*", pc, ":", opcode, modes) execute[opcode]()
n = int(input("How many apples are there with Harry: ")) mn = int(input("Minimum numbers of students: ")) mx = int(input("Maximum numbers of students: ")) if mn > mx: print("This is not a range. Minimum is greater than Maximum") if mn == mx: print("This is not a range. Minimum and Maximum are same") else: for i in range(mn, mx + 1): if n % i == 0: print(f"{i} is a divisor of {n}") if n % i != 0: print(f"{i} is not a divisor of {n}")
import heapq import math pqueue=[] grafico={ "A":{"B":5,"C":1}, "B":{"A":5,"C":2,"D":1}, "C":{"A":1,"B":2,"C":4,"D":8}, "D":{"B":1,"C":4,"E":3,"F":6}, "E":{"C":8,"D":3}, "F":{"D":6}} def iniciaDis(graph): distancia={"A":0} for vertex in grafico: if vertex !="A": distancia[vertex]=math.inf return distancia def dijkstra(grafico): pqueue=[] heapq.heappush(pqueue,(0,"A")) seen=set() parent={"A":None} distancia=iniciaDis(grafico) while(len(pqueue)>0): par=heapq.heappop(pqueue) dis=par[0] vertex=par[1] seen.add("A") nodes=grafico[vertex].keys() for w in nodes: if w not in seen: if dis+grafico[vertex][w]<distancia[w]: heapq.heappush(pqueue,(dis+grafico[vertex][w],w)) parent[w]=vertex distancia[w]=dis+grafico[vertex][w] return parent,distancia parent,distanciaa=dijkstra(grafico) print(parent) print(distanciaa)
dict={} multatotal = 0 class Motorista: empCount = 0 multa=0 def __init__(self, numero, multa): self.numero= numero self.multa = multa def adicionarmulta(multa): multa=multa+multa while True: str=input('digite registrar ou exibir :') if str=='exibir': break else: str1=input('digite numero') str2=int(input('digite multa')) if str1 in dict: dict.get(str1).adicionarmulta(str2) else: motorista=Motorista(str1,str2) dict[str1] = motorista print(dict) print(dict.get(str1))
import time class BlockChain: """ a block chain implementaion in python used for learning purpose and translated from javascript code of """ def __init__(self): self.chain = [] self.pending_transactions= [] def create_block(self, nonce, previous_block_hash, current_block_hash): new_block = { 'index': len(self.chain) + 1, 'timestamp': time.now(), 'transactions: self.pending_transactions', 'nonce': nonce, 'hash': current_block_hash, 'previous_block_hash': previous_block_hash } self.pending_transactions = [] self.chain.append(new_block); def get_last_block(self): return self.chain[-1] def create_transaction(self, amount, sender, recipient): new_transaction = { 'amount': amount, 'sender': sender, 'recipient': recipient } this.pending_transactions.append(new_transaction); def hash_block(block_data): pass
""" The meteo module contains all functions related to meteorological variables. All meteorological functions can be calculated on a daily or instantaneous basis. Base functions are available also. The daily functions have a 'daily' extension, instantaneous functions have a 'inst' extension """ from pyWAPOR.ETLook import constants as c import numpy as np def air_temperature_celcius(t_air_k): r""" Converts air temperature from Kelvin to Celcius, where 0 degrees Celcius is equal to 273.15 degrees Kelvin Parameters ---------- t_air_k : float air temperature :math:`T_a` [K] Returns ------- t_air_c : float air temperature :math:`T_a` [C] Examples -------- >>> from ETLook import meteo >>> meteo.air_temperature_celcius(12.5) 285.65 """ return t_air_k - c.zero_celcius def air_temperature_kelvin(t_air): r""" Converts air temperature from Celcius to Kelvin, where 0 degrees Celcius is equal to 273.15 degrees Kelvin Parameters ---------- t_air : float air temperature :math:`T_a` [C] Returns ------- t_air_k : float air temperature :math:`T_a` [K] Examples -------- >>> from ETLook import meteo >>> meteo.air_temperature_kelvin(12.5) 285.65 """ return t_air + c.zero_celcius def air_temperature_kelvin_daily(t_air_24): """Like :func:`air_temperature_kelvin` but as a daily average Parameters ---------- t_air_24 : float daily air temperature :math:`T_{a,24}` [C] Returns ------- t_air_k_24 : float daily air temperature :math:`T_{a,24}` [K] """ return air_temperature_kelvin(t_air_24) def air_temperature_kelvin_inst(t_air_i): """Like :func:`air_temperature_kelvin` but as an instantaneous value Parameters ---------- t_air_i : float instantaneous air temperature :math:`T_{a,i}` [C] Returns ------- t_air_k_i : float instantaneous air temperature :math:`T_{a,i}` [K] """ return air_temperature_kelvin(t_air_i) def wet_bulb_temperature_kelvin_inst(t_wet_i): """ Converts wet bulb temperature from Celcius to Kelvin, where 0 degrees Celcius is equal to 273.15 degrees Kelvin Parameters ---------- t_wet_i : float instantaneous wet bulb temperature :math:`T_{w,i}` [C] Returns ------- t_wet_k_i : float instantaneous wet bulb temperature :math:`T_{w,i}` [K] """ return air_temperature_kelvin(t_wet_i) def disaggregate_air_temperature(t_air_coarse, z, z_coarse, lapse=-0.006): r""" Disaggregates GEOS or MERRA or another coarse scale air temperature using two digital elevation models. One DEM for the target resolution, another DEM smoothed from the original air temperature resolution to the target resolution. .. math :: T_{a}=T_{a,c}+(z-z_{c})L_{T}-T_{K,0} where the following constant is used * :math:`T_{K,0}` = 273.15 K is equal to 0 degrees Celsius Parameters ---------- t_air_coarse : float air temperature at coarse resolution :math:`T_{a,c}` [K] z : float elevation :math:`z` [m] z_coarse : float elevation at coarse resolution :math:`z_{c}` [m] lapse : float lapse rate :math:`L_{T}` [K m-1] Returns ------- t_air : float air temperature :math:`T_{a}` [C] Notes ----- The input air temperature is specified in Kelvin. The output air temperature is specified in C. Examples -------- >>> from ETLook import meteo >>> meteo.disaggregate_air_temperature(24.5+273.15, 10, 5) 24.47 """ return t_air_coarse + ((z - z_coarse) * lapse) - c.zero_celcius def disaggregate_air_temperature_daily(t_air_24_coarse, z, z_coarse, lapse=-0.006): r"""Like :func:`disaggregate_air_temperature` but as a daily average Parameters ---------- t_air_24_coarse : float daily air temperature at coarse resolution :math:`T_{a,24,c}` [K] z : float elevation :math:`z` [m] z_coarse : float elevation at coarse resolution :math:`z_{c}` [m] lapse : float lapse rate :math:`L` [K m-1] Returns ------- t_air_24 : float daily air temperature :math:`T_{a,24}` [C] Notes ----- The input air temperature is specified in Kelvin. The output air temperature is specified in C. """ return disaggregate_air_temperature(t_air_24_coarse, z, z_coarse, lapse) def disaggregate_air_temperature_inst(t_air_i_coarse, z, z_coarse, lapse=-0.006): r"""Like :func:`disaggregate_air_temperature` but as a instantaneous value Parameters ---------- t_air_i_coarse : float instantaneous air temperature at coarse resolution :math:`T_{a,i,c}` [K] z : float elevation :math:`z` [m] z_coarse : float elevation at coarse resolution :math:`z_{c}` [m] lapse : float lapse rate :math:`L` [K m-1] Returns ------- t_air_i : float instantaneous air temperature :math:`T_{a,i}` [C] Notes ----- The input air temperature is specified in Kelvin. The output air temperature is specified in C. """ return disaggregate_air_temperature(t_air_i_coarse, z, z_coarse, lapse) def disaggregate_dew_point_temperature_inst(t_dew_coarse_i, z, z_coarse, lapse_dew=-0.002): r""" Disaggregates geos dew point temperature using lapse rate and difference between smoothed coarse scale DEM and fine scale DEM Parameters ---------- t_dew_coarse_i : float coarse instantaneous dew point temperature :math:`T_{dew,coarse}` [C] z : float elevation :math:`z` [m] z_coarse : float smoothed elevation at coarse resolution :math:`z` [m] lapse_dew : float lapse rate :math:`L` [K m-1] Returns ------- t_dew_i : float instantaneous dew point temperature :math:`T_{dew,i}` [C] """ return t_dew_coarse_i + ((z - z_coarse) * lapse_dew) def vapour_pressure_from_specific_humidity(qv, p_air): r""" Computes the vapour pressure :math:`e_a` in [mbar] using specific humidity and surface pressure .. math :: e_{a}=\frac{q_{v}P}{\varepsilon} where the following constant is used * :math:`\varepsilon` = ratio of molecular weight of water to dry air = 0.622 [-] Parameters ---------- qv : float specific humidity :math:`q_{v}` [kg/kg] p_air : float air pressure :math:`P` [mbar] Returns ------- vp : float vapour pressure :math:`e_{a}` [mbar] """ return (qv * p_air) / c.r_mw def vapour_pressure_from_specific_humidity_daily(qv_24, p_air_24): """Like :func:`vapour_pressure_from_specific_humidity` but as a daily average Parameters ---------- qv_24 : float daily specific humidity :math:`q_{v,24}` [kg/kg] p_air_24 : float daily air pressure :math:`P_{24}` [mbar] Returns ------- vp_24 : float daily vapour pressure :math:`e_{a,24}` [mbar] """ return vapour_pressure_from_specific_humidity(qv_24, p_air_24) def saturated_vapour_pressure_minimum(t_air_min_coarse): """Like :func:`saturated_vapour_pressure` but based on daily minimum air temperature. This is only relevant for reference ET calculations Parameters ---------- t_air_min_coarse : float daily minimum air temperature :math:`T_{a,min}` [C] Returns ------- svp_24_min : float daily saturated vapour pressure based on minimum air temperature :math:`e_{s,min}` [mbar] """ return saturated_vapour_pressure(t_air_min_coarse) def saturated_vapour_pressure_maximum(t_air_max_coarse): """Like :func:`saturated_vapour_pressure` but based on daily maximum air temperature. This is only relevant for reference ET calculations Parameters ---------- t_air_max_coarse : float daily maximum air temperature :math:`T_{a,max}` [C] Returns ------- svp_24_max : float daily saturated vapour pressure based on maximum air temperature :math:`e_{s,max}` [mbar] """ return saturated_vapour_pressure(t_air_max_coarse) def saturated_vapour_pressure_average(svp_24_max, svp_24_min): """ Average saturated vapour pressure based on two saturated vapour pressure values calculated using minimum and maximum air temperature respectively. This is preferable to calculating saturated vapour pressure using the average air temperature, because of the strong non-linear relationship between saturated vapour pressure and air temperature .. math :: e_{s}=\frac{e^{0}\left(T_{max}\right)+e^{0}\left(T_{mon}\right)}{2} Parameters ---------- svp_24_max : float daily saturated vapour pressure based on maximum air temperature :math:`e_{s,max}` [mbar] svp_24_min : float daily saturated vapour pressure based on minimum air temperature :math:`e_{s,min}` [mbar] Returns ------- svp_24 : float daily saturated vapour pressure :math:`e_{s,24}` [mbar] """ return (svp_24_max + svp_24_min)/2 def vapour_pressure_from_specific_humidity_inst(qv_i, p_air_i): """Like :func:`vapour_pressure_from_specific_humidity` but as an instantaneous value Parameters ---------- qv_i : float instantaneous specific humidity :math:`q_{v,i}` [kg/kg] p_air_i : float instantaneous air pressure :math:`P_{i}` [mbar] Returns ------- vp_i : float instantaneous vapour pressure :math:`e_{a,i}` [mbar] """ return vapour_pressure_from_specific_humidity(qv_i, p_air_i) def saturated_vapour_pressure(t_air): r""" Computes saturated vapour pressure :math:`e_s` [mbar], it provides the vapour pressure when the air is fully saturated with water. It is related to air temperature :math:`T_a` [C]: .. math :: e_{s}=6.108\exp\left[\frac{17.27T_{a}}{T_{a}+237.3}\right] Parameters ---------- t_air : float air temperature :math:`T_a` [C] Returns ------- svp : float saturated vapour pressure :math:`e_s` [mbar] Examples -------- >>> from ETLook import meteo >>> meteo.saturated_vapour_pressure(20) 23.382812709274457 .. plot:: pyplots/meteo/plot_saturated_vapour_pressure.py """ return 6.108 * np.exp(((17.27 * t_air) / (237.3 + t_air))) def saturated_vapour_pressure_daily(t_air_24): """Like :func:`saturated_vapour_pressure` but as a daily average Parameters ---------- t_air_24 : float daily air temperature :math:`T_{a,24}` [C] Returns ------- svp_24 : float daily saturated vapour pressure :math:`e_{s,24}` [mbar] """ return saturated_vapour_pressure(t_air_24) def saturated_vapour_pressure_inst(t_air_i): """Like :func:`saturated_vapour_pressure` but as an instantaneous value Parameters ---------- t_air_i : float instantaneous air temperature :math:`T_{a,i}` [C] Returns ------- svp_i : float instantaneous saturated vapour pressure :math:`e_{s,i}` [mbar] """ return saturated_vapour_pressure(t_air_i) def vapour_pressure(svp, rh): r""" Computes the vapour pressure :math:`e_a` in [mbar] .. math :: e_{a}=\frac{\phi}{100}e_{s} Parameters ---------- svp : float saturated vapour pressure :math:`e_s` [mbar] rh : float relative humidity :math:`\phi` [%] Returns ------- vp : float vapour pressure :math:`e_{a}` [mbar] Examples -------- >>> from ETLook import meteo >>> meteo.vapour_pressure(rh=75, svp=meteo.saturated_vapour_pressure(20)) 17.537109531955842 """ return 0.01 * rh * svp def slope_saturated_vapour_pressure(t_air): r""" Computes the rate of change of vapour pressure :math:`\Delta` in [mbar K-1] for a given air temperature :math:`T_a`. It is a function of the air temperature :math:`T_a` and the saturated vapour pressure :math:`e_s` [mbar] which in itself is a function of :math:`T_a`. .. math :: \Delta=\frac{4098e_{s}}{\left(237.3+T_{a}\right)^{2}} for :math:`e_s` see :func:`saturated_vapour_pressure` Parameters ---------- t_air : float air temperature :math:`T_a` [C] Returns ------- ssvp : float slope of saturated vapour pressure curve :math:`\Delta` [mbar K-1] Examples -------- >>> from ETLook import meteo >>> meteo.slope_saturated_vapour_pressure(20) 1.447401881124136 .. plot:: pyplots/meteo/plot_slope_saturated_vapour_pressure.py """ svp = saturated_vapour_pressure(t_air) return (4098 * svp) / (237.3 + t_air) ** 2 def slope_saturated_vapour_pressure_daily(t_air_24): """Like :func:`slope_saturated_vapour_pressure` but as a daily average Parameters ---------- t_air_24 : float daily air temperature :math:`T_{a,24}` [C] Returns ------- ssvp_24 : float daily slope of saturated vapour pressure curve :math:`\Delta_{24}` [mbar K-1] """ return slope_saturated_vapour_pressure(t_air_24) def slope_saturated_vapour_pressure_inst(t_air_i): """Like :func:`slope_saturated_vapour_pressure` but as an instantaneous value Parameters ---------- t_air_i : float instantaneous air temperature :math:`T_{a,i}` [C] Returns ------- ssvp_i : float instantaneous slope of saturated vapour pressure curve :math:`e_{s,i}` [mbar] """ return slope_saturated_vapour_pressure(t_air_i) def vapour_pressure_deficit(svp, vp): r""" Computes the vapour pressure deficit :math:`\Delta_e` in [mbar] .. math :: \Delta_e=e_s-e_a Parameters ---------- svp : float saturated vapour pressure :math:`e_s` [mbar] vp : float actual vapour pressure :math:`e_a` [mbar] Returns ------- vpd : float vapour pressure deficit :math:`\Delta_e` [mbar] Examples -------- >>> from ETLook import meteo >>> meteo.vapour_pressure_deficit(12.5, 5.4) 7.1 >>> meteo.vapour_pressure_deficit(vp=5.4, svp=12.3) 6.9 """ vpd = svp - vp vpd[vpd < 0] = 0 return vpd def vapour_pressure_deficit_daily(svp_24, vp_24): """Like :func:`vapour_pressure_deficit` but as a daily average Parameters ---------- svp_24 : float daily saturated vapour pressure :math:`e_{s,24}` [mbar] vp_24 : float daily actual vapour pressure :math:`e_{a,24}` [mbar] Returns ------- vpd_24 : float daily vapour pressure deficit :math:`\Delta_{e,24}` [mbar] """ return vapour_pressure_deficit(svp_24, vp_24) def air_pressure(z, p_air_0=1013.25): r""" Computes air pressure :math:`P` at a certain elevation derived from the air pressure at sea level :math:`P_0`. Air pressure decreases with increasing elevation. .. math :: P=P_{0}\left(\frac{T_{ref,0,K}-\alpha_{1}\left(z-z_{0}\right)} {T_{ref,0,K}}\right)^{\frac{g}{\alpha{}_{1^{R}}}} where the following constants are used * :math:`P_0` = air pressure [mbar] at sea level :math:`z_0` = 1013.25 mbar * :math:`T_{ref,0,K}` = reference temperature [K] at sea level :math:`z_0` = 293.15 K * :math:`g` = gravitational acceleration = 9.807 [m/s2] * :math:`R` = specific gas constant = 287.0 [J kg-1 K-1] * :math:`\alpha_1` = constant lapse rate for moist air = 0.0065 [K m-1] Parameters ---------- z : float elevation :math:`z` [m] p_air_0 : float air pressure at sea level :math:`P_0` [mbar] Returns ------- p_air : float air pressure :math:`P` [mbar] Examples -------- >>> from ETLook import meteo >>> meteo.air_pressure(z=1000) 900.5832172948869 .. plot:: pyplots/meteo/plot_air_pressure.py """ return p_air_0 * ((c.t_ref + c.lapse * (z - c.z_ref)) / c.t_ref) ** c.power def air_pressure_daily(z, p_air_0_24=1013.25): r"""Like :func:`air_pressure` but as a daily average Parameters ---------- z : float elevation :math:`z` [m] p_air_0_24 : float daily air pressure at sea level :math:`P_{0,24}` [mbar] Returns ------- p_air_24 : float daily air pressure :math:`P_{24}` [mbar] """ return air_pressure(z, p_air_0_24) def dry_air_density(p_air, vp, t_air_k): r""" Computes dry air density :math:`\rho_{d}` in [kg m-3] .. math :: \rho_{d}=\frac{P-e_{a}}{\Re T_{a,K}} where the following constants are used * :math:`\Re` = gas constant for dry air = 2.87 mbar K-1 m3 kg-1 Parameters ---------- p_air : float air pressure :math:`P` [mbar] vp : float vapour pressure :math:`e_{a}` [mbar] t_air_k : float daily air temperature :math:`T_{a}` [K] Returns ------- ad_dry : float dry air density :math:`\rho_{d}` [kg m-3] Examples -------- >>> from ETLook import meteo >>> meteo.dry_air_density(p_air=900, vp=17.5, t_air_k=293.15) 1.0489213344656534 .. plot:: pyplots/meteo/plot_dry_air_density.py """ return (p_air - vp) / (t_air_k * c.gc_dry) def dry_air_density_daily(p_air_24, vp_24, t_air_k_24): r""" Like :func:`dry_air_density` but as a daily average Parameters ---------- p_air_24 : float daily air pressure :math:`P_{24}` [mbar] vp_24 : float daily vapour pressure :math:`e_{a,24}` [mbar] t_air_k_24 : float daily air temperature :math:`T_{a,24}` [K] Returns ------- ad_dry_24 : float daily dry air density :math:`\rho_{d,24}` [kg m-3] """ return dry_air_density(p_air_24, vp_24, t_air_k_24) def dry_air_density_inst(p_air_i, vp_i, t_air_k_i): r""" Like :func:`dry_air_density` but as an instantaneous value Parameters ---------- p_air_i : float instantaneous air pressure :math:`P_{i}` [mbar] vp_i : float instantaneous vapour pressure :math:`e_{a,i}` [mbar] t_air_k_i : float instantaneous air temperature :math:`T_{a,i}` [K] Returns ------- ad_dry_i : float instantaneous dry air density :math:`\rho_{d,i}` [kg m-3] """ return dry_air_density(p_air_i, vp_i, t_air_k_i) def moist_air_density(vp, t_air_k): r""" Computes moist air density :math:`\rho_{s}` in [kg m-3] .. math :: \rho_{s}=\frac{e_{a}}{R_{v}T_{a,K}} where the following constants are used * :math:`R_v` = gas constant for moist air = 4.61 mbar K-1 m3 kg-1 Parameters ---------- vp : float vapour pressure :math:`e_{a}` [mbar] t_air_k : float air temperature :math:`T_{a,K}` [K] Returns ------- ad_moist : float moist air density :math:`\rho_{s}` [kg m-3] Examples -------- >>> from ETLook import meteo >>> meteo.moist_air_density(vp=17.5, t_air_k = 293.15) 0.012949327800393881 .. plot:: pyplots/meteo/plot_moist_air_density.py """ return vp / (t_air_k * c.gc_moist) def moist_air_density_daily(vp_24, t_air_k_24): r""" Like :func:`moist_air_density` but as a daily average Parameters ---------- vp_24 : float daily vapour pressure :math:`e_{a,24}` [mbar] t_air_k_24 : float daily air temperature :math:`T_{a,K,24}` [K] Returns ------- ad_moist_24 : float daily moist air density :math:`\rho_{s,24}` [kg m-3] """ return moist_air_density(vp_24, t_air_k_24) def moist_air_density_inst(vp_i, t_air_k_i): r""" Like :func:`moist_air_density` but as an instantaneous value Parameters ---------- vp_i : float instantaneous vapour pressure :math:`e_{a,i}` [mbar] t_air_k_i : float instantaneous air temperature :math:`T_{a,K,i}` [K] Returns ------- ad_moist_i : float instantaneous moist air density :math:`\rho_{s,i}` [kg m-3] """ return moist_air_density(vp_i, t_air_k_i) def air_density(ad_dry, ad_moist): r""" Computes air density :math:`\rho` in [kg m-3] .. math :: \rho=\rho_{s}+\rho_{d} Parameters ---------- ad_dry : float dry air density :math:`\rho_{d}` [kg m-3] ad_moist : float moist air density :math:`\rho_{s}` [kg m-3] Returns ------- ad : float air density :math:`\rho` [kg m-3] Examples -------- >>> from ETLook import meteo >>> ad_moist = meteo.moist_air_density(vp=17.5, t_air_k = 293.15) >>> ad_dry = meteo.dry_air_density(p_air=900, vp=17.5, t_air_k=293.15) >>> meteo.air_density(ad_dry=ad_dry, ad_moist=ad_moist) 1.0618706622660472 .. plot:: pyplots/meteo/plot_air_density.py """ return ad_dry + ad_moist def air_density_daily(ad_dry_24, ad_moist_24): r""" Like :func:`air_density` but as a daily average Parameters ---------- ad_dry_24 : float daily dry air density :math:`\rho_{d,24}` [kg m-3] ad_moist_24 : float daily moist air density :math:`\rho_{s,24}` [kg m-3] Returns ------- ad_24 : float daily air density :math:`\rho_{24}` [kg m-3] """ return air_density(ad_dry_24, ad_moist_24) def air_density_inst(ad_dry_i, ad_moist_i): r""" Like :func:`air_density` but as a instantaneous value Parameters ---------- ad_dry_i : float instantaneous dry air density :math:`\rho_{d,i}` [kg m-3] ad_moist_i : float instantaneous moist air density :math:`\rho_{s,i}` [kg m-3] Returns ------- ad_i : float instantaneous air density :math:`\rho_{i}` [kg m-3] """ return air_density(ad_dry_i, ad_moist_i) def latent_heat(t_air): r""" Computes latent heat of evaporation :math:`\lambda` [J kg-1], describing the amount of energy needed to evaporate one kg of water at constant pressure and temperature. At higher temperatures less energy will be required than at lower temperatures. .. math :: \lambda=(\lambda_0 + \Delta_\lambda T_{a}) where the following constants are used * :math:`\lambda_0` = latent heat of evaporation at 0 C = 2501000 [J kg-1] * :math:`\Delta_\lambda` = rate of change of latent heat with respect to temperature = -2361 [J Kg-1 C-1] Parameters ---------- t_air : float air temperature :math:`T_a` [C] Returns ------- lh : float latent heat of evaporation :math:`\lambda` [J/kg] Examples -------- >>> from ETLook import meteo >>> meteo.latent_heat(20) 2453780.0 .. plot:: pyplots/meteo/plot_latent_heat.py """ return c.lh_0 + c.lh_rate * t_air def latent_heat_daily(t_air_24): """Like :func:`latent_heat` but as a daily average Parameters ---------- t_air_24 : float daily air temperature :math:`T_{a,24}` [C] Returns ------- lh_24 : float daily latent heat of evaporation :math:`\lambda_{24}` [J/kg] """ return latent_heat(t_air_24) def psychrometric_constant(p_air, lh): r""" Computes the psychrometric constant :math:`\gamma` [mbar K-1] which relates the partial pressure of water in air to the air temperature .. math :: \gamma=\frac{Pc_{p}}{\varepsilon\lambda} where the following constants are used * :math:`c_{p}` = specific heat for dry air = 1004 [J Kg-1 K-1] * :math:`\varepsilon` = ratio of molecular weight of water to dry air = 0.622 [-] Parameters ---------- p_air : float air pressure :math:`P` [mbar] lh : float latent heat of evaporation :math:`\lambda` [J/kg] Returns ------- psy : float psychrometric constant :math:`\gamma` [mbar K-1] Examples -------- >>> from ETLook import meteo >>> meteo.psychrometric_constant(p_air = 1003.0, lh = 2500000.0) 0.6475961414790997 >>> meteo.psychrometric_constant(1003.0, 2500000.0) 0.6475961414790997 .. plot:: pyplots/meteo/plot_psychrometric_constant.py """ return (c.sh * p_air) / (c.r_mw * lh) def psychrometric_constant_daily(p_air_24, lh_24): """Like :func:`psychrometric_constant` but as a daily average Parameters ---------- p_air_24 : float daily air pressure :math:`P_{24}` [mbar] lh_24 : float daily latent heat of evaporation :math:`\lambda_{24}` [J/kg] Returns ------- psy_24 : float daily psychrometric constant :math:`\gamma_{24}` [mbar K-1] """ return psychrometric_constant(p_air_24, lh_24) def wind_speed_blending_height(u, z_obs=2, z_b=100): r""" Computes the wind speed at blending height :math:`u_{b}` [m/s] using the logarithmic wind profile .. math :: u_{b}=\frac{u_{obs}\ln\left(\frac{z_{b}}{z_{0,m}}\right)} {\ln\left(\frac{z_{obs}}{z_{0,m}}\right)} Parameters ---------- u : float wind speed at observation height :math:`u_{obs}` [m/s] z_obs : float observation height of wind speed :math:`z_{obs}` [m] z_b : float blending height :math:`z_{b}` [m] Returns ------- u_b : float wind speed at blending height :math:`u_{b}` [m/s] Examples -------- >>> from ETLook import meteo >>> meteo.wind_speed_blending_height(u=3.0, z_obs=2, z_b=100) 5.4646162953650572 .. plot:: pyplots/meteo/plot_wind_speed.py """ z0m = 0.0171 ws = (c.k * u) / np.log(z_obs / z0m) * np.log(z_b / z0m) / c.k ws = np.clip(ws, 1, 150) return ws def wind_speed_blending_height_daily(u_24, z_obs=2, z_b=100): """Like :func:`wind_speed_blending_height` but as a daily average Parameters ---------- u_24 : float daily wind speed at observation height :math:`u_{obs,24}` [m/s] z_obs : float observation height of wind speed :math:`z_{obs}` [m] z_b : float blending height :math:`z_{b}` [m] Returns ------- u_b_24 : float daily wind speed at blending height :math:`u_{b, 24}` [m/s] """ return wind_speed_blending_height(u_24, z_obs, z_b) def air_pressure_kpa2mbar(p_air_kpa): """Like :func:`p_air` Parameters ---------- p_air_kpa : float air pressure :math:`Pair_{a}` [kpa] Returns ------- p_air_mbar : float air pressure :math:`Pair_{a}` [mbar] """ return p_air_kpa * 10
from vector import Vector class Rigidbody: gravity = 9.8 / 120 def __init__(self, obj, mass, collider): self.mass = mass self.velocity = Vector(0, 0) self.acceleration = Vector(0, self.gravity) self.rotationalVelocity = 0 self.rotationAcceleration = 0 self.maxRotationalVelocity = 7 self.position = obj.pos self.rotation = obj.rotation self.centreOfMass = () self.collider = collider def AddForce(self): pass def AddForceAtPosition(self): pass def AddRotationalForce(self): pass def UpdatePosition(self): self.velocity = Vector.Add(self.velocity, self.acceleration) self.position = Vector.Add(self.position, self.velocity) return self.position def UpdateRotation(self): self.rotationalVelocity = min(self.rotationalVelocity + self.rotationAcceleration, self.maxRotationalVelocity) self.rotation += self.rotationalVelocity return self.rotation
import sqlite3 import sys conn = sqlite3.connect('food.sqlite') curs = conn.cursor() query = 'SELECT * FROM Food WHERE ' + sys.argv[1] print(query) curs.execute(query) print(curs.description) names = [f[0] for f in curs.description] for row in curs.fetchall(): print(row) for pair in zip(names, row): print('{}: {}'.format(*pair)) print()
name = input("Enter your name pls : ") print(f"Welcome : " + name) #OR print(f"Welcome : {name}")
# 이건 시간초과,,,, # def Oct_to_binary(n): # if n <= 1: # return str(n) # answer = '' # while True: # if n % 2 == 0: # answer += '0' # else: # answer += '1' # n //= 2 # # if n == 1: # answer += '1' # return answer[::-1] # # # import sys # input = sys.stdin.readline # # N = input() # result = '' # for i in N: # x = # result += Oct_to_binary(int(i)).zfill(3) # 앞에 0을 채워서 문자열을 더해줌 # print(int(result)) # 맨 앞의 0을 제거하기위해 정수형으로 출력 # print(bin(int(input(), 8)[2:])) #정답 N = int(input(), 8) # 8진법으로 숫자를 입력 받음 print(bin(N)[2:]) # bin을 쓰면 앞에 0b가 붙으므로, 0b 떼고 문자열의 2번인덱스부터 출력
a = [15,26,78,54,69] print("Maximum element in the list is :", max(a), "\nMinimum element in the list is :", min(a)) a = [] num = int(input('How many numbers: ')) for n in range(num): numbers = int(input('Enter number ')) a.append(numbers) print("Maximum element in the list is :", max(a), "\nMinimum element in the list is :", min(a))
""" Implements the transition model. """ import dataclasses as py_dataclasses import random from typing import AbstractSet, Any import pomdp_py from ..action import Action from ..state import ALL_CARDS, Card, CardValue, State, Suit, lowest_club from ..utils import agent_won_trick class TransitionModel(pomdp_py.TransitionModel): """ Implements the transition model. """ _TWO_OF_CLUBS = Card(suit=Suit.CLUBS, value=CardValue.TWO) _QUEEN_OF_SPADES = Card(suit=Suit.SPADES, value=CardValue.QUEEN) _ALL_HEARTS = {c for c in ALL_CARDS if c.suit == Suit.HEARTS} @classmethod def __transition_common(cls, state: State) -> State: """ Performs the parts of the state transition that are common to all transitions and deterministic. Args: state: The current state. Returns: The updated state. """ return py_dataclasses.replace( state, is_first_trick=False, # A partial trick becomes the current trick. opponent_play=state.opponent_partial_play, opponent_partial_play=None, ) @classmethod def __possible_first_plays(cls, state: State) -> AbstractSet[Card]: """ Determines the possible cards that the first player can lead with while still following the rules. Args: state: The initial state. Returns: The set of cards that player 1 can legally play. """ if state.is_first_trick: # We nominally lead with the two of clubs. Note that a valid state # initialization always makes the player with the two of clubs # the first player, so if we don't have it, it can only be held out. assert ( cls._TWO_OF_CLUBS not in state.second_player_hand ), "Second player shouldn't have the two of clubs." # Play our lowest club. first_card = lowest_club(state.first_player_hand) assert ( first_card is not None ), "Agent should not be first if they have no clubs." return {first_card} else: # Normally, we can lead with anything. possible_plays = state.first_player_hand if not state.hearts_broken: # Hearts have not been broken, so we cannot lead with one. possible_plays -= cls._ALL_HEARTS if len(possible_plays) == 0: # ...except when we have nothing BUT hearts. possible_plays = state.first_player_hand return possible_plays @classmethod def __possible_second_plays( cls, next_state: State, state: State ) -> AbstractSet[Card]: """ Determines the possible cards that the second player can play while still following the rules. Args: next_state: The known part of the final state, including player 1's play. state: The initial state. Returns: The set of cards that player 2 can legally play. """ if next_state.lead_play is None: # If the first player did nothing, we can't do anything either. return set() lead_suit = next_state.lead_play.suit # We have to follow suit. same_suit = { c for c in state.second_player_hand if c.suit == lead_suit } if len(same_suit) > 0: # Choose from one of these. return same_suit # Otherwise, we can play any other suit. non_lead_suit = { c for c in state.second_player_hand if c.suit != lead_suit } possible_plays = non_lead_suit if state.is_first_trick: # On the first trick, we can't play hearts if we don't have to or # the queen of spades. possible_plays = ( non_lead_suit - {cls._QUEEN_OF_SPADES} - cls._ALL_HEARTS ) if len(possible_plays) == 0: # In this case, we have no choice but to play a heart. possible_plays = non_lead_suit - {cls._QUEEN_OF_SPADES} return possible_plays @classmethod def __handle_heartbreak(cls, next_state: State) -> State: """ `assert "It's going to be okay"` Keeps track of when hearts have been broken and updates the state accordingly. Args: next_state: The partially-updated state encompassing the results of the current trick. Returns: The updated state. """ if ( next_state.second_play.suit == Suit.HEARTS or next_state.lead_play.suit == Suit.HEARTS or next_state.opponent_partial_play == Suit.HEARTS ): # Hearts have been broken. return py_dataclasses.replace(next_state, hearts_broken=True) return next_state @classmethod def __handle_moonshot(cls, next_state: State) -> State: """ Keeps track of whether players are shooting the moon, and updates the state accordingly. Args: next_state: The partially-updated state, encompassing the results of the current trick. Returns: The updated state. """ agent_took_all_penalties = next_state.agent_took_all_penalties opponent_took_all_penalties = next_state.opponent_took_all_penalties trick_painted = ( next_state.agent_play.is_penalty or next_state.opponent_play.is_penalty ) agent_won = agent_won_trick(next_state) if trick_painted and agent_won: # If the agent took a penalty card, the opponent can't shoot the # moon. opponent_took_all_penalties = False elif trick_painted and not agent_won: # Similarly, if the opponent took a penalty card, the agent can't # shoot the moon. agent_took_all_penalties = False return py_dataclasses.replace( next_state, agent_took_all_penalties=agent_took_all_penalties, opponent_took_all_penalties=opponent_took_all_penalties, ) @classmethod def __handle_trick_winner(cls, next_state: State) -> State: """ If the opponent wins, they go first next trick. This is simulated by immediately updating the state again. This method checks for this condition and performs the necessary state update if it is met. Args: next_state: The partially-updated state encompassing the results of the current trick. Returns: The updated state. """ # Handle shooting the moon. next_state = cls.__handle_moonshot(next_state) # Determine the first player for the next trick. next_state = py_dataclasses.replace( next_state, agent_goes_first=agent_won_trick(next_state) ) if next_state.agent_goes_first: # The agent goes first next round. No need to do anything else. return next_state # Otherwise, we have to simulate the first play by the opponent. player_1_plays = cls.__possible_first_plays(next_state) if len(player_1_plays) == 0: # We are out of cards to play, so we don't have to do anything. return next_state # Choose a random card to play. player_1_hand = next_state.first_player_hand player_1_play = random.choice(tuple(player_1_plays)) player_1_hand -= {player_1_play} next_state = py_dataclasses.replace( next_state, opponent_hand=player_1_hand, # Update the partial play variable since this is technically a # new trick. opponent_partial_play=player_1_play, ) # Update the heartbreak status again because we might have played a # heart. return cls.__handle_heartbreak(next_state) @classmethod def __sample_agent_is_first(cls, state: State, action: Action) -> State: """ Handles the sampling in the case that the agent is the first player. Args: state: The current state. action: The action to take. Returns: The sampled next state. """ nop_state = py_dataclasses.replace( state, agent_play=None, opponent_play=None ) # The first trick flag will always be set to false. next_state = cls.__transition_common(state) # Determine possible plays for the agent. player_1_plays = cls.__possible_first_plays(state) # Make sure that our action is valid. if action.card is None or action.card not in player_1_plays: # Action is invalid. This is a nop. return nop_state # Update the state with the action. player_1_hand = state.first_player_hand player_1_hand -= {action.card} next_state = py_dataclasses.replace( next_state, agent_play=action.card, agent_hand=player_1_hand ) # Determine possible plays for player 2. player_2_plays = cls.__possible_second_plays(next_state, state) assert len(player_2_plays) > 0, "Agent 2 ended up with fewer cards." # Select one randomly. player_2_play = random.choice(tuple(player_2_plays)) player_2_hand = state.second_player_hand player_2_hand -= {player_2_play} next_state = py_dataclasses.replace( next_state, opponent_hand=player_2_hand, opponent_play=player_2_play, ) next_state = cls.__handle_heartbreak(next_state) # Handle additional modifications based on the winner of this trick. return cls.__handle_trick_winner(next_state) @classmethod def __sample_agent_is_second(cls, state: State, action: Action) -> State: """ Handles the sampling in the case that the agent is the second player. Args: state: The current state. action: The action to take. Returns: The sampled next state. """ nop_state = py_dataclasses.replace( state, agent_play=None, opponent_play=None ) # The first trick flag will always be set to false. next_state = cls.__transition_common(state) # In this case, we should already be halfway done with the trick from # the previous state update. if next_state.lead_play is None: # The opponent did a nop, so we have to do the same. return nop_state player_2_plays = cls.__possible_second_plays(next_state, state) assert len(player_2_plays) > 0, "Agent 2 ended up with fewer cards." if action.card not in player_2_plays: # Action is invalid. This is a nop. return nop_state # Update the state. player_2_hand = state.second_player_hand player_2_hand -= {action.card} next_state = py_dataclasses.replace( next_state, agent_hand=player_2_hand, agent_play=action.card ) next_state = cls.__handle_trick_winner(next_state) # Handle additional modifications based on the winner of this trick. return cls.__handle_heartbreak(next_state) def sample(self, state: State, action: Action, **kwargs: Any) -> State: """ Randomly samples a possible next state given a current state and an action. Args: state: The current state. action: The action to take. **kwargs: Will be ignored. Returns: The sampled next state. """ if state.agent_goes_first: return self.__sample_agent_is_first(state, action) else: return self.__sample_agent_is_second(state, action)
# Finding the right amount to save away def final_savings(starting_salary, portion_saved, semi_annual_raise = .07, r = .04, months = 36): """Return the amounts of money saved over a specified period.""" annual_salary = starting_salary current_savings = 0 for month in range(months): if(month + 1) % 6 == 0: annual_salary += semi_annual_raise * annual_salary current_savings += r / 12 * current_savings + (portion_saved / 10000) * annual_salary / 12 return current_savings def savings_rate(starting_salary, semi_annual_raise = .07, r = .04, months =36, portion_down_payment = .25, total_cost = 1000000): """Return the best rate of savings using bisection search.""" down_payment = portion_down_payment * total_cost low = 0 high = 10000 portion_saved = (low + high) / 2 epsilon = 100 tries = 0 # Check if reaching target is possible if final_savings(starting_salary, 10000) < down_payment: return False, None, None # Case if possible while abs(final_savings(starting_salary, portion_saved) - down_payment) > epsilon: if final_savings(starting_salary, portion_saved) < down_payment: low = portion_saved else: high = portion_saved portion_saved = int((low + high) / 2) tries += 1 return True, portion_saved, tries starting_salary = float(input("Enter the starting salary: ")) possible, portion_saved, tries = savings_rate(starting_salary) if possible: print(f"Best savings rate: {portion_saved / 10000:.4f}") print(f"Steps in bisection search: {tries}") else: print('It is not possible to pay the down payment in three years.') ''' To simplify things, assume: 1. Your semi­annual raise is .07 (7%) 2. Your investments have an annual return of 0.04 (4%) 3. The down payment is 0.25 (25%) of the cost of the house 4. The cost of the house that you are saving for is $1M. You are now going to try to find the best rate of savings to achieve a down payment on a $1M house in 36 months. Since hitting this exactly is a challenge, we simply want your savings to be within $100 of the required down payment. In​ ps1c.py​, write a program to calculate the best savings rate, as a function of your starting salary. You should use ​bisection search​ to help you do this efficiently. You should keep track of the number of steps it takes your bisections search to finish. You should be able to reuse some of the code you wrote for part B in this problem Test Case 1 >>> Enter the starting salary:​ 150000 Best savings rate:​ 0.4411 Steps in bisection search:​ 12 >>> Test Case 2 >>> Enter the starting salary:​ 300000 Best savings rate:​ 0.2206 Steps in bisection search:​ 9 >>> Test Case 3 >>> Enter the starting salary:​ 10000 It is not possible to pay the down payment in three years. >>> '''
# merge all overlapping intervals def mer (intervals): intervals=sorted([intervals]) new_list=[] start=intervals[0][0][0] end =intervals[0][0][1] print(start,end ) for i in intervals[0][1:]: print(i) if i[0]>=start and i[0]<=end : if i[1]>= start and i[1]<=end : start=start end=end else: if i[0]>=start and i[0]<=end : if i[1]>= start and i[1]>=end : end = intervals[i][1] else: if i[0]>=start and i[0]>=end : if i[1]>= start and i[1]>=end : start= intervals[i[0]] end=intervals[i[1]] print (i) new_list.append([start,end]) return new_list array=[[1,4],[3,6],[7,8]] print(mer(array))
months = ['jan', 'feb', 'march', 'april', 'may'] # Sort list in alphabetical order months.sort() print(months) # Sort list in reversed alphabetical order months.sort(reverse=True) print(months) # Sort list temporarily months = ['jan', 'feb', 'march', 'april', 'may'] print(sorted(months)) print(months) # Reverse a list months = ['jan', 'feb', 'march', 'april', 'may'] months.reverse() print(months)
# Retrieve value from dictionary user = { 'name': 'derrick', 'email': 'derrick@gmail.com' } print(user.get('name'))
#!/usr/bin/env python # -*- coding: utf-8 -*- def f(n): """ Calculate the next step in the collatz sequence. Parameters ---------- n : int Returns ------- int """ if n % 2 == 0: return n / 2 else: return 3*n + 1 if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description="get the collatz sequence for one n" ) parser.add_argument("-n", dest="n", default=20, type=int, help="n") args = parser.parse_args() n = args.n steps = 0 print("steps,n") while n != 1: print("%i,%i" % (steps, n)) n = f(n) steps += 1
#!/usr/bin/env python # -*- coding: utf-8 -*- """Solves https://code.google.com/codejam/contest/4304486/dashboard#s=p1.""" def solve(lists, n): """ Get the missing list. Parameters ---------- lists : list of lists 2*n - 1 lists with integers n : int Returns ------- strictly increasing list of n integers. """ numbers = {} for list_ in lists: for el in list_: if el in numbers: numbers[el] += 1 else: numbers[el] = 1 missing = [] for number, count in numbers.items(): if count % 2 == 1: missing.append(number) assert len(missing) == n return sorted(missing) if __name__ == "__main__": testcases = input() for caseNr in range(1, testcases+1): n = int(raw_input()) lists = [] for i in range(2*n-1): tmp_list = raw_input() tmp_list = [int(el) for el in tmp_list.split(" ")] lists.append(tmp_list) print("Case #%i: %s" % (caseNr, " ".join([str(el) for el in solve(lists, n)])))
#!/usr/bin/env python """Generate datasets.""" # core modules import math # 3rd party modules import matplotlib.pyplot as plt import numpy as np def spiral(radius, step, resolution=.1, angle=0.0, start=0.0, direction=-1): """ Generate points on a spiral. Original source: https://gist.github.com/eliatlarge/d3d4cb8ba8f868bf640c3f6b1c6f30fd Parameters ---------- radius : float maximum radius of the spiral from the center. Defines the distance of the tail end from the center. step : float amount the current radius increases between each point. Larger = spiral expands faster resolution : float distance between 2 points on the curve. Defines amount radius rotates between each point. Larger = smoother curves, more points, longer time to calculate. angle : float starting angle the pointer starts at on the interior start : float starting distance the radius is from the center. direction : {-1, 1} direction of the rotation of the spiral Returns ------- coordinates : List[Tuple[float, float]] """ dist = start + 0.0 coords = [] while dist * math.hypot(math.cos(angle), math.sin(angle)) < radius: cord = [] cord.append(dist * math.cos(angle) * direction) cord.append(dist * math.sin(angle)) coords.append(cord) dist += step angle += resolution return coords def generate(name, nb_datapoints): if name == 'gaussian': d1 = [np.random.normal(loc=[2.0, 2.0], scale=1.0, size=2) for _ in range(nb_datapoints)] print(d1) d2 = [np.random.normal(loc=[-2, -2], scale=1.0, size=2) for _ in range(nb_datapoints)] x1, y1 = zip(*d1) t1 = ['orange'] * nb_datapoints x2, y2 = zip(*d2) t2 = ['blue'] * nb_datapoints x = x1 + x2 y = y1 + y2 t = t1 + t2 elif name == 'spiral': x = [] y = [] t = [] x1, y1 = zip(*spiral(radius=6, step=0.05, direction=-1.0, angle=180)) t1 = ['orange'] * len(x1) x2, y2 = zip(*spiral(radius=6, step=0.05, direction=-1.0, angle=90)) t2 = ['blue'] * len(x2) x = x1 + x2 y = y1 + y2 t = t1 + t2 else: raise NotImplementedError(name) return x, y, t def plot(x, y, t): plt.scatter(x, y, c=t) plt.show() x, y, t = generate(name='spiral', nb_datapoints=100) plot(x, y, t)
#!/usr/bin/env python """Example for learning a regression.""" from keras.models import Sequential from keras.layers import Dense, Dropout, Activation import numpy def plot(xs, ys_truth, ys_pred): """ Plot the true values and the predicted values. Parameters ---------- xs : list Numeric values ys_truth : list Numeric values, same length as `xs` ys_pred : list Numeric values, same length as `xs` """ import matplotlib.pyplot as plt truth_plot, = plt.plot(xs, ys_truth, '-o', color='#00ff00') pred_plot, = plt.plot(xs, ys_pred, '-o', color='#ff0000') plt.legend([truth_plot, pred_plot], ['Truth', 'Prediction'], loc='upper center') plt.savefig('plot.png') # Parameters learning_rate = 0.1 momentum = 0.6 training_epochs = 1000 display_step = 100 # Generate training data train_X = [] train_Y = [] test_X = [] test_Y = [] # First simple test: a linear function from math import sin f = lambda x: sin(x) # Second, more complicated test: x^2 # f = lambda x: x**2 for x in range(-20, 20): train_X.append(float(x)) train_Y.append(f(x)) for x in range(20, 25): train_X.append(float(x)) train_Y.append(f(x)) train_X = numpy.asarray(train_X) train_Y = numpy.asarray(train_Y) test_X = numpy.asarray(test_X) test_Y = numpy.asarray(test_Y) n_samples = train_X.shape[0] model = Sequential() model.add(Dense(512, activation='relu', input_dim=1)) model.add(Dense(512, activation='relu')) # model.add(Dropout(0.5)) # model.add(Dense(1, activation='relu')) model.add(Dense(1, activation='linear')) model.summary() # let's train the model using SGD + momentum (how original). # sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_absolute_error', optimizer='rmsprop', metrics=['accuracy']) nb_epoch = 2 batch_size = 64 history = model.fit(train_X, train_Y, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(test_X, test_Y)) score = model.evaluate(test_X, test_Y, verbose=2) print(score) # print('Test score:', score[0]) # print('Test accuracy:', score[1]) # Get output and plot it xs = [] ys_pred = [] ys_truth = [] test_X = [] for x in range(-40, 40): test_X.append(float(x)) for x in test_X: xs.append(x) ret = model.predict_proba(numpy.array([x])) ys_pred.append(list(ret)[0][0]) ys_truth.append(f(x)) plot(xs, ys_truth, ys_pred)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Generate a testset for range minimum queries.""" from random import randint, seed def generate_numbers(n, filename, minimum, maximum): """ Generate n numbers in the range [minimum, maximum] and store them in filename. Parameters ---------- n : int filename : str minimum : int maximum : int """ seed(0) with open(filename, "w") as f: for i in range(n): if i == 0: f.write(str(randint(minimum, maximum))) else: f.write(" " + str(randint(minimum, maximum))) def generate_queries(nr_of_numbers, nr_of_queries, filename): """ Generated minimum range queries and write them to `filename`. Parameters ---------- nr_of_numbers : int nr_of_queries : int filename : str """ seed(42) with open(filename, "w") as f: for i in range(nr_of_queries): start = randint(0, nr_of_numbers-1) end = randint(start, nr_of_numbers-1) query = str(start) + ":" + str(end) if i + 1 == nr_of_queries: f.write(query) else: f.write(query + "\n") def generate_testset(nr_of_numbers, nr_of_queries, min_number=0, max_number=1000000): """ Generate a testset and store it in text files. Parameters ---------- nr_of_numbers : int nr_of_queries : int min_number : int max_number : int """ generate_numbers(nr_of_numbers, "Testing/%i.numbers.txt" % nr_of_numbers, min_number, max_number) generate_queries(nr_of_numbers, nr_of_queries, "Testing/%i.%i.queries.txt" % (nr_of_numbers, nr_of_queries)) if __name__ == "__main__": from argparse import ArgumentParser parser = ArgumentParser() # Add more options if you like parser.add_argument("-n", "--numbers", dest="numbers", type=int, default=42, help="how many numbers should the array have?") parser.add_argument("-q", "--queries", dest="queries", type=int, default=10, help="how many queries do you want to generate") args = parser.parse_args() generate_testset(args.numbers, args.queries)
name = input() name2 = input() print('Hello {} {}! You just delved into python.'.format(name , name2))
n = int(input()) list1=[] for p in range(n): a = input() b = a.split(" ") if(b[0] == 'insert'): i = int(b[1]) j = int(b[2]) list1.insert(i,j) elif(b[0] == 'remove' ): k = int(b[1]) list1.remove(k) elif(b[0] == 'append'): l = int(b[1]) list1.append(l) elif(b[0] == 'sort'): list1.sort() elif(b[0] == 'print'): print(list1) elif(b[0] == 'pop'): list1.pop() elif(b[0] == 'reverse'): list1.reverse()
''' HEllO!!!! Install These all Modules Before running the code :) ''' import requests # it sends HTTP request with python from bs4 import BeautifulSoup #Beautiful soup library is used for extracting data from website HTMl content import pprint # it prettify's the syntax of result import json res = requests.get('https://news.ycombinator.com/news') #requesting and getting response soup = BeautifulSoup(res.text, 'html.parser') # it creates a 'BeautifulSoup' object links = soup.select('.storylink') # here ".storylink" is class of the links for which we select it and take all the links.. ''' IMPORTANT NOTE: Go Through BeautifulSoup documentation Its easy to learn ' :-) ' ''' subtext = soup.select('.subtext') def sort_stories_by_votes(hnlist): return sorted(hnlist, key= lambda k:k['votes'], reverse=True) def create_custom_hn(links, subtext): hn = [] for idx, item in enumerate(links): title = item.getText() href = item.get('href', None) vote = subtext[idx].select('.score') if len(vote): points = int(vote[0].getText().replace(' points', '')) if points > 99: hn.append({'title': title, 'link': href, 'votes': points}) return sort_stories_by_votes(hn) pprint.pprint(create_custom_hn(links,subtext)) ''' {{{{{ THANKYOU }}}}} '''
# ***** Building a Trie in Python *****# # ***** PROBLEM DESCRIPTION ********# #Before we start let us reiterate the key components of a Trie or Prefix Tree. A trie is a tree-like data structure that stores a dynamic set of strings. Tries are commonly used to facilitate operations like predictive text or autocomplete features on mobile phones or web search. #Before we move into the autocomplete function we need to create a working trie for storing strings. We will create two classes: #A Trie class that contains the root node (empty string) #A TrieNode class that exposes the general functionality of the Trie, # like inserting a word or finding the node which represents a prefix. # Give it a try by implementing the TrieNode and Trie classes below! ## Represents a single node in the Trie import collections from typing import List class TrieNode: def __init__(self): ## Initialize this node in the Trie self.end_word = False self.word = {} def insert(self, char): ## Add a child node in this Trie if char not in self.word: self.word[char] = TrieNode() def print_node(self): node = self.word for key,elem in node.items(): print(key,':',elem.end_word) if elem!=None: elem.print_node() ## The Trie itself containing the root node and insert/find functions class Trie: def __init__(self): ## Initialize this Trie (add a root node) self.root = TrieNode() def insert(self, word): ## Add a word to the Trie current_node = self.root for char in word: if char not in current_node.word: current_node.insert(char) current_node = current_node.word[char] current_node.end_word = True def print_trie(self): node = self.root node.print_node() def find(self, prefix): current_node= self.root for char in prefix: if char in current_node.word: current_node = current_node.word[char] else: return None return current_node def suffixes(self, suffix = ''): ## Recursive function that collects the suffix for ## all complete words below this point output='' ans =[] if suffix!='': current_node=self.find(suffix) if current_node==None: return [] else: #current_node.print_node() self.suff(current_node,output,ans) return ans def suff(self, current_node: TrieNode, output:str, ans): for key,elem in current_node.word.items(): if elem.end_word == True: ans.append(output+key) self.suff(elem, output+key, ans) return ## Find the Trie node that represents this prefix root = TrieNode() #root.insert('c') #root.insert('d') #root.insert('e') #root.insert('c') t = Trie() t.insert("lunes") t.insert("luna") t.insert("lunesa") t.insert("luz") print(t.suffixes("lun")) #print(t.suffixes('l')) MyTrie = Trie() wordList = [ "ant", "anthology", "antagonist", "antonym", "fun", "function", "factory", "trie", "trigger", "trigonometry", "tripod" ] for word in wordList: MyTrie.insert(word) #MyTrie.find("an").print_node() print(MyTrie.suffixes("")) #return empty list print(MyTrie.suffixes("an")) #return all word staring with an print(MyTrie.suffixes("f")) #return all word staring with f print(MyTrie.suffixes("tri")) #return all word staring with tri print(MyTrie.suffixes("id")) #return empty list
class Group(object): def __init__(self, _name): self.name = _name self.groups = [] self.users = [] def add_group(self, group): self.groups.append(group) def add_user(self, user): self.users.append(user) def get_groups(self): return self.groups def get_users(self): return self.users def get_name(self): return self.name def print_group(self): if self.groups!=None: print("--",self.name) for elem in self.groups: print("---",elem.name) def print_users(self): if self.groups!=None: print("Group:", self.name) print("Users:",self.users) for elem in self.groups: elem.print_users() def is_user_in_group(user, group): """ Return True if user is in the group, False otherwise. Args: user(str): user name/id group(class:Group): group to check user membership against """ if group != None: for elem in group.users: if elem==user: return True for elem in group.groups: result=is_user_in_group(user,elem) if result==True: return True return False ##Test 1 ## no childs ########################################### parent = Group("parent") #Create User user_ = "User_1" #Asociated User parent.add_user(user_) print("Test #1 no childs") print("Belongs User_1 user to parent?",is_user_in_group("User_1", parent)) ##Test 2 ## child and 1 subchild ########################################### parent = Group("parent") child = Group("child") sub_child = Group("subchild") #Asociate parent to child parent.add_group(child) #Asociate child to sub_child child.add_group(sub_child) #Create User user_ = "User_1" #Asociated User sub_child.add_user(user_) print("Test #2 1 child and 1 subchild") print("Belongs User_1 user to subchild?",is_user_in_group("User_1", sub_child)) print("Belongs User_1 user to child?",is_user_in_group("User_1", child)) print("Belongs User_1 user to parent?",is_user_in_group("User_1", parent)) ##Test ## 3 multiple childs and multiple subchilds ########################################### parent = Group("parent") child_1 = Group("child_1") sub_child_1_1= Group("Administrator") child_2 = Group("child_2") sub_child_1_2 = Group("Domain Admins") child_3 = Group("child_3") sub_child_2_3 = Group("Enterprise Admins") sub_child_2_4 = Group("Remote Desktop") sub_child_3_5 = Group("Event Log Readers") #Asociating parent to childs parent.add_group(child_1) parent.add_group(child_2) parent.add_group(child_3) #Asociating child to sub_childs child_1.add_group(sub_child_1_1) child_1.add_group(sub_child_1_2) child_2.add_group(sub_child_2_3) child_2.add_group(sub_child_2_4) child_3.add_group(sub_child_3_5) #Create Users user_1_1 = "Adam" user_1_2 = "Angel" user_1_3 = "David" user_2_4 = "Victor" user_2_5 = "Matthew" user_2_6 = "Linda" user_2_7 = "Albert" user_3_8 = "Mary" #Asociating Users sub_child_1_1.add_user(user_1_1) #Adam is an Administrator sub_child_1_1.add_user(user_1_2) #Angel is an Administrator sub_child_1_2.add_user(user_1_3) #David is a Domain Admin sub_child_2_3.add_user(user_2_4) #Victor Enterprise Admin sub_child_2_3.add_user(user_2_5) #Mattthew Enterprise Admin sub_child_2_3.add_user(user_2_6) #Linda Enterprise Admin sub_child_2_4.add_user(user_2_7) #Albert is a Remote Desktop sub_child_3_5.add_user(user_3_8) #Mary is a Event Log Reader print("Test #3 multiple childs and multiple subchilds") print("Belongs Adam user to Administrator Group?",is_user_in_group("Adam", sub_child_1_1)) #Returns True Because Adam is just an Administrator print("Belongs Adam user to Domain Admins?",is_user_in_group("Adam", sub_child_1_2)) #Returns False Because Adam is just an Administrator print("Belongs Angel user to Administrator Group?",is_user_in_group("Angel", sub_child_1_1)) #Returns True Because Angel is just an Administrator print("Belongs Angel user to Domain Admins?",is_user_in_group("Angel", sub_child_1_2)) #Returns False Because Angel is just an Administrator print("Belongs Linda user to Enterprise Admins?",is_user_in_group("Linda", sub_child_2_3)) #Returns True Because Linda is just an Enterprise Admin print("Belongs Linda user to Remote Desktop?",is_user_in_group("Linda", sub_child_2_4)) #Returns False Because Linda is an Enterprise Admin print("Belongs Linda user to child2?",is_user_in_group("Linda", child_2)) #Returns True Because Linda is in Group Category child2 print("Belongs Linda user to child1?",is_user_in_group("Linda", child_1)) #Returns False Because Linda is not in Group Category child1 print("Belongs Linda user to parent?",is_user_in_group("Linda", parent)) #Returns True Because Linda is in Group Category child2 - sub_child_2_3 print("Belongs Linda user to child2?",is_user_in_group("Linda", child_3)) #Returns False Because Linda is in Group Category child2
country_1 = input('請輸入國家(中文): ') age_1 = input('請輸入年齡: ') age_1 = float(age_1) if country_1 == '台灣': if age_1 >= 18: print('你可以開車') else: print('你還無法開車') elif country_1 == '美國': if age_1 >= 16: print('你可以開車') else: print('你還無法開車') else: print('你只能輸入美國或台灣') country_2 = input('請再次輸入國家(中文): ') age_2 = input('請再次輸入年齡: ') age_2 = float(age_2) if country_2 == '台灣': if age_2 >= 18: print('你可以開車') else: print('你還無法開車') elif country_2 == '美國': if age_2 >= 16: print('你可以開車') else: print('你還無法開車')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 11 22:02:34 2019 @author: tcm410 """ values = [] values.append(1) values.append(3) values.append(5) print('first time:', values) values=values[1:3] #slice function print('second time:', values) print('string to list:', list('tin')) print('list to string:', ''.join(['g','o','l','d'])) element = 'helium' print(element[0:-1]) element = 'fluorine' #lookup stride in manual print(element[::2]) #https://docs.python.org/3/library/stdtypes.html#typesseq print(element[::-1]) #letters = list('gold') #result = sorted(letters) #print(letters, result) #letters = list('gold') #print(letters.sort(gold)) #lookup in manual #print(letters, result) old = list('gold') new = old new[0] = 'D' #item 0 of new replaced by D print(new, old) old = list('gold') new = old[:] #a copy is returned iterable[:] https://docs.python.org/3/library/stdtypes.html?highlight=slice%20assignment new[0] = 'D' print(new, old)
# Generate a basic quiver plot (vectors) inside a sphere from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': fig = plt.figure() ax = fig.gca(projection='3d') ax.quiver([0,0,0],[0,0,0],[0,0,0],[0,0,1],[0,1,0],[1,0,0], normalize=True, color=['r','g','b']) # Make data u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) # Plot the surface ax.plot_surface(x, y, z, alpha=0.1, color='black') plt.show()
from collections import namedtuple Point = namedtuple('Point', ('x', 'y')) def sign (p1, p2, p3): return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); while True: try: x = list(map(float, input().split())) p1 = Point(x[0], x[1]) p2 = Point(x[2], x[3]) p3 = Point(x[4], x[5]) pp = Point(x[6], x[7]) b1 = sign(pp, p1, p2) < 0.0 b2 = sign(pp, p2, p3) < 0.0 b3 = sign(pp, p3, p1) < 0.0 if (b1 == b2) and(b2 == b3): print('YES') else: print('NO') except: break
import tkinter as tk root = tk.Tk() canvas1 = tk.Canvas(root, width=300, height=300) canvas1.pack() def hello(): label1 = tk.Label(root, text='Hello World!', fg='green', font=('helvetica', 12, 'bold')) canvas1.create_window(150, 200, window=label1) button1 = tk.Button(text='Click Me', command=hello, bg='brown', fg='white') canvas1.create_window(150, 150, window=button1) root.mainloop()
# Logger. Сыпем действия в лог. # Рекомендуется использовать только функцию write_to_log. class Logger: def __init__(self): self.logfile = "log.log" self.logfile_inst = None def open_file_for_write(self): self.logfile_inst = open(self.logfile,'a') def write_to_log(self, text): self.open_file_for_write() self.logfile_inst.write(text) self.logfile_inst.write("\n") self.logfile_inst.close()
import random number = random.randint(1, 100) while (True): user_guess = int(raw_input("pick a number between 1 and 100:")) #think about what type the input is. print(number) if user_guess > number: print("Lower\n") elif user_guess < number: print("Higher\n") else: print("Correct")
import numpy as np import pandas as pd gp = pd.DataFrame([[30133, 2419.76], [28000,2172.90],[22286, 1350.11], [21500, 1137.52], [19530, 1562.45], [18595, 3016.3], [17000, 1375.00], [13400, 1591.76]], index=["shanghai", "beijing", "shenzhen", "guangzhou", "chongqing", "tianjing", "suzhou", "wuhan"], columns=["GDP", "Population"]) gp.index.name="City_Name" gp.columns.name="Items" print gp dict_gdp={"GDP":[30133, 28000, 22286, 21500],"Population":[2419.76, 2172.90, 1350.11, 1137.52]} print pd.DataFrame.from_dict(dict_gdp) print pd.DataFrame.from_dict(dict_gdp, orient="index") print pd.read_csv("d:/datapy/datapy/pands/gdp-population.csv", names=["CITY", "GDP", "POP"], skiprows=[0], index_col=0)
# create array from numpy import array # create array list1 = [1.0, 2.0, 3.0] a = array(list1) # display array print(a) # display array shape print(a.shape) # display array data type print(a.dtype) # create empty array from numpy import empty b = empty([3,3]) print(b) #The values or content of the created array will be random and will need to be assigned before use # create zero array from numpy import zeros c = zeros([3,5]) print(c) # create one array from numpy import ones d = ones([5,2]) print(d) # create array with Vertical Stack - vstack from numpy import array from numpy import vstack # create first array a1 = array([1,2,3]) print(a1) # create second array a2 = array([4,5,6]) print(a2) # vertical stack a3 = vstack((a1, a2)) print(a3) print(a3.shape) # create array with Horizontal Stack - hstack from numpy import array from numpy import hstack # create first array b1 = array([1,2,3]) print(b1) # create second array b2 = array([4,5,6]) print(b2) # create horizontal stack b3 = hstack((b1, b2)) print(b3) print(b3.shape) # create one-dimensional list to an array from numpy import array # list of data data = [11, 22, 33, 44, 55] # array of data data = array(data) print(data) print(type(data)) # create two-dimensional list to an array from numpy import array # list of data data1 = [[11, 22], [33, 44], [55, 66]] # array of data data1 = array(data1) print(data1) print(type(data1)) # index a one-dimensional array from numpy import array # define array data2 = array([11, 22, 33, 44, 55]) # index data print(data2[0]) print(data2[4]) #print(data2[5]) print(data2[-1]) print(data2[-5]) # index two-dimensional array from numpy import array # define array data3 = array([ [11, 22], [33, 44], [55, 66]]) # index data print(data3[0,0]) print(data3[0,]) # slice a one-dimensional array from numpy import array # define array data4 = array([11, 22, 33, 44, 55]) print(data4[:]) print(data4[0:1]) #starts with 0 with 1 excluded print(data4[0:2]) #starts with 0 with 2 excluded print(data4[1:3]) #starts with 1 with 3 excluded print(data4[-2:]) #starts with -2 & so on -3,-4,-5 etc (in -ve order) # slice a two-dimensional array from numpy import array # define array data5 = array([ [11, 22, 33], [44, 55, 66], [77, 88, 99]]) # separate data X= data5[:, :] #all rows & all columns print(X) y= data5[0:1, :] #0 to 1st row (excluding 1st row) & all columns print(y) z=data5[:3, :] print(z) w=data5[0:2, :2] print(w) t=data5[2:, 1:] print(t) # split train and test data from numpy import array # define array data = array([ [11, 22, 33], [44, 55, 66], [77, 88, 99]]) # separate data split = 2 train,test = data[:split,:],data[split:,:] print(train) print(test) # shape of one-dimensional array from numpy import array # define array data = array([11, 22, 33, 44, 55]) print(data.shape) # shape of a two-dimensional array from numpy import array # list of data data = [[11, 22], [33, 44], [55, 66]] # array of data data = array(data) print(data.shape) # row and column shape of two-dimensional array from numpy import array # list of data data = [[11, 22],[33, 44], [55, 66]] # array of data data = array(data) print('Rows: %d' % data.shape[0]) print('Cols: %d' % data.shape[1]) # reshape 1D array to 2D from numpy import array # define array data = array([11, 22, 33, 44, 55]) print(data) print(data.shape) # reshape data1 = data.reshape((data.shape[0], 1)) print(data1.shape) print(data1) #reshape 2D array to 1D import numpy as np a = np.array([[1, 2], [3, 4], [5, 6]]) a_flat = a.flatten() print(a_flat) # reshape 2D array to 3D from numpy import array # list of data data = [[11, 22], [33, 44], [55, 66]] # array of data data = array(data) print(data.shape) print (data) # reshape data = data.reshape((data.shape[0], data.shape[1], 1)) print(data.shape) print(data) #Array Broadcasting #Arrays with different sizes cannot be added, subtracted, or generally be used in arithmetic. #A way to overcome this is to duplicate the smaller array so that it has the dimensionality #and size as the larger array. This is called array broadcasting # broadcast scalar to one-dimensional array from numpy import array # define array a = array([1, 2, 3]) print(a) # define scalar b = 2 print(b) # broadcast c = a + b #([1+2, 2+2, 3+2]) print(c) # broadcast scalar to two-dimensional array from numpy import array # define array A = array([ [1, 2, 3], [1, 2, 3]]) print(A) # define scalar b = 2 print(b) # broadcast C = A + b print(C) # broadcast one-dimensional array to two-dimensional array from numpy import array # define two-dimensional array A = array([ [1, 2, 3], [1, 2, 3]]) print(A) # define one-dimensional array b = array([1, 2, 3]) print(b) # broadcast C = A + b print(C) # broadcasting error from numpy import array # define two-dimensional array A = array([ [1, 2, 3], [1, 2, 3]]) print(A.shape) # define one-dimensional array b = array([1, 2]) print(b.shape) # attempt broadcast C = A + b print(C) #Arithmetic, including broadcasting, can only be performed when the shape of #each dimension in the arrays are equal or one has the dimension size of 1. #The dimensions are considered in reverse order, starting with the trailing dimension.
import csv import json #We need to create a list of users whose passwords have been compromised. compromised_users=[] with open("passwords.csv") as password_file: password_csv=csv.DictReader(password_file) for password_row in password_csv: #print(password_row['Username']) compromised_users.append(password_row) #print(compromised_users) #Start a new with block, opening a file called compromised_users.txt. # Open this file in write-mode, saving the file object as compromised_user_file. with open("compromised_users.txt","w") as compromised_user_file: for compromised_user in compromised_users: #Write the username of each compromised_user in compromised_users to compromised_user_file. compromised_user_file.write(compromised_user['Username']+", ") with open("boss_message.json","w") as boss_message: boss_message_dict={"recipient":"The Boss", "message" : "Mission Success"} #Write out boss_message_dict to boss_message using json.dump() json.dump(boss_message_dict,boss_message) #Now that we’ve safely recovered the compromised users we’ll want to remove the "passwords.csv" # file completely. with open("new_passwords.csv","w") as new_passwords_obj: slash_null_sig=""" _ _ ___ __ ____ / )( \ / __) / \(_ _) ) \/ ( ( (_ \( O ) )( \____/ \___/ \__/ (__) _ _ __ ___ __ _ ____ ____ / )( \ / _\ / __)( / )( __)( \ ) __ (/ \( (__ ) ( ) _) ) D ( \_)(_/\_/\_/ \___)(__\_)(____)(____/ ____ __ __ ____ _ _ ___ / ___)( ) / _\ / ___)/ )( \# (___) \___ \/ (_/\/ \ \___ \) __ ( (____/\____/\_/\_/ (____/\_)(_/ __ _ _ _ __ __ ( ( \/ )( \( ) ( ) / /) \/ (/ (_/\/ (_/\ \_)__)\____/\____/\____/""" new_passwords_obj.write(slash_null_sig)
# https://www.hackerrank.com/challenges/nested-list/problem if __name__ == '__main__': result = {} min_2 = 101.0 min_1 = 101.0 for _ in range(int(input())): name = input() score = float(input()) if score in result: result[score].append(name) else: result[score] = [name] new_list = [] for i in result: new_list.append([i, result[i]]) new_list.sort() res = new_list[1][1] res.sort() print (*res, sep = '\n')
x = int(input()) for i in range(1, x+1): if(x%i == 0): print(i, end = ' ')
counties = ["Arapahoe", "Denver", "Jefferson"] # if counties[1] == 'Denver': # print(counties[1]) # if "El Paso" in counties: # print("El Paso is in the list of counties") # else: # print("El Paso is not in the list of counties") # if "Arapahoe" in counties and "El Paso" in counties: # print("Arapahoe and El Paso are in the list of counties.") # else: # print("Arapahoe or El Paso is not in the list of counties") # if "Arapahoe" in counties or "El Paso" in counties: # print("Arapahoe or El Paso is in the list of counties.") # else: # print("Arapahoe and El Paso are not in the list of counties.") # for county in counties:2 # print(county) #Iterate Through Lists and Tuples # for county in counties: # print(county) # counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} # for county in counties_dict: # print(county) # for county in counties_dict.keys(): # print(county) # for voters in counties_dict.values(): # print(voters) # for county in counties_dict: # print(counties_dict[county]) # for county in counties_dict: # print(counties_dict.get(county)) # for county,voters in counties_dict.items(): # print(county, voters) # for county,voters in counties_dict.items(): # print(county + " county has " +str(voters)+ " registered voters") # for county,voters in counties_dict.items(): # print(f"{county} county has {voters:,} registered voters") # for county, voters in counties_dict.items(): # print(f"{county} count has {voters} registered voters.") voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] #for county_dict in voting_data: #print(county_dict) for county_dict in range(len(voting_data)): print(voting_data[county_dict]) # for county_dict in voting_data: # for value in county_dict.values(): # print(value) # for county_dict in voting_data: # print(county_dict['registered_voters']) # for county_dict in voting_data: # print(county_dict['county']) ################## Need TO COMPLETE SKILL DRILL
#!/usr/local/bin/python3 # -*- coding:UTF-8 -*- """ @desc: 描述 @Time: 2019/9/26 10:46 下午 @Author: lvxh """ import sys import doctest # 斐波那契(fibonacci)数列模块 def fib(n): # 定义到 n 的斐波那契数列 a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a + b print() def fib2(n): # 返回到 n 的斐波那契数列 result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a + b return result dir(fib(3)) dir(sys) a = 1 b = [2, 3, 4] dir() table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} for name, number in table.items(): print('{0:10} ==> {1:10d}'.format(name, number)) def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) doctest.testmod() # print(a)
#!/usr/local/bin/python3 # -*- coding:UTF-8 -*- """ @desc: 选择排序 @Time: 2019/10/11 3:57 下午 @Author: lvxh """ import random a = {} num = 10 for i in range(num): a[i] = random.randint(1, 100) print(a) # del a[2] # print(a) def chose_sort(arr): a = [] while len(arr) > 0: min = None min_k = None for k,v in arr.items(): if (min == None): min = v min_k = k if (v < min): min = v min_k = k a.append(min) del arr[min_k] return a print(chose_sort(a))
#coding:utf8 #desc: 递归输出当前目录下的子目录和文件 #author: me import os import time def dirlist(pathname,level=1): if level == 1: print "%s" % pathname for d in os.listdir(pathname): time.sleep(1) print('%s|-- %s' %('| '* (level-1),d)) #这一行控制树形的格式,level 控制输入 | 的数量,当前层级减1 if os.path.isdir(os.path.join(pathname,d)): #必须用os.path.join(pathname,d) 这个函数,否则无法进入第3层子目录 dirlist(os.path.join(pathname,d),level+1) #level 控制输入 | 的数量,每深入一层,| 数量加1 dirlist(".")
#!/usr/bin/env python #coding:utf8 def shout(word="yes"): """" this is shout function documents: demoe : shout(paramsStr) print ParamsStr """ return word.capitalize()+"!" help(shout) times = 10 print times print times print times print 1.1 import decimal print decimal.Decimal(1.1)
import tkinter window = tkinter.Tk() window.title("My First GUI Program") window.minsize(width=500, height=300) window.config(padx=200, pady=200) #Label my_label = tkinter.Label(text="I am a label", font=("Arial", 24, "bold")) my_label.grid(column=0, row=0) my_label["text"] = "New Text" my_label.config(text="New Text") my_label.config(padx=50, pady=50) #button def button_clicked(): print("I got clicked") my_label.config(text=input.get()) my_label.grid(column=0, row=0) button = tkinter.Button(text="Click Me", command=button_clicked) button.grid(column=1, row=1) #Entry input = tkinter.Entry(width=10) input.grid(column=3, row=2) input.get() button1 = tkinter.Button(text="Click Me", command=button_clicked) button1.grid(column=2, row=0) window.mainloop() # def add(*arg): # return sum(arg) # add(5,4,8,7,5,4,8)
import tkinter from tkinter import messagebox import string from random import choice, randint import pyperclip import json # ---------------------------- PASSWORD GENERATOR ------------------------------- # def generate_password(): characters = string.ascii_letters + string.digits + string.punctuation password = "".join(choice(characters) for x in range(randint(12, 16))) password_input.delete(0, 'end') password_input.insert(0, password) pyperclip.copy(password) # ---------------------------- SAVE PASSWORD ------------------------------- # def add_password(): website = website_input.get() email = email_input.get() password = password_input.get() new_data = {website: { "email": email, "password": password, }} if len(website) == 0 or len(password) == 0: messagebox.showinfo(title="Oh No!", message="Please make sure you fill out all the fields") else: # messagebox.askokcancel(title=website, message= f"These are the details entered: \nEmail: {email}" # f"\nPassword: {password} \nIs this ok to save?") try: with open("data.json", "r") as plist: # plist.write(f"{website}, {email}, {password}\n") # Reading old data data = json.load(plist) except FileNotFoundError: with open("data.json", "w") as plist: json.dump(new_data, plist, indent=4) # except json.JSONDecodeError: # data = dict() else: # Updating old data with new data data.update(new_data) with open("data.json", "w") as plist: # Saving updated data json.dump(data, plist, indent=4) finally: website_input.delete(0, 'end') password_input.delete(0, 'end') # ---------------------------- FIND PASSWORD --------------------------- # def find_password(): website = website_input.get() email = email_input.get() if len(website) == 0 or len(email) == 0: messagebox.showinfo(title="Input Required", message="Please make sure you have the website and email filled out") else: try: with open("data.json", "r") as data_file: data = json.load(data_file) except FileNotFoundError: messagebox.showinfo(title="No File", message="File is not created yet.") else: # new_data = data.get(website[:]) if website in data: web = data[website] messagebox.showinfo(title="Your Saved Password", message=f"Email: {web['email']}\n Password: {web['password']}") else: messagebox.showinfo(title="Error", message=f"No details for {website} exists.") # messagebox.showinfo(title="Password Ready", message=f"Email: {newemail}\n Password: {newpassword}") # ---------------------------- UI SETUP ------------------------------- # window = tkinter.Tk() window.title("Password Manager") window.config(padx=50, pady=50) canvas = tkinter.Canvas(width=200, height=200, highlightthickness=0) lock = tkinter.PhotoImage(file="logo.png") canvas.create_image(100, 100, image=lock) canvas.grid(column=1, row=0) # labels website_label = tkinter.Label(text="website:") website_label.grid(column=0, row=1) email_label = tkinter.Label(text="email/username:") email_label.grid(column=0, row=2) password_label = tkinter.Label(text="password:") password_label.grid(column=0, row=3) # entries website_input = tkinter.Entry(width=21) website_input.grid(column=1, row=1) website_input.focus() email_input = tkinter.Entry(width=38) email_input.grid(column=1, row=2, columnspan=2) email_input.insert(0, "thomasisthebest@gmail.com") password_input = tkinter.Entry(width=21) password_input.grid(column=1, row=3) # buttons search_button = tkinter.Button(text="Search", width=13, command=find_password) search_button.grid(column=2, row=1) password_button = tkinter.Button(text="Generate Password", width=13, command=generate_password) password_button.grid(column=2, row=3) add_button = tkinter.Button(text="Add", width=36, command=add_password) add_button.grid(column=1, row=4, columnspan=2) window.mainloop()
seq = ["nestor", "hugo", "gomez", "franco", 45, 22, False, "Python"] # Show items and indexes from sequence using the range function for i in range(len(seq)): print("index", i, seq[i]) # Show items and indexes from sequence using a wrap class class Indexed: def __init__(self, seq): self.seq = seq def __getitem__(self, i): return self.seq[i], i for item, index in Indexed(seq): print("index", index, item) # Show items and indexes from sequence using the zip function def IndexedFunc(seq): indices = range(len(seq)) return zip(seq, indices) zipped = IndexedFunc(seq) for tuple in zipped: print("index", tuple[1], tuple[0])
#!/usr/bin/env python # coding: utf-8 # # AMOGH G. LONARE # # TASK 1 : Prediction using Supervised ML # Predict the percentage of an student based on the no. of study hours. # # IMPORTING LIBRARIES # In[34]: import numpy as np # In[35]: import pandas as pd import matplotlib.pyplot as plt import seaborn as snb import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[36]: link = "https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv" data = pd.read_csv(link) print("Data is imported succesfully") data.head() # In[37]: data.shape data.describe() # In[38]: data.info() # In[39]: data.isnull().sum() # In[40]: data.plot(x="Hours",y="Scores",style="o") plt.title("Study Hours v/s Percentage Scores") plt.ylabel("Scores in Percentage") plt.xlabel("No of Hours") plt.show() # In[41]: sns.regplot(x=data["Hours"],y=data["Scores"],data=data) plt.title("Study Hours vs Percentage Scores") plt.xlabel("No of Hours") plt.ylabel("Scores in Percentage") plt.show() # In[ ]: # In[42]: sns.regplot(x=data["Hours"],y=data["Scores"],data=data) plt.title("Study Hours vs Percentage Scores") plt.xlabel("No of Hours") plt.ylabel("Scores in Percentage") plt.show() # It can be see that there is a +ve correlationship between the study hours and the percentage scores. # In[43]: x = data.iloc[:,:-1].values y = data.iloc[:,1].values # In[44]: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) # In[45]: from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) # In[46]: print("Coefficient :", model.coef_) print("Intercept :", model.intercept_) # In[47]: line = model.coef_*x - model.intercept_ plt.scatter(x,y) plt.plot(x, line, color="red", label="Regression Line") plt.legend() plt.show() # In[48]: y_preds = model.predict(X_test) # In[49]: df = pd.DataFrame({'Actual': y_test, 'Predicted': y_preds}) df # In[50]: print("Training Score :", model.score(X_train, y_train)) print("Testing Score :", model.score(X_train, y_train)) # In[51]: df.plot(kind="bar", figsize=(9,5)) plt.grid(which="major",linewidth='0.5', color='blue') plt.grid(which="minor",linewidth='0.5', color='red') # # Task 2 : What if Student studies for 9.25 hours/day # In[52]: hours = 9.25 test = np.array([hours]) test = test.reshape(-1,1) new_pred = model.predict(test) print(f"No. of hours = {hours}") print(f"Predicted Acore = {new_pred[0]}") # # Final Step To Evaluating This Model # In[56]: from sklearn import metrics print("Mean Absolute Error :", metrics.mean_absolute_error(y_test, y_preds)) print("Mean Squared Error :", metrics.mean_squared_error(y_test, y_preds)) print("Root Mean Squared Error :", np.sqrt(metrics.mean_squared_error(y_test, y_preds))) print("R-2 :", metrics.r2_score(y_test,y_preds)) # # Thank You # In[ ]:
# Necessary for the program import json import zipfile import sys # Just used for file selection gui from tkinter.filedialog import askopenfilename from tkinter import Tk Tk().withdraw() history = askopenfilename(title = "Select Zip file for analysis",filetypes = (("zip files","*.zip"),("all files","*.*"))) # All variables distance_bicycle = 0 distance_vehicle = 0 distance_foot = 0 distance_bus = 0 distance_plane = 0 distance_subway = 0 failed = 0 success = 0 # Select the time period to look through period = input("=============\n1. All-Time (all) \n2. Specific Year (####) [Example: 2020]\n3. Specific Year/Month (####_MONTH) [Example: 2020_JANUARY]\nChoose a time period (in specified format)\t") # Given a json.load() dict, iterates through the dicts of the first key, # "timelineObjects". If the dict/key is an "activitySegment", # looks for "distance" and "activityType" keys and their values. # Stores the distance within the corresponding activityType variable. def GetDistance(data): for i in data['timelineObjects']: global success, failed, distance_bicycle, distance_bus, distance_foot, distance_plane, distance_subway, distance_vehicle try: if "activitySegment" in i: activityType = i["activitySegment"].get("activityType") if (activityType == "IN_PASSENGER_VEHICLE") or (activityType == "IN_VEHICLE"): distance_vehicle += i["activitySegment"].get("distance") if activityType == "CYCLING": distance_bicycle += i["activitySegment"].get("distance") if (activityType == "WALKING") or (activityType == "RUNNING"): distance_foot += i["activitySegment"].get("distance") if (activityType == "IN_BUS"): distance_bus += i["activitySegment"].get("distance") if (activityType == "FLYING"): distance_plane += i["activitySegment"].get("distance") if (activityType == "IN_TRAIN") or (activityType == "IN_SUBWAY"): distance_subway += i["activitySegment"].get("distance") success += 1 else: pass except: failed += 1 pass # Reads through every file in the Zip file, except "Location History.json" and # "archive_browser.html". Sends the files to GetDistance. with zipfile.ZipFile(history,'r') as z: for filename in z.namelist(): try: print(filename) with z.open(filename) as f: if (filename != "Takeout/Location History/Location History.json") and (filename != "Takeout/archive_browser.html"): if period == "all": data = json.load(f) GetDistance(data) elif period in filename: data = json.load(f) GetDistance(data) else: pass else: pass except: pass # Printing the recorded values print("=============") print("File:\t\t" + history) print("Biked:\t\t" + str(distance_bicycle/1000) + " km") print("Walked/Ran:\t" + str(distance_foot/1000) + " km") print("Driven:\t\t" + str(distance_vehicle/1000) + " km") print("Bussed:\t\t" + str(distance_bus/1000) + " km") print("Flew:\t\t" + str(distance_plane/1000) + " km") print("Subway:\t\t" + str(distance_subway/1000) + " km") print("Success Rate:\t" + str(success/(failed+success)*100) + " %")
import os class Filelo(object): filename = None def __init__(self,filename): self.filename = filename def ReadFile(self): try: f = open(self.filename, "r") text = f.read() print(text) f.close() except IOError: print(self.filename + " not found") def CopyToNewFile(self): oFileName = self.filename + "_copy.txt" # print(oFileName) with open(self.filename, "r") as o, open(oFileName,"w") as n: for line in o: n.write(line) def ReplaceWord(self, ofile,text,word): f = open(self.filename,"r") data = f.read() # print(type(data)) data = data.replace(text,word) fnew = open(ofile,"w") fnew.write(data) f.close() fnew.close() fObj = Filelo("testfile") # fObj.ReadFile() # fObj.CopyToNewFile() fObj.ReplaceWord("hello.txt","file", "filelo")
#Numeros Random import random print(random.randrange(1, 10)) print('\n') #ciclos for x in "banana": print(x) a = "Hello, World!" print('\n') print(len(a)) #Busca la palabra en el txt txt = "The best things in life are free!" print("free" in txt) #Condicional if if "free" in txt: print("Yes, 'free' is present.") txt = "Hello, World!" print(txt[2:5]) print(txt[:5]) print(txt[2:]) print(txt[-5:-2]) #Upper Case print(txt.upper()) #Lowe Case print(txt.lower()) #Remove WhiteSpace #remueve los espacios al principio y al final del texto print(txt.strip()) #Replace String print(txt.replace("H", "J")) #Split String """ Separa los Strings segun el dato por el que quiera que se separe """ print(txt.split(",")) edad = 20 txt = "Mí nombre es Juan Pablo, y tengo {}" print(txt.format(edad)) #Caracteres de Escape txt = "Nosotros somos los llamados \"Vikings\" del norte" print(txt) """ \\ Barra invertida \n Nueva Linea \r Acarrea la oración \t Tabulación \b Quita el espacio entre texto \f Alinea un formulario """ """ capitalize() convierte el primer caracter en mayuscula casefold() convierte la cadena en minuscula completamente center() retorna el centro de toda la cadena count("frase") retorna el número el número de veces un valor especificado en una cadena endcode() retorna el final de la cadena codificada endswith("") retorna verdadero si termina con el símbolo especificado expandtabs(2) Da saltos horizontales en la cadena find("frase") busca en el string la frase especificada y retorna la posición donde esta format(frase) da formato a un string format_map() index() busca una cadena un valor especificada y retorna la posición donde se encontró isalnum() retorna verdadero si todos los caracteres del string son alphanumericos isalpha() retorna verdadero si todos los caracteres del string son digítos isdecimal() retorna verdadero si los caracteres del string son decimales isdigit() retorna verdadero si todos los caracteres del string son números isidentifier() retorna verdadero si todos los caracteres del string ha excepción del primero sean diferente a una letra islower() retorna verdadero si todos los caracteres estan en minuscula isnumeric() retorna verdadero si todos los caracteres son númericos isprintable() retorna verdadero si no esta en saltado en una nueva linea isspace() retorna verdadero si la cadena tiene espaciados istitle() retorna verdadero si la cadena tiene las teglas para ser un titulo isupper() retorna verdadero si la cadena esta completamente en mayuscula join() une los elementos de una iteración al final de la cadena ljust() retorna la cadena justificada al lado izquierdo lower() convierte la cadena completamente en minuscula lstrip() retorna una versión recortada a la izquierda de la cadena maketrans("letra-vieja", "letra-nueva") retorna la cadena con la letra reemplazada partition() retorna una tupla donde el string esta partido en dos partes replace() retorna una cadena donde toma un valor especificado y otro por el cual será reemplazado rfind() encuentra las cadenas para especificar un valor y retornarlo en la ultima posición rindex() busca la cadena para especificar el valor y retornar la ultima posición donde fue encontrada rjust() retorna la cadena justificado hacia la derecha rpartition() retorna una tupla donde la cadena donde la cadena es partida dentro de 3 partes rsplit() separa las cadenas especificando el separador y retorna una lista rstrip() devuelve una version recortada a la derecha por la cadena split() separa la cadena especificando el separador y retorna una lista splitlines() separa la cadena con lineas y retornandola en una lista startswith() retorna verdadero si la cadena inicia con el valor especificado strip() retorna una version recortada del string swapcase() intercambia casos, los casos mínusculos los convierte a mayuscula y vice versa title() comvierte el primer caracter de cada palabra a mayuscula translate() retorna una cadena transladada upper() convierte la cadena en mayuscula zfill() rellena la cadena con un número especificado de valores 0 al principio """ """ Listas en Python """ """ Las listas aceptan valores repetidos """ """ append() Agrega elementos al final de la lista clear() Remueve todos los elementos de la lista copy() Retorna una copia de la lista count() Retorna el número de elementos con el valor especificado extends() Agrega los elementos de una lista, a el final de la lista pasada como parametro index() Retorna el index de el primer elemento con el valor especificado insert() Agrega los elementos a una posición especificada pop() Remueve los elementos de una posición especificada remove() Remueve los items con el valor especificado reverse() Invierte el orden de la lista sort() Clasifica la lista """ lista = ["manzana", "banana", "fresa", "naranja", "kiwi", "melon"] print(len(lista)) """Tambien aceptan todo tipo de valores en una misma lista """ lista1 = ["abc", 34, True, 40, "male"] print(lista1) print(type(lista)) print(lista[1]) print(lista[2:5]) print(lista[:4]) print(lista[2:]) lista[1:2] = ["blackcurrant", "watermelon"] print(lista) lista.insert(2, "piña") print(lista) lista.append("Lulo") print(lista) lista.extend(lista) print(lista) t = ("maracuya", "mango") lista.extend(t) print(lista) lista.remove("naranja") print(lista) lista.pop() print(lista) del lista[0] print(lista) lista.clear() print(lista) for x in lista: print(x) for i in range(len(lista)): print(lista[i]) [print(x) for x in lista] frutas = ["apple", "banana", "cherry", "kiwi", "mango"] #nuevaLista = [x for x in frutas if "a" in x] #nuevaLista2 = [x for x in frutas if x != "apple"] thislist = ["Banana", "Orange", "Kiwi", "Cherry"] thislist.reverse() print(thislist) frutas.sort() print(frutas) frutas.sort(reverse = True) print(frutas) frutas.copy() print(frutas) lista01 = ["a", "b", "c"] lista02 = [1, 2, 3] lista01.extend(lista02) print(lista01) """ Tuplas en Python """ thisTuple = ("Manzana", "Banana", "Fresa", "Mango") print(thisTuple) tupla1 = ("Manzana", "Banana", "Fresa") tupla2 = (1, 3 , 4, 5, 6, 8) tupla3 = (True, False, False) tupla = ("abc", 34, True, 40, "male") fruits = ("apple", "banana", "cherry") (green, yellow, red) = fruits print(green) print(yellow) print(red) print(fruits) for i in range(len(fruits)): print(fruits[i]) for x in fruits: print(x) print(fruits * 2) """ Set en Python """ myset = {"Manzana", "Banana", "Fresa"} print(myset) print(len(myset)) set1 = {"Apple", "Banana", "Cherry"} set2 = {1, 3, 4, 6, 8} set3 = {True, False, False} setexample = {"abc", 34, True, 40, "male"} for x in setexample: print(x) print("Banana" in myset) myset.add("Orange") print(myset) thisset = {"Manzana", "Banana", "Fresa"} tropical = {"Piña", "Mango", "Papaya"} thisset.remove("Fresa") print(thisset) thisset.discard("Banana") print(thisset) thisset.update(tropical) print(thisset) thisset.clear() print(thisset) set4 = set1.union(set2) print(set4) x = {"Apple", "Banana", "Fresa"} y = {"Google", "Microsoft","Apple"} x.symmetric_difference_update(y) print(x) x.intersection_update(y) print(x) z = x.intersection(y) print(z) """ Dictionario en Python """ thisdict = { "Marca": "Ford", "Modelo": "Mustang", "Year": 1964 }
# prime.py from math import sqrt def is_prime(x): if x < 2: return False for i in range(2, int(sqrt(x))+1): if x % i == 0: return False return True def nth_prime(n): count = -1 num = 0 while True: if is_prime(num): count += 1 if count == n: return num num += 1
# Control Structures # Exercises # 1. Conditional Basics # a. prompt the user for a day of the week, print out whether the day is Monday or not print('Please enter a day of the week: ') day = input() if day.lower() == 'monday': print(f'Your day is {day}!') else: print('Not Monday.') # b. prompt the user for a day of the week, print out whether the day is a weekday or a weekend print('Please enter a day of the week: ') day = input() if day.lower() in ('monday', 'tuesday', 'wednesday', 'thursday', 'friday'): print('Your day is a weekday.') elif day.lower() in ('saturday', 'sunday'): print('Your day is a weekend day!') else: print('That is not a day at all!') # c. create variables and make up values for # - the number of hours worked in one week hours_worked = 35 # - the hourly rate hourly_rate = 400 # - how much the week's paycheck will be this_weeks_pay = hours_worked * hourly_rate # write the python code that calculates the weekly paycheck. You get paid time # and a half if you work more than 40 hours if hours_worked <= 40: this_weeks_pay = hours_worked * hourly_rate else: this_weeks_pay = (hourly_rate * 40) + (hourly_rate * 1.5 * (hours_worked - 40)) print(this_weeks_pay) # 2. Loop Basics # a. While # - Create an integer variable i with a value of 5. i = 5 # - Create a while loop that runs so long as i is less than or equal to 15 while i <= 15 # - Each loop iteration, output the current value of i, then increment i by one. while i <= 15: print(i) i += 1 # - Create a while loop that will count by 2's starting with 0 and ending at 100. # Follow each number with a new line. i = 0 while i <= 98: print(i, '\n') i = i + 2 # - Alter your loop to count backwards by 5's from 100 to -10. i = 100 while i >= -10: print(i, '\n') i = i -5 # - Create a while loop that starts at 2, and displays the number # squared on each line while the number is less than 1,000,000. i = 2 while i < 1000000: print(i) i **= 2 # - Write a loop that uses print to create the output shown below. i = 100 while i >= 5: print(i) i -= 5 # b. For Loops # i. Write some code that prompts the user for a number, then shows # a multiplication table up through 10 for that number. print('Please input a number: ') number = int(input()) for n in range(1, 11): print(number, 'X', n, '=', number * n) # ii. Create a for loop that uses print to create the output shown below. for i in range (1, 10): print(str(i) * i) # c. break and continue # i. Prompt the user for an odd number between 1 and 50. Use a loop and # a break statement to continue prompting the user if they enter invalid input. # (Hint: use the isdigit method on strings to determine this). Use a loop and # the continue statement to output all the odd numbers between 1 and 50, except # for the number the user entered. while True: number = input('Please input an odd integer between 1 and 50: ') if number.isdigit(): number = int(number) if (number > 1 and number < 50) and number % 2 == 1: print(f'Number to skip is: {number}') break for n in range(1, 50): if n == number: print(f'Yikes! Skipping number: {number}') if n % 2 == 1 and n != number: print(f'Here is an odd number: {n}') continue # d. The input function can be used to prompt for input and use that input in # your python code. Prompt the user to enter a positive number and write a loop # that counts from 0 to that number. (Hints: first make sure that the value the # user entered is a valid number, also note that the input function returns a # string, so you'll need to convert this to a numeric type.) while True: number = input('Please input a positive number: ') if number.isdigit(): number = int(number) if number > 0: break for n in range(number + 1): print(n) # e. Write a program that prompts the user for a positive integer. Next write a # loop that prints out the numbers from the number the user entered down to 1. while True: number = input('Please input a positive integer: ') if number.isdigit(): number = int(number) if number > 0: break while number > 0: print(number) number -= 1 # 3. Fizzbuzz # One of the most common interview questions for entry-level programmers is # the FizzBuzz test. Developed by Imran Ghory, the test is designed to test # basic looping and conditional logic skills. # - Write a program that prints the numbers from 1 to 100. # - For multiples of three print "Fizz" instead of the number # - For the multiples of five print "Buzz". # - For numbers which are multiples of both three and five print "FizzBuzz". for n in range(1, 101): if n % 5 == 0 and n % 3 == 0: print('FizzBuzz') elif n % 5 == 0: print('Buzz') elif n % 3 == 0: print('Fizz') else: print(n) # 4. Display a table of powers. # - Prompt the user to enter an integer. # - Display a table of squares and cubes from 1 to the value entered. # - Ask if the user wants to continue. # - Assume that the user will enter valid data. # - Only continue if the user agrees to. while True: number = input('What number would you like to go up to? ') if number.isdigit(): number = int(number) if number > 0: break print('This program will create a table of powers for your number.') proceed = input('Would you like to continue? ') if proceed.lower().startswith('y'): print() print('Here is your table!') print('number | squared | cubed') print('------ | ------- | -----') for n in range(1, number + 1): n_squared = n ** 2 n_cubed = n ** 3 print(f'{n: 6} | {n_squared: 7} | {n_cubed: 5}') # 5. Convert given number grades into letter grades. # - Prompt the user for a numerical grade from 0 to 100. # - Display the corresponding letter grade. # - Prompt the user to continue. # - Assume that the user will enter valid integers for the grades. # - The application should only continue if the user agrees to. # - Grade Ranges: # -- A : 100 - 88 # -- B : 87 - 80 # -- C : 79 - 67 # -- D : 66 - 60 # -- F : 59 - 0 # --- Bonus # --- Edit your grade ranges to include pluses and minuses (ex: 99-100 = A+). while True: number = input('Please enter a numerical grade from 0 to 100: ') if number.isdigit(): number = int(number) if number >= 0 and number <= 100: break if number >= 88: print('Your grade is an A!') elif number in range(80, 88): print('Your grade is a B.') elif number in range(67, 80): print('Your grade is a C.') elif number in range(60, 67): print('Your grade is a D.') else: print('Your grade is an F.') # 6. Create a list of dictionaries where each dictionary represents a book that # you have read. Each dictionary in the list should have the keys title, author, # and genre. Loop through the list and print out information about each book. bookshelf = [ {'title': 'Game of Thrones', 'author': 'George R. R. Martin', 'genre': 'Fantasy'}, {'title': 'The Anatomy of Evil', 'author': 'Michael H. Stone MD', 'genre': 'True Crime'}, {'title': 'Tales from Margaritaville', 'author': 'Jimmy Buffett', 'genre': 'Humour'}, ] for book in bookshelf: for key in book: print(key, ': ', book[key]) print('-----------------------------------') # -a. Prompt the user to enter a genre, then loop through your books list and # print out the titles of all the books in that genre. while True: print('Please choose a genre.') choice = input('Enter either Fantasy, True Crime or Humour: ') if choice.lower() in ('fantasy', 'true crime', 'humour'): break for book in bookshelf: if choice.lower() == book['genre'].lower(): for key in book: print(key, ': ', book[key]) print('-----------------------------------')
def encrypt1(plaintext: str, k: int) -> str: """ Basic implementation of caesar cipher """ cipher = '' for p in plaintext: z = chr(((ord(p) - ord('a') + k) % 26) + ord('a')) cipher += z return cipher def encrypt2(plaintext: str, k: int, alphabet: str = "abcdefghijklmnopqrstuvwxyz") -> str: """ on the hindsight - this is a poor man's substitution cipher! :param plaintext: non-encrypted plaintext :param k: shift in caesar cipher :param alphabet: alphabet string for the shift (this allows to change/expand the base text) :return: encrypted ciphertext """ cipher = '' for p in plaintext: index_p = alphabet.find(p) if index_p != -1: cipher += alphabet[(index_p + k) % len(alphabet)] else: raise ValueError('non-alphabet found in plaintext') return cipher
import sqlite3 with sqlite3.connect('db.sqlite3') as connection: cursor = connection.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)') cursor.execute('INSERT OR IGNORE INTO users VALUES (1, "alice", "1234")') cursor.execute('INSERT OR IGNORE INTO users VALUES (2, "bob", "5678")') def authenticate_with_vulnerability(username, password): with sqlite3.connect('db.sqlite3') as connection: cursor = connection.cursor() cursor.execute("SELECT * FROM users WHERE username = '{}' AND password = '{}'".format(username, password)) resp = cursor.fetchall() print(resp) return len(resp) > 0 def authenticate_secure(username, password): with sqlite3.connect('db.sqlite3') as connection: cursor = connection.cursor() cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password)) resp = cursor.fetchall() print(resp) return len(resp) > 0 def hack(): username, password = sql_injection() print(authenticate_with_vulnerability(username, password)) print(authenticate_secure(username, password)) def sql_injection(): return "' OR 1=1 --", '' hack()
a = 2 if a == 1: print("a == 1") elif a == 2: print("a == 2") else: print("other")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 15 00:51:00 2018 @author: jia_qu """ import requests def exchange(base,other): #base="USD" #other="GBP" resp=requests.get("https://api.exchangeratesapi.io/latest?",params={"base":base,"symbols":other}) #resp=requests.get("https://data.fixer.io/api/latest?base=USD&symbols=EUR") if resp.status_code!=200: raise Exception("Error") data=resp.json() rate=data['rates'][other] print("1 {} is equal to {} {}".format(base,rate,other)) if __name__=="__main__": exchange()
class QElement: def __init__(self, value, priority): self.value = value self.priority = priority def __str__(self): return 'Value: %d, Prioirty: %d' % (self.value, self.priority) class PriorityQueue: def __init__(self): self.data = [] def enqueue(self, value, priority): qElement = QElement(value, priority) for idx, element in enumerate(self.data): if element.priority > priority: self.data.insert(idx, qElement) return self.data.append(qElement) def dequeue(self): if self.isEmpty(): return self.data = self.data[1:] def front(self): if self.isEmpty(): return return self.data[0] def rear(self): if self.isEmpty(): return return self.data[-1] def isEmpty(self): return len(self.data) == 0 def print(self): for element in self.data: print(element) pQueue = PriorityQueue() pQueue.print() pQueue.enqueue(123, 2) pQueue.enqueue(3, 3) pQueue.enqueue(34, 2) pQueue.enqueue(14, 1) pQueue.enqueue(5, 5) pQueue.enqueue(734, 8) pQueue.print() print('----') pQueue.dequeue() pQueue.print() print('----') print(pQueue.front()) print(pQueue.rear())
class Node: def __init__(self, value): self.left = None self.right = None self.value = value def __str__(self): return 'Node value: %d, Left node: %s, Right node: %s' % (self.value, self.left.value if self.left != None else 'None', self.right.value if self.right != None else 'None') def isLeaf(self): return self.left == None and self.right == None class BinarySearchTree: def __init__(self): self.root = None def print(self): currentNodes = [self.root] level = 1 nodes = {} nodes[level] = [n for n in currentNodes] while len(currentNodes) > 0: level += 1 nodes[level] = [] nextNodes = [] for node in currentNodes: if node.left != None: nodes.get(level).append(node.left) if node.right != None: nodes.get(level).append(node.right) nextNodes += [node.left, node.right] currentNodes = [n for n in nextNodes if n != None] if len(nodes.get(level)) == 0: del nodes[level] for k, v in nodes.items(): print('level %d' % k) for n in v: print(n) def insert(self, value): if self.root == None: self.root = Node(value) else: newNode = Node(value) parentNode = self.root while True: if parentNode.value > value: if parentNode.left == None: parentNode.left = newNode break else: parentNode = parentNode.left elif parentNode.value < value: if parentNode.right == None: parentNode.right = newNode break else: parentNode = parentNode.right else: print('Existed value') return def lookup(self, value): if self.root == None: return None currentNode = self.root while currentNode != None: if currentNode.value == value: return currentNode if currentNode.value > value: currentNode = currentNode.left else: currentNode = currentNode.right return None def remove(self, value): assert self.root != None parentNode = None directionFlag = '' currentNode = self.root while currentNode != None: if currentNode.value > value: directionFlag = 'left' parentNode = currentNode currentNode = currentNode.left elif currentNode.value < value: directionFlag = 'right' parentNode = currentNode currentNode = currentNode.right else: if currentNode.isLeaf(): if directionFlag == 'left': parentNode.left = None elif directionFlag == 'right': parentNode.right = None elif currentNode.left == None: if directionFlag == 'left': parentNode.left = currentNode.right elif directionFlag == 'right': parentNode.right = currentNode.right elif currentNode.right == None: if directionFlag == 'left': parentNode.left = currentNode.left elif directionFlag == 'right': parentNode.right = currentNode.left else: replaceNode = currentNode.right while replaceNode.left != None: if replaceNode.left.left == None: tempNode = replaceNode.left replaceNode.left = tempNode.right replaceNode = tempNode else: replaceNode = replaceNode.left replaceNode.left = currentNode.left replaceNode.right = currentNode.right if directionFlag == 'left': parentNode.left = replaceNode elif directionFlag == 'right': parentNode.right = replaceNode else: self.root = replaceNode break def breadthFirstSearch(self): currentNode = self.root nodeList = [] nodeQueue = [] nodeQueue.append(currentNode) while len(nodeQueue) > 0: currentNode = nodeQueue[0] nodeQueue = nodeQueue[1:] nodeList.append(currentNode.value) if currentNode.left != None: nodeQueue.append(currentNode.left) if currentNode.right != None: nodeQueue.append(currentNode.right) return nodeList def BFS(self): return self.breadthFirstSearchRecursive([], [self.root]) def breadthFirstSearchRecursive(self, nodeList, queue): if len(queue) == 0: return nodeList currentNode = queue[0] queue = queue[1:] nodeList.append(currentNode.value) if currentNode.left != None: queue.append(currentNode.left) if currentNode.right != None: queue.append(currentNode.right) return self.breadthFirstSearchRecursive(nodeList, queue) def DFS(self, orderType): if orderType == 'InOrder': return self.depthFirstSearchInOrder(self.root, []) elif orderType == 'PreOrder': return self.depthFirstSearchPreOrder(self.root, []) elif orderType == 'PostOrder': return self.depthFirstSearchPostOrder(self.root, []) def depthFirstSearchInOrder(self, currentNode, nodeList): if currentNode.left != None: nodeList = self.depthFirstSearchInOrder(currentNode.left, nodeList) nodeList.append(currentNode.value) if currentNode.right != None: nodeList = self.depthFirstSearchInOrder(currentNode.right, nodeList) return nodeList def depthFirstSearchPreOrder(self, currentNode, nodeList): nodeList.append(currentNode.value) if currentNode.left != None: nodeList = self.depthFirstSearchPreOrder(currentNode.left, nodeList) if currentNode.right != None: nodeList = self.depthFirstSearchPreOrder(currentNode.right, nodeList) return nodeList def depthFirstSearchPostOrder(self, currentNode, nodeList): if currentNode.left != None: nodeList = self.depthFirstSearchPostOrder(currentNode.left, nodeList) if currentNode.right != None: nodeList = self.depthFirstSearchPostOrder(currentNode.right, nodeList) nodeList.append(currentNode.value) return nodeList tree = BinarySearchTree() tree.insert(9) tree.insert(4) tree.insert(6) tree.insert(20) tree.insert(170) tree.insert(15) tree.insert(1) # 9 # 4 20 #1 6 15 170 print('Breadth First Search') print(tree.breadthFirstSearch()) print(tree.BFS()) print() print('Depth First Search') print('''InOrder [1, 4, 6, 9, 15, 20, 170] InOrder return the sorted list PreOrder [9, 4, 1, 6, 20, 15, 170] PreOrder list is useful recreation of tree PostOrder [1, 6, 4, 15, 170, 20, 9] ''') print(tree.DFS('InOrder')) print(tree.DFS('PreOrder')) print(tree.DFS('PostOrder'))
class HashTable: def __init__(self, size): self.data = [None] * size self.size = size self.keyList = [] def _hash(self, key): hash = 0 for i in range(len(key)): hash = (hash + ord(key[i]) * i) % self.size return hash def set(self, key, value): index = self._hash(key) if self.data[index] == None: self.data[index] = [] self.data[index].append((key, value)) self.keyList.append(key) def get(self, key): index = self._hash(key) if self.data[index] != None: for k, value in self.data[index]: if k == key: return value else: return None def keys(self): # keys = [] # for data in self.data: # if data != None and len(data) > 0: # for key, _ in data: # keys.append(key) # return keys return self.keyList myHashTable = HashTable(50) print(myHashTable._hash('grapes')) myHashTable.set('grapes', 10000) print(myHashTable.get('grapes')) myHashTable.set('AI', 99999) print(myHashTable.get('grapes')) print(myHashTable.get('AI')) print(myHashTable.get('apples')) print(myHashTable.keys())
# Problem # Given a array and a integer, whether there is a pair in the array that their sum is the same to given integer or not. # Sample # [1,2,4,9], 8 - False # [1,2,4,4], 8 - True # [6,4,3,2,1,7], 9 - True # Brute-force solution def isPairWithSum1(arr, target): for i in range(len(arr)-1): for j in range(i+1, len(arr)): if arr[i] + arr[j] == target: return True return False # Time Complexity: O(n^2) # Space Complexity: O(1) print('--- Brute-Force ---') print(isPairWithSum1([1,2,4,9], 8)) print(isPairWithSum1([1,2,4,4], 8)) print(isPairWithSum1([6,4,3,2,1,7], 9)) def isPairWithSum2(arr, target): i = 0 j = len(arr)-1 while i < j: subsum = arr[i] + arr[j] if subsum == target: return True elif subsum > target: j -= 1 elif subsum < target: i += 1 return False # Time Complexity: O(n) # Space Complexity: O(1) # However, this function only works under the condition that the given array is sorted print('--- Solution 2 ---') print(isPairWithSum2([1,2,4,9], 8)) print(isPairWithSum2([1,2,4,4], 8)) print(isPairWithSum2([6,4,3,2,1,7], 9)) def isPairWithSum3(arr, target): needNums = {} for num in arr: if needNums.get(num): return True else: needNums[target-num] = True return False # Time Complexity: O(n) # Space Complexity: O(n) print('--- Solution 3 ---') print(isPairWithSum3([1,2,4,9], 8)) print(isPairWithSum3([1,2,4,4], 8)) print(isPairWithSum3([6,4,3,2,1,7], 9)) print('-------------------')
#!/usr/bin/python3 from string import punctuation import os def text_analyzer(s="", *argv): """\nThis function counts the number of upper characters, \ lower characters, punctuation and spaces in a given text.""" if len(argv) > 0: print("ERROR") quit() print("SSS ", s) if s == "": s = input("What is the text to analyse?\n>>") print("The text contains %d characters:\n" % (sum(1 for c in s))) print("%d upper letters\n" % (sum(1 for c in s if c.isupper()))) print("%d lower letters\n" % (sum(1 for c in s if c.islower()))) print("%d punctuation marks\n" % (sum(1 for c in s if c in punctuation))) print("%d spaces\n" % (sum(1 for c in s if c.isspace())))
#!/usr/bin/python3 import sys cookbook = { "sandwich": { "ingredients": ["ham", "bread", "cheese", "tomatoes"], "type": "lunch", "prep_time": 10, }, "cake": { "ingredients": ["flour", "sugar", "eggs"], "type": "dessert", "prep_time": 60, }, "salad": { "ingredients": ["avocado", "arugula", "tomatoes", "spinach"], "type": "lunch", "prep_time": 15, } } def print_list(): print("\nPlease select an option by typing the corresponding number:") print("1: Add a recipe") print("2: Delete a recipe") print("3: Print a recipe") print("4: Print the cookbook") print("5: Quit") def print_recipe(): print("Please enter the recipe's name to get its details:") st = input(">> ") if st in cookbook: print("Recipe for cake:") print("Ingredients list: %s" % (cookbook[st]['ingredients'])) print("To be eaten for %s." % (cookbook[st]['type'])) print("Takes %s minutes of cooking." % (cookbook[st]['prep_time'])) else: print("%s is not in cookbook" % (st)) handle_input() def add_recipe(): s = [] s1 = input("Enter recipe name: >> ") s2 = input("Enter ingredients list: >> ") s = s2.split() s3 = input("Enter recipe type: >> ") s4 = input("Enter prep time: >> ") try: s5 = int(s4) except ValueError: print("Not a number.") print_list() handle_input() cookbook.update({s1: { 'ingredients': s, "type": s3, "prep_time": s4, } }) print("%s added to cookbook." % (s1)) print_list() handle_input() def delete_recipe(): s1 = input("Enter recipe name to delete: >> ") if s1 in cookbook: cookbook.pop(s1, None) print("%s deleted." % (s1)) print_list() handle_input() else: print("%s is not in cookbook" % (s1)) print_list() handle_input() def print_all_recipes(): for st in cookbook: print(" ---> ", st) print_list() handle_input() def handle_input(): s = input(">> ") try: if (int(s) < 0 and int(s) > 5): print_error() except ValueError: print_error() if int(s) == 5: print("\nCookbook closed.") exit() if int(s) == 1: add_recipe() if int(s) == 2: delete_recipe() if int(s) == 3: print_recipe() if int(s) == 4: print_all_recipes() def print_error(): print("\nOption does not exists, please type the corresponding number.") print("To exit, enter 5") handle_input() if __name__ == "__main__": print_list() handle_input()
#!/usr/bin/python3 import numpy as np def cost_elem_(y, y_hat): if len(y) != len(y_hat): return None J_elem = (1 / (2 * len(y))) * (y_hat - y)**2 return np.asarray(J_elem) def cost_(y, y_hat): if len(y) != len(y_hat): return None J_value = 0.0 J_elem = cost_elem_(y, y_hat) for i in J_elem: J_value += i #J_value = np.square(np.subtract(y, y_hat)).mean() return J_value if __name__ == "__main__": X = np.array([0, 15, -9, 7, 12, 3, -21]) Y = np.array([2, 14, -13, 5, 12, 4, -19]) print(cost_(X, Y))
import numpy as np import os import math from decimal import Decimal from fractions import Fraction import time print(len(str(0.45))) def factorising(a,b,c): ### Todo Add support for coefficients roots = solvefact(a,b,c) print("(x + {0})(x + {1}) | Currently only works with coeffficient of 1".format(roots[0] * -1 , roots[1] * -1 )) def expandbracket(a,b,c,d): #(ax + b)(cx + d) #(ax * cx) + (ax * d) + (b * cx) + (b * d) print("({}x + {})({}x + {}) is {}x^2 + {}x + {}".format(a,b,c,d,a*c, (a*d)+(b*c), b*d)) def solvefact(a,b,c): #ax^2+bx+c roots = [0,0] x = -30 """ -b +- sqrt ( b ^2 - 4ac 2a """ start = time.time() try: roots[0], roots[1] = ((-b) + math.sqrt(pow(b,2) - (4*a*c))) / (2*a) , ((-b) - math.sqrt(pow(b,2) - (4*a*c))) / (2*a) print(roots) except ValueError: print("{0}x^2 + {1}x + {2} has no roots.".format(a,b,c)) print("{0:0.10f} seconds".format(time.time() - start )) #Looping Table Method Works """start = time.time() roots = [] while len(roots) < 2: #y = (a*pow(x,2))+(b*x)+(c) x += 0.1 y = 0 y += a*float((round(x,10)**2)) y += b*float(round(x,10)) y += c #print("{0} | {1}".format(round(x,10),y)) if y == 0: roots.append(round(x,10)) if len(roots) == 2: break print(roots) print("{0:0.10f} seconds".format(time.time() - start ))""" print("Roots: {} {}".format(roots[0],roots[1])) return roots a = float(input("a: ")) b = float(input("b: ")) c = float(input("c: ")) #d = float(input("d: ")) factorising(a,b,c)
# This calculates the number of days and years needed to save a certain amount of money. # Savings = int(input("input savings wanted")) Balance = [1] Cents = (Savings * 100) Day = 0 while (Balance[Day] < Cents): Balance.append(Balance[Day] + Day) Day = Day + 1 print ("The number of days needed to save is", Day) print ("The number of years needed to save is" , (Day/365)) print ("The final balance is", (Balance[Day]/100)) print ("The contribution on the final day is", (Day/100))
""" 9. Write a Python program to add a border (filled with 0's) around an existing array. Expected Output: Original array: [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] 1 on the border and 0 inside in the array [[ 0. 0. 0. 0. 0.] [ 0. 1. 1. 1. 0.] [ 0. 1. 1. 1. 0.] [ 0. 1. 1. 1. 0.] [ 0. 0. 0. 0. 0.]] """ import numpy as np array = np.ones([3,3]) print(array) array = np.pad(array, pad_width = 1, mode = 'constant', constant_values = 0) print(array)
""" 18. Write a Python program to change the name 'James' to 'Suresh' in name column of the DataFrame. exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] """ import pandas as pd import numpy as np exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] SNo = ['001', '002', '003', '004', '005', '006', '007', '008', '009', '010'] df = pd.DataFrame(data = exam_data, index = labels, columns = exam_data) print(df) print(" ") print("--------------------------------------------------") print(" ") df.name = df.name.replace(to_replace = "James", value = "Suresh") print(df)
import math import statistics from functools import reduce area = lambda radius: math.pi * (radius ** 2) # from Celius to F c_to_f = lambda data: (data[0], (9/5)*data[1]+32) radii = [2, 5, 7.1, 0.5, 10] output_areas = list(map(area, radii)) print(radii) print(output_areas) temps = [("Berlin", 29), ("Cairo", 36), ("Buenos Aires", 19), ("Los Angeles", 29, ("Tokyo", 27))] output_temps = list(map(c_to_f, temps)) print(temps) print(output_temps) #filter the logic False values data = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1] print("====original data: {}".format(data)) avg = statistics.mean(data) print("====the mean: {0}".format(avg)) filtered_list = list(filter(lambda x: x<avg, data)) print("====the filter output: {}".format(filtered_list)) # filter the None value countries = ["", "China", "Japan", "Thailand", "Korea", "", "USA", "Canada"] print("====Original list: {}".format(countries)) filtered_countries = list(filter(None, countries)) # Note 0 is considered None too print("====Filtered countries: {}".format(filtered_countries)) # reduce function # given data: [a1, a2, a3, ... an] and function: f(x,y) # reduce(f, data): # step 1: val1 = f(a1, a2) # step 2: val2 = f(val1, a3) # step 3: val3 = f(val2, a4) # ... # step n-1: valn-1 = f(valn-2, an) # return valn-1 # or: f(f(f(a1,a2),a3),a4),...an) data=[2,3,7,11,13,17,19,23,29] multiplier = lambda x,y: x*y reduce_output = reduce(multiplier,data) print("====output of reduce: {}".format(reduce_output)) try: with open("Gundam1.txt") as f: text = f.read() print(text) except FileNotFoundError: text = None print("====File NOT Found") countries = ["China", "Japan", "Thailand", "Korea", "USA", "Canada", "Mexico"] try: with open("country.txt",'w') as f: for country in countries: f.write(country) f.write("\n") except FileNotFoundError: pass with open("country.txt",'w') as f: for country in countries: print(country, file=f) with open("country.txt", 'a') as f: print(20*"=", file=f) print("There are {} countries.".format(len(countries)), file=f)
def pythagorean_triplet_checker(triplet_array): arr_len = len(triplet_array) for i in range(arr_len): triplet_array[i] = triplet_array[i] ** 2 triplet_array.sort() for val in range(arr_len-1, 1, -1): j = 0 k = val - 1 while (j < k): if (triplet_array[j] + triplet_array[k] == triplet_array[val]): return True else: if (triplet_array[j] + triplet_array[k] < triplet_array[val]): j += 1 else: k -= 1 return False if __name__ == "__main__": print(pythagorean_triplet_checker([3, 4, 5]))
from functools import reduce def add_subtract(x): def add_subtract_recursive(x, add_subtract_func): def curried_add_subtract(y): return add_subtract_func(x, y) return curried_add_subtract def add_subtract_func(x, y): def add_subtract_iterate(acc, item): if acc % 2 == 0: return acc + item else: return acc - item return reduce(add_subtract_iterate, (x, y), 0) return add_subtract_recursive(x, add_subtract_func) if __name__ == '__main__': result = add_subtract(7) print(result) print(add_subtract(1)(2)(3)) print(add_subtract(-5)(10)(3)(9))
def find_bridges(graph, num_vertices): # Initialize a list to store the bridges bridges = [] # Initialize a counter to assign discovery times to the vertices disc_time = [0] * (num_vertices + 1) # Initialize an array to store the lowest discovery time reachable from a given vertex low = [0] * (num_vertices + 1) # Initialize a parent array to store the parent of each vertex in the DFS tree parent = [-1] * (num_vertices + 1) # Initialize a counter to keep track of the time during the DFS time = 0 # Perform a DFS traversal of the graph for i in range(1, num_vertices + 1): if not disc_time[i]: # Start a new DFS tree rooted at vertex i time = dfs_util(graph, i, disc_time, low, parent, bridges, time) return bridges def dfs_util(graph, u, disc_time, low, parent, bridges, time): # Return immediately if the vertex is not connected to the root of the DFS tree if not parent[u]: return time # Mark the discovery time of the current vertex disc_time[u] = low[u] = time + 1 # Explore each adjacent vertex of the current vertex for v in graph[u]: # If the vertex has not been visited yet, # explore it and update the low time of the current vertex if not disc_time[v]: parent[v] = u time = dfs_util(graph, v, disc_time, low, parent, bridges, time) # Update the low time of the current vertex low[u] = min(low[u], low[v]) # If the low time of the adjacent vertex is greater than the discovery time of the current vertex, # then the edge (u, v) is a bridge if low[v] > disc_time[u]: bridges.append((u, v)) elif v != parent[u]: # If the vertex has been visited before and it is not the parent of the current vertex, # update the low time of the current vertex low[u] = min(low[u], disc_time[v]) return time # Construct an undirected graph as an adjacency list graph = { 1: [2], 2: [1, 3], 3: [2, 4], 4: [3, 5], 5: [4, 6], 6: [5] } if __name__ == '__main__': bridges = find_bridges(graph, 6) print(bridges)
def is_toeplitz(matrix): # Iterate through each element of the matrix, starting from the second row and second column for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): # Check if the current element is equal to the element above and to the left of it if matrix[i][j] != matrix[i-1][j-1]: return False return True matrix = [[1, 2, 3, 4, 8], [5, 1, 2, 3, 4], [4, 5, 1, 2, 3], [7, 4, 5, 1, 2]] if __name__ == '__main__': print(is_toeplitz(matrix)) # True