text
stringlengths
37
1.41M
til = input('Tilni tanlang: uz/en ? ') if til == 'uz': print('Assalomu alaykum') elif til == 'en': print('Hello') else: print('uz/en lardan birini tanlang')
a = int(input("son kirg'izing:")) b = int(input("son kiriting:")) if(a > b): print("togri") else: print("notogri")
fon = {} fon['a'] = 123 fon['b'] = 456 print(fon) print(fon.items()) print(fon.keys()) print(fon.values()) for k,v in fon.items(): print(k,fon[k],v)
L = ["a", "b", "c", "d", "e"] def opgave3(L): print(L[1: -3]) #opgave3(L)
from tkinter import * from random import randint import time class Plotter(): def __init__(self): self.running = True self.messageCounter = 1 self.minValue = 0 self.maxValue = 100 self.s = 1 self.x2 = 50 self.y2 = self.value_to_y(randint(0, 100)) self.root = Tk() self.root.title('simple plot') self.canvas = Canvas(self.root, width=1420, height=600, bg='white') # 0,0 is top left corner self.canvas.pack(expand=YES, fill=BOTH) #buttons self.quitButton = Button(self.root, text='Quit', command=self.root.quit).pack() self.pauseButton = Button(self.root, text='Pause/Continue', command=self.pause).pack() self.subMitValues = Button(self.root, text='submitValue', command=self.getMinAndMaxValues).pack() #labels self.xLable = Label(self.root, text='x- as') #x-as lable self.xLable.place(x= 55, y=560) self.xLable = Label(self.root, text='x- as')# y-as lable self.xLable.place(x=15, y=460) self.minLable = Label(self.root, text= 'min value').place(x=945, y=603) self.maxLable = Label(self.root, text='max value').place(x=945, y=630) #tekstfields self.minValueEntry = Entry(self.root) self.minValueEntry.place(x=1000, y=603) self.maxValueEntry = Entry(self.root) self.maxValueEntry.place(x=1000, y=630) self.messageLog = Text(self.root) self.messageLog.place(x=1100, y=603) #lines self.canvas.create_line(50, 550, 1150, 550, width=2) # x-axis self.canvas.create_line(50, 550, 50, 50, width=2) # y-axis for i in range(23): x = 50 + (i * 50) self.canvas.create_line(x, 550, x, 50, width=1, dash=(2, 5)) self.canvas.create_text(x, 550, text='%d' % (10 * i), anchor=N) # y-axis for i in range(11): y = 550 - (i * 50) self.canvas.create_line(50, y, 1150, y, width=1, dash=(2, 5)) self.canvas.create_text(40, y, text='%d' % (10 * i), anchor=E) def value_to_y(self, val): return 550 - 5 * val def step(self): if self.running: if self.s == 23: self.s = 1 self.x2 = 50 self.canvas.delete("temp") x1 = self.x2 y1 = self.y2 self.x2 = 50 + self.s*50 self.y2 = self.value_to_y(randint(self.minValue, self.maxValue)) self.canvas.create_line(x1, y1, self.x2, self.y2, fill='blue', tags='temp') self.canvas.after(300, self.step) self.s += 1 def pause(self): if self.running == True: self.running = False else: self.running = True self.step() print(self.running) def getMinAndMaxValues(self): if self.minValueEntry.get() == '' or self.maxValueEntry.get() == '': self.messageLog.insert(INSERT, str(self.messageCounter) + ' :enter values in both fields \n') self.messageCounter +=1 else: minValue = int(self.minValueEntry.get()) maxValue = int(self.maxValueEntry.get()) # self.canvas.create_line(50, 550, 1150, 550, width=2) # x-axis # self.canvas.create_line(50, 550, 50, 50, width=2) # y-axis #minValueLine = self.canvas.create_line(50, 550, minValue, 550) if minValue > maxValue: self.messageLog.insert(INSERT, str(self.messageCounter) + ' :minValue has to be smaller than max \n') self.messageCounter += 1 else: self.minValue = minValue self.maxValue = maxValue #self.canvas.place(minValueLine) def main(self): self.canvas.after(300, self.step) self.root.mainloop() p = Plotter() p.main()
from math import isclose class PerfectNumberChecker(): perfectNumberList = [] def fillPerfectNumberList(self): candidateNumber = 1 while candidateNumber < 10000: self.perfectNumberCheck(candidateNumber) candidateNumber += 1 def printPerfectNumberList(self): print(self.perfectNumberList) def perfectNumberCheck(self, checkNumber): numberList = [] i = 1 while i < checkNumber: result = checkNumber / i if self.isWhole(result): numberList.append(i) if(sum(numberList) > checkNumber): break i += 1 if(sum(numberList) == checkNumber): self.perfectNumberList.append(checkNumber) print("perfectNumber Found") def isWhole(self, number): if (number % 1 == 0): return True else: return False p = PerfectNumberChecker() #p.perfectNumberCheck(28) p.fillPerfectNumberList() p.printPerfectNumberList()
# If Statements # Use boolean logic to set is_hot and is_cold variables to True or False. is_hot = False is_cold = False # Use an if statement to determine if the variable "is_hot" is equal to True and if so print "It's a hot day", "Drink plenty of water" and "Enjoy your day". if is_hot: print("It's a hot day") print("Drink plenty of water") # Use an elif statement to determine if the variable "is_cold" is equal to True and if so print "It's a cold day", "Wear warm clothes" and "Enjoy your day". elif is_cold: print("It's a cold day") print("Wear warm clothes") # Use an else statement so that if neither of the above conditions are true print "It's a lovely day" and "Enjoy your day". else: print("It's a lovely day") print("Enjoy your day")
__author__ = 'yna1' import math #Dictionaries #have keys instead of indexes dictEx = ({"Age":35,"height":"6'3","Weight":165}) #DICTIONARIES ARE Immutable print dictEx print dictEx.get("Age") print dictEx.items() #Prints the keys and the values print dictEx.values() #prints just the values dictEx.pop("height") #removes the key and value in the parameter, which takes a key strName ='Bob' floatAge = 35.3 charSex ='M' intKids = 2 boolMarried = True print 'My name is',strName print '%s is %.1f years old' %(strName,floatAge) print 'Sex: %c' %(charSex) print 'He had %d kids and said it\'s %s he is married' % (intKids,boolMarried) print '%.15f'%(math.pi) print '%20f' %(math.pi) print '%20.15f' %(math.pi) print '%-25.15f' %(math.pi) #precisionPi = int(raw_input("How precise should pu be: ")) #print 'Pi = %.*f' %(precisionPi,math.pi) bigString = 'Her is a loing string that i will be messing with' print bigString[1:20:2] print bigString.find('string') print bigString.count("e") print bigString.count("e",4,20) copyStr = tuple(bigString) print copyStr copy2 = ''.join(copyStr) # ''.joid(tuple) turns the tuple into a string print copy2 copy2 = ','.join(copyStr) print copy2 print bigString.replace("loing","short") print bigString.split(' ') #splits up the string into a list with each element separated by a ' ' space randomWhite = ' Random White Space ' print randomWhite.strip() #this is equivalent to java trim method
# Copyright 2012 Dorival de Moraes Pedroso. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. from numpy import ones from numpy.random import seed, random, randint, shuffle def Seed(val): """ Seed initialises random numbers generator """ seed(val) def IntRand(low, high=None, size=None): """ IntRand generates random integers """ return randint(low, high, size) def FltRand(n, xa=0.0, xb=1.0): """ FltRand generates n numbers between xa and xb """ res = random(n) * (xb - xa) + xa if len(res) == 1: return res[0] return res def FlipCoin(p): """ Flip generates a Bernoulli variable; throw a coin with probability p """ if p==1.0: return True if p==0.0: return False if random()<=p: return True return False def Shuffle(x): """ Shuffle modifies an array by shuffling its contents """ shuffle(x) if __name__ == "__main__": from numpy import array a = array([1,2,3,4,5], dtype=int) print 'before: a =', a Shuffle(a) print 'after: a =', a
#!/usr/bin/python3 str = input("请输入:") print("你输入的内容是: " + str) # name = 'oopxiajun'; # print(name);
while True: number = input('Number: ') try: if int(number) > 0: break except ValueError: pass mc = [str(i) for i in range(1,6)] digits = [n for n in number][::-1] result = str(sum([int(item) for item in ''.join([str((2 * int(n))) for n in digits[1::2]])]) + sum([int(n) for n in digits[0::2]]))[-1] if (number[0:2] == '34' or number[0:2] == '37') and len(number) == 15 and result == '0': print('AMEX') elif number[0] == '5' and number[1] in mc and len(number) == 16 and result == '0': print('MASTERCARD') elif number[0] == '4' and (len(number) == 13 or len(number) == 16) and result == '0': print('VISA') else: print('INVALID')
def diamond(): row = 1 n = 1 while row <= 5: column = 1 #printing the spaces before the stars in every row while column <= abs(3 - row): print("\b "), column += 1 #printing the stars in every row column = 1 while column <= 2 * n - 1: print("\b*"), column += 1 print("\r") if row < 3: #no. of stars increase till 3rd row n += 1 elif row >= 3: #no. of stars decrease from 4th row onwards n = n - 1 row += 1
from Q2input import * # Your code - begin output = {} #Appending the key,value pair to the output dictionary for i in Dic1.keys(): if Dic1[i] not in Dic2.keys(): output[i] = Dic1[i] for j in Dic2.keys(): if Dic2[j] not in Dic1.keys(): output[j] = Dic2[j] #Adding the 2 values with same key and then appending it to output dictionary for k in Dic1.keys(): if k in Dic2.keys(): output[k] = Dic1[k] + Dic2[k] # Your code - end print output
#defining a function to print a given message a given number of times def print_n_messages(m, n): i = 0 while i < n: print(m) i += 1
def factorial(n): ## Your code - begin if n > 0: #base case to exit recursion return(n * factorial(n - 1)) else: return 1 ## Your code - end if __name__ == "__main__": n = input("Enter number: ") output = factorial(n) print output
def even_elements(l): ## Your code - begin l1 = [i for i in l if i % 2 == 0] return l1 ## Your code - end if __name__ == "__main__": l = range(10) print "input = ", l print even_elements(l)
#finds if binary tree is balanced class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class BalancedSolution: def isBalanced(self, root): if root is None: return True return self.getHeight(root) != -1 def getHeight(self, node): if node is None: return 0 lnode = self.getHeight(node.left) rnode = self.getHeight(node.right) if (lnode == -1) or (rnode == -1) or (abs(lnode - rnode) > 1): return -1 return max(lnode, rnode) + 1 #Finds minimum depth of a tree class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class MinDepthSolution: def minDepth(self, root: TreeNode) -> int: if root is None: return 0 if root.left is None and root.right is None: return 1 if root.left is None: return self.minDepth(root.right) + 1 if root.right is None: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 #Finds a path of a tree when adding all the nodes equals the target value class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def hasPathSum(self, root: TreeNode, sum: int) -> bool: if not root: return False elif (not root.left) and (not root.right) and (sum - root.val == 0): return True return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
#counts the lenght of the last word class LenLastWordSolution: #one Way def lengthOfLastWord(self, s): counter = 0 for l in range(len(s) - 1, -1, -1): if s[l] != " ": counter += 1 elif counter > 0: break return counter #second way '''def lengthOfLastWord(self, s): strippedStr = s.strip() listOfWords = strippedStr.split(" ") return len(listOfWords[-1])''' q1 = LenLastWordSolution() print(q1.lengthOfLastWord("James is a beast")) print(q1.lengthOfLastWord("jjjjjaaaa mmmm ")) #Plus One class PlusOneSolution: def plusOne(self, digits): for i in range(len(digits) - 1, 0, -1): digits[i] += 1 if digits[i] != 10: return digits digits[i] = 0 return [1] + digits q2 = PlusOneSolution() print(q2.plusOne([2,4,5,9])) #compute squareroot of a number class SqrtSolution: #Binary SOlution def mySqrt(self, x): r = x l = 0 while l <= r: mid = (l + r) // 2 if (mid * mid) > x: r = mid - 1 elif (mid * mid) < x: l = mid + 1 else: return mid return r #simple solution '''def mySqrt(self, x): return int(x**0.5)''' q3 = SqrtSolution() print(q3.mySqrt(15)) #max subarray class maxSubArraySolution: def maxSubArray(self, nums): maxNum = [0] * len(nums) maxNum[0] = nums[0] for i in range(1, len(nums)): maxNum[i] = max(maxNum[i - 1] + nums[i], nums[i]) print(maxNum[i]) return max(maxNum) q4 = maxSubArraySolution() print(q4.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
set1 = {2, 1, 3} set2 = {1, 2, 3} print(set1.intersection(set2)) print(set1 - set2) print(set2.issubset(set1)) print(set1 != set2)
num = int(input('Digite um numero :')) res = num %2 if res == 0: print('O numero {} que você digitou e par'.format(num)) else: print('O numero {} que digitou e impar'.format(num))
pi = float(input('Qual o valor do produto?')) d = (5/100)* pi pf = pi - d print('O produto custa {:.2f}R$ com desconto de 5% o valor será de {:.2f}R$'.format(pi, pf))
al = float(input('Qual altura da parede:')) la = float(input('Qual a largura da parede :')) area = al * la li = area / 2 print('A parede tem area de {:.2f}m² vai ser utilizado {}l de tinta '.format(area, li))
cont = ('ziro', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen','fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen','twenty') while True: num = int(input('Digite um numero entre 0 e 20 : ')) if 0 <= num <=20: break print('Tente novamanente. ',end='') print(f'Você digitou o Número {cont[num]}')
# 作者 ljc # 将图像的绿色值变为0 import cv2 as cv import numpy as np img = cv.imread('out.jpg') print(img.shape) print(img.size) print(img.dtype) # shape 包含 宽度,高度 和通道数 # size 图像像素的大小 # Datatype 图像的数据类型 如uint8 # cv.imwrite('111.jpg', img)
# Capture information name = input('Please tell me your name: ') age = input('Please tell me your age: ') reddit_username = input('Please tell me your Reddit Username: ') # Print the information in requested format print('Your name is ' + name + ', You are ' + age + ' years old, \ and your username is ' + reddit_username) # Extra Credit: Save information to file for use later user_info = (name, age, reddit_username) save_user_info = str(user_info) file = open('userinfo.txt', 'w') file.write(save_user_info)
#!/usr/bin/env python # coding: utf-8 # In[1]: # Step 1: Write a function that can print out a board. Set up your board as a list, # where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation. # This function is to display a board of up to 9 inputs. This board will display a manaully printed spaces and lines, # while adding the input spots (board[#]) and the spaces between each input # In[2]: from IPython.display import clear_output def display_board(board): # 1) create a function that will input a list # 2) define the list input in the function (board) # 3) create a board display manually that will make it asthetically pleasing to see each board input index print(" " + board[1] + ' | ' + board[2] + ' | ' + board [3] + " 1" + ' | ' + "2" + ' | ' + '3') print("--------------- ------------------") print(" " + board[4] + ' | ' + board[5] + ' | ' + board [6] + " 4" + ' | ' + "5" + ' | ' + '6') print("--------------- -------------------") print(" " + board[7] + ' | ' + board[8] + ' | ' + board [9] + " 7" + ' | ' + "8" + ' | ' + '9') # In[3]: #TEST Step 1: run your function on a test version of the board list, and make adjustments as necessary # In[4]: test_board = ['#','X','O','X','O','X','O','X','O','X'] display_board(test_board) # 1) create a list of items to test the board display, the list will run through the display_board function # 2) the inputs will take a indexed spot according to the display_function(board) function. # 3) The test_board must contain a list of 10 objects since our board is indexing for 1-9, and index starts at 0 # In[5]: #Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. # Think about using while loops to continually ask until you get a correct answer. # In[6]: # Now that we have a function that displays a board and can take in inputs, #we need to make a function that allows a player to choose a marker def player_input(): # Define a string to be defined for the X and O markers. marker = '' # create a loop that will wait on a person to enter either X or O as a choice. # The input by a person has to accept lower case letters and turn it into an upper case. while not (marker == "X" or marker == "O"): #The marker input must only be ONE equal sign (=) since it is a input variable that will be entered by a customer. # input variables will display a string to communicate to person what is being asked. # if the input by a person does not equal to any of the markers, the while loop will ensure it keeps # asking the person until a valid input is entered marker = input("Player 1, choose X or O as your marker: ").upper() # once a marker is entered that breaks the loop, meaning a person chose X or x or O or o, then it will return if marker == "X": return ("X", "O") else: return ("O" , "X") # In[7]: #TEST Step 2: run the function to make sure it returns the desired output # In[ ]: # In[8]: # Step 3: Write a function that takes in the board list object, # a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board. # In[9]: # the function will go to the board list in the display_board function, #it will index at a position, then equate a marker input to the positon def place_marker(board, marker, position): board[position] = marker # In[10]: #TEST Step 3: run the place marker function using test parameters and display the modified board # In[11]: #This test will take the test_board list, and place a $ sign in position 8 place_marker(test_board,'$',8) display_board(test_board) # In[12]: # Step 4: Write a function that takes in a board and checks to see if someone has won. # In[13]: # the function will take a board, and a see if a specific mark equals to each in each position, # according to how you win. # The function can just use the return function will default to say true or false if any criteria matches to the parameters # it has to be a an OR between each, to ensure that only one scenerio occurs during a move. # the "mark" parameter is new since, a marker will check if X or O wins, # which is different than the input marker of a person def win_check(board,mark): return ((board[1] == mark and board[2] == mark and board[3] == mark) or (board[4] == mark and board[5] == mark and board[6] == mark) or (board[7] == mark and board[8] == mark and board[9] == mark) or (board[1] == mark and board[4] == mark and board[7] == mark) or (board[2] == mark and board[5] == mark and board[8] == mark) or (board[3] == mark and board[6] == mark and board[9] == mark) or (board[1] == mark and board[5] == mark and board[9] == mark) or (board[3] == mark and board[5] == mark and board[7] == mark)) # In[14]: #win_check(test_board,'X') # In[15]: #This function is checking if the win_check(test_board,'X') # In[16]: #Step 5: Write a function that uses the random module to randomly decide which player goes first. #You may want to lookup random.randint() Return a string of which player went first. # In[17]: import random def choose_first(): if random.randint(0, 1) == 0: return "Player 2" else: return "Player 1" # In[18]: #Step 6: Write a function that returns a boolean #indicating whether a space on the board is freely available. # In[19]: def space_check(board, position): return board[position] == ' ' # In[20]: #Step 7: Write a function that checks if the board is full and returns a boolean value. #True if full, False otherwise. # In[21]: def full_board_check(board): for i in range(1,10): if space_check(board, i): return False return True # In[22]: #Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if its a free position. #If it is, then return the position for later use. # In[23]: def player_choice(board): position = 0 while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position): position = int(input('Choose your next position (1-9): ' )) return position # In[24]: #Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again. # In[25]: def replay(): return input("Do you want to play again? Enter Yes or No: ").lower().startswith('y') # In[26]: #Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game! # In[ ]: print('Welcome to Tic Tac Toe!') while True: theBoard = [' '] * 10 player1_marker, player2_marker = player_input() turn = choose_first() print(turn + ' will go first!') play_game = input('Are you ready to play? Enter Yes or No.') if play_game.lower()[0] == "y": game_on = True else: game_on = False while game_on: if turn == 'Player 1': display_board(theBoard) position = player_choice(theBoard) place_marker(theBoard, player1_marker, position) if win_check(theBoard, player1_marker): display_board(theBoard) print('Player 1 has WON!') game_on = False else: if full_board_check(theBoard): display_board(theBoard) print('The game is a draw!') break else: print(" ") print(" PLAYER 2's TURN", "(", player2_marker, ")") turn = 'Player 2' else: # Player2's turn. display_board(theBoard) position = player_choice(theBoard) place_marker(theBoard, player2_marker, position) if win_check(theBoard, player2_marker): display_board(theBoard) print('Player 2 has WON!') game_on = False else: if full_board_check(theBoard): display_board(theBoard) print('The game is a draw!') break else: print(" ") print(" PLAYER 1's TURN", "(", player1_marker, ")") turn = 'Player 1' if not replay(): break # In[ ]: # In[ ]:
from typing import List, Optional from brackettree import parser class Node: name: str children: List["Node"] def __init__(self, name: str) -> None: self.name = name self.children = [] def find(self, name: str) -> Optional["Node"]: if self.name == name: return self for c in self.children: r = c.find(name) if r is not None: return r return None def bracket_representation(self) -> str: # avoiding string concatenation since strings are immutable object - # thus creating list of string and joining on return s = [self.name] s.extend(["({})".format(c.bracket_representation()) for c in self.children]) return "".join(s) def count_leaves(self) -> int: if len(self.children) == 0: return 1 return sum(c.count_leaves() for c in self.children) def add_child(self, bracket_tree: str) -> None: self.children.append(parser.parse(bracket_tree))
# Assume s is a string of lower case characters. # Write a program that counts up the number of vowels contained in # the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. # For example, if s = 'azcbobobegghakl', your program should print: # Number of vowels: 5 # For problems such as these, do not include raw_input statements or # define the variable s in any way. Our automated testing wil s = 'azcbobobegghakl' vowels = ("a", "e", "i", "o", "u") numVowels = 0 for oneChar in s: if oneChar in vowels: numVowels += 1 print("Number of vowels: " + str(numVowels))
import pandas as pd from pandas import Series, DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns st_df = pd.read_csv("StudentsPerformance.csv") print("________data header__________") st_df.head() print("________discription_________") st_df.info() st_df.describe() print("removing lunch and test preparation course") st_df1 = st_df.drop(['lunch','test preparation course'],axis=1) st_df1.head() print("filling the empty values in parental level of education") st_df1["parental level of education"] = st_df["parental level of education"].fillna("highSchool") print(st_df1["parental level of education"]) ax = sns.countplot(x="test preparation course", hue="gender", palette="Set1", data=st_df) ax.set(title="test prepration", xlabel="course", ylabel="total") plt.show()
from functools import reduce l1 = [1, 2, 3, 4, 5] newlist = [x*3 for x in l1] sum1 = reduce(lambda a,b:a+b, l1) sum2 = reduce(lambda a,b:a+b, newlist) print(sum1) print(sum2)
from functools import partial, wraps basetwo = partial(int, base=2) basetwo.__doc__ = "test" print basetwo('0010') print int('0010', base=2) print('-'*30) def my_decorator(f): @wraps(f) def wrapper(*args, **kwargs): print('calling decorated func') f(*args, **kwargs) return return wrapper @my_decorator def example(): """ This is an example func() """ print 'called example func()' example() print example.__name__ print example.__doc__
# -*- coding:utf8 -*- # 练习for循环 # Created by fanghuabao on 2017/9/25. for i in range(10): print('loop ', i) for a in ['a', 'b', 'c']: print(a)
#Número par/impar #Número positivo/negativo x= input('Ingrese un número: ') if not x.isalpha(): x=int(x) if x%2==0: if x>=0: print(f'El número {x} es par y positivo') else: print(f'El número {x} es par y negativo') else: if x>=0: print(f'El número {x} es impar y positivo') else: print(f'El número {x} es impar y negativo') else: print('Dato incorrecto')
def comma(lv): for i in range(0, len(lv) - 1): print(str(lv[i]), end = ', ') else: print('and' + ' ' + str(lv[-1])) return
# A dumb program to learn and mess around with command line while True: try: x = int(input('give me an int: ')) except ValueError: print ('Dont be an idiot') continue else: break if x < 4: print ('less than 4') elif x == 4: print ("egual 2 4") else: print ('thats a big number') print("your number is {}" .format(x)) print("Count to {} with me!" .format(x)) for num in range(x + 1): print(num) print("Weee, that was fun!") print("Now lets count backwards!") for num1 in reversed(range(x + 1)): print(num1) print("haha, I can't believe that worked")
import pandas as pd import numpy as np # 1. read data df = pd.read_csv("ChurnData.csv") df['churn'] = df['churn'].astype('int') # 2. Determine x, y with right columns X = df[['tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip']] .values #.astype(float) y = df['churn'].values # 3. Standardlize X from sklearn import preprocessing X = preprocessing.StandardScaler().fit(X).transform(X) # 4. Split data into training and test 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=4) # 5. Create Model and training from sklearn.linear_model import LogisticRegression LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train) yhat = LR.predict(X_test) # 6. Evaluate results: from sklearn.metrics import jaccard_similarity_score print(jaccard_similarity_score(y_test, yhat))
# Any sequence or iterable can be unpacked into variables using a simple assigement. # The only requirement is that the number of variables and structure match the sequence. print('unpacking a tuple:') p = (4, 5) x, y = p print(x) print(y) print('unpacking a List:') data = ['ACME', 50, 91.1, (2012, 12, 21)] name, shares, price, date = data print(name) print(date) # ignore certain values name, shares, price, (year, month, _) = data print(year) print(month)
''' You want to return multiple values from a function. ''' # Solution: Simply return a tuple. # A tuple is actually created. def myfun(): return 1, 2, 3
import random def gameplay(): number = random.randint(0,100) NString=str(number) print(number) guess='' tippek=[] while guess!=NString: # for x in tippek: print(tippek) guess=input('Tipped: ') if guess!=NString: if int(guess)<number: print('Tul alacsony') tippek.append(u"\u2193"+guess) else: print('Tul magas') tippek.append(u"\u2191"+guess) else: x=len(tippek) z=str(x) print('Kitalaltad '+z+' probalkozasbol') play=input('Uj jatek?\nigen/nem\n') if play=='igen': gameplay() play=input('szeretnel jatszani?\n igen/nem\n') if play=='igen' : print("Jatszol") gameplay() else : print('Nem jatszol')
from typing import Tuple from logic import * ASSUMPTIONS_HEADER = 'ASSUMPTIONS' GUARANTEES_HEADER = 'GUARANTEES' INS_HEADER = 'INPUTS' OUTS_HEADER = 'OUTPUTS' END_HEADER = 'END' COMMENT_CHAR = '#' FILE_HEADER_INDENT = 0 DATA_INDENT = 1 TAB_WIDTH = 2 def parse(file_path: str) -> Tuple[str, str, str, str]: """Returns: assumptions, guarantees, inputs, outputs""" assumptions = [] guarantees = [] inputs = [] outputs = [] file_header = "" with open(file_path, 'r') as ifile: for line in ifile: line, ntabs = _count_line(line) # skip empty lines if not line: continue # parse file header line elif ntabs == FILE_HEADER_INDENT: if ASSUMPTIONS_HEADER in line: if file_header == "": file_header = line else: Exception("File format not supported") elif GUARANTEES_HEADER in line: if file_header == ASSUMPTIONS_HEADER: file_header = line else: Exception("File format not supported") elif INS_HEADER in line: if file_header == GUARANTEES_HEADER: file_header = line else: Exception("File format not supported") elif OUTS_HEADER in line: if file_header == INS_HEADER: file_header = line else: Exception("File format not supported") elif END_HEADER in line: if file_header == OUTS_HEADER: return And(assumptions), And(guarantees), Comma(inputs), Comma(outputs) else: Exception("File format not supported") else: raise Exception("Unexpected File Header: " + line) else: if ASSUMPTIONS_HEADER in file_header: if ntabs == DATA_INDENT: assumptions.append(line.strip()) if GUARANTEES_HEADER in file_header: if ntabs == DATA_INDENT: guarantees.append(line.strip()) if INS_HEADER in file_header: if ntabs == DATA_INDENT: inputs.append(line.strip()) if OUTS_HEADER in file_header: if ntabs == DATA_INDENT: outputs.append(line.strip()) def _count_line(line): """Returns a comment-free, tab-replaced line with no whitespace and the number of tabs""" line = line.split(COMMENT_CHAR, 1)[0] # remove comments tab_count = 0 space_count = 0 for char in line: if char == ' ': space_count += 1 elif char == '\t': tab_count += 1 else: break tab_count += int(space_count / 4) line = line.replace('\t', ' ' * TAB_WIDTH) # replace tabs with spaces return line.strip(), tab_count
import csv import os.path def create_csv(csv_out, headers): if csv_out[-4:] != '.csv': raise ValueError('Expecting a csv_out argument ending with ".csv"') if os.path.isfile(csv_out): print(csv_out + ' already exists. File will not be overwritten') return if type(headers) is not list: raise ValueError('Expecting a list of headers as the headers argument') f = open(csv_out, 'x', newline='') # x to create file: error if it already exists writer = csv.writer(f) writer.writerow(headers) f.close() def read_api_credentials(txt_file): """User is required to save a txt file with two lines: the first being their applicationID and the second being their application key""" credentials = {} with open(txt_file) as f: credentials['app_id'] = f.readline().rstrip() credentials['app_key'] = f.readline().rstrip() return credentials def append_to_csv(csvfile, row_items): with open(csvfile, 'a', newline='') as f: writer = csv.writer(f) writer.writerow(row_items)
x = 5 y = 6 z = 5 if z < y > x: print('y is greater than z va y is greater than x') if x == z: print('x is equal z') if y != x: print('y is not equal x') # if elif else if x > y : print('x is greater than y') elif x==y: print('x is equal y') else: print('x is less than y')
int_var = 5 str_var = 'string variables' bool_var = True print(int_var) print(str_var) print(bool_var) # gan gia tri cho nhieu bien x,y = (5,10) # or x,y = 5,10 print(x) print(y)
import numpy as np print(np.array([True, 1, 2])) print(np.array([3, 4, False])) # array in np chi chua duy nhat 1 kieu du lieu # Arue se bi convert ve 1 # False se bi convert ve 0 print(np.array([True, 1, 2]) + np.array([3, 4, False])) # Select element in array same in list a = np.array([2, 4, 5, 2, 1, 9]) print(a[3]) print(a[:4])
""" 1. Bygg ett program som låter användaren mata in ett reg.nr och skriv ut de två grupperna var för sig; använd slicing-syntax för att dela upp inputsträngen. Ex. Ange regnr: ABC663 Bokstävsgrupp: ABC Siffergrupp: 663 """ reg_nr = input("Skriv reg nr:") print(f"Regnr: {reg_nr}\nBokstävsgrupp:{reg_nr[0:3]}\nSiffergrupp:{reg_nr[3:7]} ") """ 2. Bygg ett program där användaren matar in ett gäng heltal med komma emellan, och skriver ut följande: Ange tal med komma emellan: 1,2,3,5,100 Första talet: 1 Sista talet: 100 Summan av talen: 111 Talen baklänges: 100, 5, 3, 2, 1 """ num = [] tal = input("Ange tal med komma emellan: 1,2,3,5,100: ").split(",") back = ', '.join(list(reversed(tal))) for i in tal: num.append(int(i)) print(f"Första talet:{tal[0]}\nSista talet:{tal[-1]}\nSumman av talen:{sum(num)}\nTalen baklänges: {back}")
""" ------------------------------------------------------------------------------- Name: main.py Purpose: Multiple choice review quiz of course content Author: Wang.J Created: 01/14/2021 ------------------------------------------------------------------------------- """ # title print("*** Multiple Choice Computer Studies Review Quiz ***") # name name = input("Enter your first and last name: ") # confirmation to start quiz with instruction question = input(name + ", Type 'READY' to start the quiz: ") confirmation = "READY" while question != confirmation: question = input("Type 'READY' when you are ready: ") if question == confirmation: print("Read each question carefully and answer each with one of the following lowercase letters. Good Luck! ") # variables answers_correct = 0 answers_incorrect = 0 # get answers for the questions and output correct or incorrect through if statements. # question one q_one = input("\n 1. What is the computer processing sequence of events in order? \n a) Input, process, output, storage. \n b) Storage, input, process, output. \n c) Process, output, input, storage. \n Enter Answer: ") while q_one != "a" and q_one != "b" and q_one != "c": q_one = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_one == ("a"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question two q_two = input("\n 2. How many bits are in 1 byte? \n a) 8 bits. \n b) 7 bits. \n c) 10 bits. \n Enter Answer: ") while q_two != "a" and q_two != "b" and q_two != "c": q_two = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_two == ("a"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question three q_three = input("\n 3. How many bytes are in 1 Kilobyte (KB)? \n a) 800 bytes. \n b) 1024 bytes. \n c) 2000 bytes. \n Enter Answer: ") while q_three != "a" and q_three != "b" and q_three != "c": q_three = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_three == ("b"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'b'. ") answers_incorrect += 1 # question four q_four = input("\n 4. How many bits are in 1 megabit? \n a) 10 bits. \n b) 1 million bits. \n c) 1000 bits. \n Enter Answer: ") while q_four != "a" and q_four != "b" and q_four != "c": q_four = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_four == ("b"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'b'.") answers_incorrect += 1 # question five q_five = input("\n 5. DPI (Dots per Inch) and PPI (Pixels Per Inch) measures how many points of information can be captured in a _____? \n a) centimeter. \n b) meter. \n c) inch. \n Enter Answer: ") while q_five != "a" and q_five != "b" and q_five != "c": q_five = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_five == ("c"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'c'.") answers_incorrect += 1 # question six q_six = input("\n 6. What does CPU stand for? \n a) Circle process unit. \n b) Central processing unit. \n c) Central professional units. \n Enter Answer: ") while q_six != "a" and q_six != "b" and q_six != "c": q_six = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_six == ("b"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'b'.") answers_incorrect += 1 # question seven q_seven = input("\n 7. What is the purpose of the motherboard? \n a) It serves a connection between the various different parts of a computer system. \n b) It stores data. \n c) It gives power to the computer. \n Enter Answer: ") while q_seven != "a" and q_seven != "b" and q_seven != "c": q_seven = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_seven == ("a"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question eight q_eight = input("\n 8. What does RAM stand for? \n a) Random access memory. \n b) Real accessible memory. \n c) Random application memory. \n Enter Answer: ") while q_eight != "a" and q_eight != "b" and q_eight != "c": q_eight = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_eight == ("a"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question nine q_nine = input("\n 9. Megahertz(MHz) & Gigahertz(GHz) measure what type of speed? \n a) Downloading speed. \n b) Updating speed. \n c) Processing speed. \n Enter Answer: ") while q_nine != "a" and q_nine != "b" and q_nine != "c": q_nine = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_nine == ("c"): print("Correct!") answers_correct += 1 else: print("Incorrect. The correct answer was 'c'.") answers_incorrect += 1 # question ten q_ten = input("\n 10. What is the primary function of random access memory (RAM)? \n a) It provides a temporary storage space for programs that are not actively being used. \n b) It provides a permanent storage space for the computer. \n c) It provides a temporary storage space for programs that are in the act of using. \n Enter Answer: ") while q_ten != "a" and q_ten != "b" and q_ten != "c": q_ten = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_ten == ("c"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'c'.") answers_incorrect += 1 # question eleven q_eleven = input("\n 11. What is the primary function of hard drives? \n a) Storing data. \n b) Updating files. \n c) Providing power. \n Enter Answer: ") while q_eleven != "a" and q_eleven != "b" and q_eleven != "c": q_eleven = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_eleven == ("a"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question twelve q_twelve = input("\n 12. What is the CPU performance measured in? \n a) Megahertz(MHz). \n b) Gigahertz(GHz). \n c) Hertz(H). \n Enter Answer: ") while q_twelve != "a" and q_twelve != "b" and q_twelve != "c": q_twelve = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_twelve == ("b"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'b'.") answers_incorrect += 1 # question thirteen q_thirteen = input("\n 13. How many processors are on a dual core processor? \n a) Three. \n b) Two. \n c) Four. \n Enter Answer: ") while q_thirteen != "a" and q_thirteen != "b" and q_thirteen != "c": q_thirteen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_thirteen == ("b"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'b'.") answers_incorrect += 1 # question fourteen q_fourteen = input("\n 14. What is the primary unit of storage? \n a) Gb/Tb. \n b) MHz/GHz. \n c) MM/CM. \n Enter Answer: ") while q_fourteen != "a" and q_fourteen != "b" and q_fourteen != "c": q_fourteen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_fourteen == ("a"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question fifteen q_fifteen = input("\n 15. What does DRAM stand for? \n a) Dynamic random access memory. \n b) Data random access memory. \n c) Dynamic random application memory. \n Enter Answer: ") while q_fifteen != "a" and q_fifteen != "b" and q_fifteen != "c": q_fifteen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_fifteen == ("a"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question sixteen q_sixteen = input("\n 16. What is a url? \n a) A complex phone number. \n b) Phone book. \n c) Web address you type into a browser to reach a website. \n Enter Answer: ") while q_sixteen != "a" and q_sixteen != "b" and q_sixteen != "c": q_sixteen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_sixteen == ("c"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'c'.") answers_incorrect += 1 # question seventeen q_seventeen = input("\n 17. What is an IP address? \n a) A series of numbers that tells your computer where to find the information you're looking for. \n b) A web address you type into a browser to reach a website. \n c) Phone book. \n Enter Answer: ") while q_seventeen != "a" and q_seventeen != "b" and q_seventeen != "c": q_seventeen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_seventeen == ("a"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question eighteen q_eighteen = input("\n 18. What is the least dangerous malware? \n a) Adware. \n b) Trojan. \n c) Spyware. \n Enter Answer: ") while q_eighteen != "a" and q_eighteen != "b" and q_eighteen != "c": q_eighteen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_eighteen == ("a"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'a'.") answers_incorrect += 1 # question nineteen q_nineteen = input("\n 19. What is the most dangerous malware? \n a) Rootkit. \n b) Ransomware. \n c) Trojan. \n Enter Answer: ") while q_nineteen != "a" and q_nineteen != "b" and q_nineteen != "c": q_sixteen = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_nineteen == ("c"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'c'.") answers_incorrect += 1 # question twenty q_twenty = input("\n 20. What does GPU stand for? \n a) Graphics Profesional Universe. \n b) General Professional Unit. \n c) Graphics Processing Unit. \n Enter Answer: ") while q_twenty != "a" and q_twenty != "b" and q_twenty != "c": q_twenty = input("Invalid Answer. Choose one of the following letters shown! Try Again.\n Enter Answer: ") if q_twenty == ("c"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'c'.") answers_incorrect += 1 # true and false questions print("\n >>> Part 2 True or False Questions <<< \nPick 'True' if you think the statement is correct and 'False' if you think the statement is wrong.") # question twenty one q_twenty_one = input("\n 21. External storage allows users to store data separately from a computer’s main storage. \n True \n False \n Enter Answer: ") while q_twenty_one != "True" and q_twenty_one != "False": q_twenty_one = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_one == ("True"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'True'.") answers_incorrect += 1 # question twenty two q_twenty_two = input("\n 22. A pointing device is an input interface that allows a user to input spatial data to a computer. \n True \n False \n Enter Answer: ") while q_twenty_two != "True" and q_twenty_two != "False": q_twenty_two = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_two == ("True"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'True'.") answers_incorrect += 1 # question twenty three q_twenty_three = input("\n 23. The display monitor is an input device that displays the image taken from the storage device. \n True \n False \n Enter Answer: ") while q_twenty_three != "True" and q_twenty_three != "False": q_twenty_three = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_three == ("False"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'False'.") answers_incorrect += 1 # question twenty four q_twenty_four = input("\n 24. Speakers/Headphones output sounds from devices. \n True \n False \n Enter Answer: ") while q_twenty_four != "True" and q_twenty_four != "False": q_twenty_four = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_four == ("True"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'True'.") answers_incorrect += 1 # question twenty five q_twenty_five = input("\n 25. The keyboard is an output device that sends commands to the display monitor. \n True \n False \n Enter Answer: ") while q_twenty_five != "True" and q_twenty_five != "False": q_twenty_five = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_five == ("False"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'False'.") answers_incorrect += 1 # question twenty six q_twenty_six = input("\n 26. SSD is typically less expensive and slower than HDD. \n True \n False \n Enter Answer: ") while q_twenty_six != "True" and q_twenty_six != "False": q_twenty_six = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_six == ("False"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'False'.") answers_incorrect += 1 # question twenty seven q_twenty_seven = input("\n 27. Hz measures the refresh rate of the monitor. \n True \n False \n Enter Answer: ") while q_twenty_seven != "True" and q_twenty_seven != "False": q_twenty_seven = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_seven == ("True"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'True'.") answers_incorrect += 1 # question twenty eight q_twenty_eight = input("\n 28. Sound is measured in decibels. \n True \n False \n Enter Answer: ") while q_twenty_eight != "True" and q_twenty_eight != "False": q_twenty_eight = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_eight == ("True"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'True'.") answers_incorrect += 1 # question twenty nine q_twenty_nine = input("\n 29. GB measures how fast the monitor screen can switch between colours in milliseconds. \n True \n False \n Enter Answer: ") while q_twenty_nine != "True" and q_twenty_nine != "False": q_twenty_nine = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_twenty_nine == ("False"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'False'.") answers_incorrect += 1 # question thirty q_thirty = input("\n 30. The Auxiliary port allows the connection of the audio from one device to another. Ex. Headphones, speakers, microphones. \n True \n False \n Enter Answer: ") while q_thirty != "True" and q_thirty != "False": q_thirty = input("Invalid Answer. Choose one of the following shown! Try Again.\n Enter Answer: ") if q_thirty == ("True"): print("Correct.") answers_correct += 1 else: print("Incorrect. The correct answer was 'True'.") answers_incorrect += 1 # output the final score total_questions = 30 print("\n >>>> Final Score <<<<") print (name) print("Your final score is " + str(answers_correct) + "/" + str(total_questions) + ".") # calculate the average average = round((answers_correct/total_questions) * 100) print("Your average percentage is " + str(average) + "%.") # feedback if average >= 85: print("Excellent Work! You had " + str(answers_incorrect) + " incorrect answers out of " + str(total_questions) + ".") elif average >= 70 and average <= 84: print("Good Job! You had" + str(answers_incorrect) + " incorrect answers out of " + str(total_questions) + ".") else: print("Study harder next time, you had " + str(answers_incorrect) + " incorrect answers out of " + str(total_questions) + ".") # end print("Thank you for taking the online multiple choice computer studies review quiz. Have a good day!")
""" RSA functions """ """ Encrypt message m (decimal representation) using RSA with key (e,n) """ def encrypt_rsa(m, e, n): return pow(m,e,n) """ Decrypt message c to decimal representation using RSA with key (d,n) """ def decrypt_rsa(c, d, n): return pow(c,d,n) # Note that while the above functions seem to imply encryption needs the private key and decryption the public key, # they can also be used the other way around. In fact they can be used interchangeably # as they are equal except for variable names. """ Converts a string to its decimal representation by concatenating hexadecimal representations of their ASCII values and converting the result to decimal """ def text_to_decimal(m_text): m_hex = m_text.encode('hex') m_dec = int(m_hex,16) return m_dec """ Converts a long decimal representation of a string to the plaintext string. Opposite process of the previous function """ def long_to_text(m_long, length): # Cast the hex representation to string: easier to slice off unwanted parts m_hex = str(hex(m_long)) # Slice the first two characters (0x) and the final character ('L' for long) m_hex = m_hex[2:len(m_hex) - 1] # Add leading 0s to reach target length m_hex = ((length*2 - len(m_hex)) * "0") + m_hex m_text = m_hex.decode('hex') return m_text
from datetime import datetime #nasc = input('Digite a data de nascimento (00/00/0000): ') nasc = "06/10/1994" nasc = datetime.strptime(nasc, '%d/%m/%Y') hoje = datetime.today() anos = hoje.year - nasc.year - ((hoje.month, hoje.day) < (nasc.month, nasc.day)) print(anos)
balance = 3329 annualInterestRate = 0.2 def payDebt(payment): balanceCopy = balance monthlyIntRate = annualInterestRate / 12 for month in range(12): balanceCopy -= payment balanceCopy += balanceCopy * monthlyIntRate return balanceCopy <= 0 payment = 10 debtPaid = False while not debtPaid: debtPaid = payDebt(payment) if not debtPaid: payment += 10 print("Lowest Payment: " + str(payment))
'this program calculates the intra-variable and inter-variable of power system input.' 'the input is one-year data of household load, PV generation, and EV charging' 'the size of these inputs should be the same' import numpy as np class getdata(object): #to get any one-year timeseries data from csv def __init__(self, csvdata, timerange): self._csvdata = csvdata self._timerange = timerange def givedata(self): return (np.genfromtxt(self._csvdata,delimiter=',')) def resolution(self): #in hour return (8760/self._timerange) class getvar(getdata): #to get the variables. def __init__(self, csvdata, timerange, inputvar): super(getvar,self).__init__(csvdata, timerange) self._inputvar = inputvar def theprof(self): #the time-series profile return(self.givedata()) def theres(self): #the data resolution return(self.resolution()) def intracorr(self): #the intra-var corr return(np.corrcoef(self.givedata(), rowvar=False)) def inputtype(self): return (self._inputvar) def intercorr(var1,var2): #to get the correlation from two different variables corr = [] for i in range(len(var1[0])-1): x = np.corrcoef(var1[:,i+1],var2[:,i+1])[1][0] print(x) corr = corr+[x] return (corr) #example #get the load data from 15 minutes resolution-one year data loaddata = getvar ('household_load.csv',35040,'load') #get the pv data from 15 minutes resolution-one year data pvdata = getvar ('solar_production.csv',35040,'pv') #some information that can be taken is time-series profile as np.array, resolution, and the intra-variable correlation loadintracorr = loaddata.intracorr() #intra-correlation of load pvintracorr = pvdata.intracorr() #intra-correlation of PV #inter-variable correlation between load and pv interc = intercorr(loaddata.theprof(),pvdata.theprof())
######################################################################## # This file is based on the TensorFlow Tutorials available at: # https://github.com/Hvass-Labs/TensorFlow-Tutorials # Published under the MIT License. See the file LICENSE for details. # Copyright 2017 by Magnus Erik Hvass Pedersen ######################################################################## import numpy as np class LinearControlSignal: """ A control signal that changes linearly over time. This is used to change e.g. the learning-rate for the optimizer of the Neural Network, as well as other parameters. TensorFlow has functionality for doing this, but it uses the global_step counter inside the TensorFlow graph, while we want the control signals to use a state-counter for the game-environment. So it is easier to make this in Python. """ def __init__(self, start_value, end_value, num_iterations, repeat=False): """ Create a new object. :param start_value: Start-value for the control signal. :param end_value: End-value for the control signal. :param num_iterations: Number of iterations it takes to reach the end_value from the start_value. :param repeat: Boolean whether to reset the control signal back to the start_value after the end_value has been reached. """ # Store arguments in this object. self.start_value = start_value self.end_value = end_value self.num_iterations = num_iterations self.repeat = repeat # Calculate the linear coefficient. self._coefficient = (end_value - start_value) / num_iterations def get_value(self, iteration): """Get the value of the control signal for the given iteration.""" if self.repeat: iteration %= self.num_iterations if iteration < self.num_iterations: value = iteration * self._coefficient + self.start_value else: value = self.end_value return value ######################################################################## class EpsilonGreedy: """ The epsilon-greedy policy either takes a random action with probability epsilon, or it takes the action for the highest Q-value. If epsilon is 1.0 then the actions are always random. If epsilon is 0.0 then the actions are always argmax for the Q-values. Epsilon is typically decreased linearly from 1.0 to 0.1 and this is also implemented in this class. During testing, epsilon is usually chosen lower, e.g. 0.05 or 0.01 """ def __init__(self, num_actions, epsilon_testing=0.05, num_iterations=1e6, start_value=1.0, end_value=0.1, repeat=False): """ :param num_actions: Number of possible actions in the game-environment. :param epsilon_testing: Epsilon-value when testing. :param num_iterations: Number of training iterations required to linearly decrease epsilon from start_value to end_value. :param start_value: Starting value for linearly decreasing epsilon. :param end_value: Ending value for linearly decreasing epsilon. :param repeat: Boolean whether to repeat and restart the linear decrease when the end_value is reached, or only do it once and then output the end_value forever after. """ # Store parameters. self.num_actions = num_actions self.epsilon_testing = epsilon_testing # Create a control signal for linearly decreasing epsilon. self.epsilon_linear = LinearControlSignal(num_iterations=num_iterations, start_value=start_value, end_value=end_value, repeat=repeat) def get_epsilon(self, iteration, training): """ Return the epsilon for the given iteration. If training==True then epsilon is linearly decreased, otherwise epsilon is a fixed number. """ if training: epsilon = self.epsilon_linear.get_value(iteration=iteration) else: epsilon = self.epsilon_testing return epsilon def get_action(self, q_values, iteration, training, epsilon_override=None): """ Use the epsilon-greedy policy to select an action. :param q_values: These are the Q-values that are estimated by the Neural Network for the current state of the game-environment. :param iteration: This is an iteration counter. Here we use the number of states that has been processed in the game-environment. :param training: Boolean whether we are training or testing the Reinforcement Learning agent. :param epsilon_override: Value to override epsilon for this step only :return: action (integer), epsilon (float) """ if epsilon_override is None: epsilon = self.get_epsilon(iteration=iteration, training=training) else: epsilon = epsilon_override # With probability epsilon. if np.random.random() < epsilon: # Select a random action. action = np.random.randint(low=0, high=self.num_actions) else: # Otherwise select the action that has the highest Q-value. action = np.argmax(q_values) return action, epsilon
import random game=['rock','paper','scissor'] p1=random.choice(game) print("party 1:",p1) p2=random.choice(game) print("party 2:",p2) if p1=='rock' and p2=='scissor': print("p1 won the task") elif p1=='paper' and p2=='rock': print("p1 won the task") elif p1=='scissor' and p2=='paper': print("p1 won the task") else: print("p2 won the task")
# # WELCOME TO PYTHON # # # Programming Python. WEEK 03 # 019 --> 020 # TASK 001 - Types of numbers print(type(10)) # integer print(type(10.5)) # float print(type(5+2j)) # complex print(type(5 == 5)) # boolean #------------------------------------------------- # Task 002 - COMPLEX Number a = 1+2j print(a.imag) print(a.real) #------------------------------------------------- # Task 003 - transfer integer number to real number num = 10 numm = float(num) print('%.10f'%numm) #------------------------------------------------- # Task 004 - transfer real number to integer number num = 159.650 numm = int(num) print(numm) print(type(numm)) #------------------------------------------------- # Task 005 - putting the true operator print(100 - 115 == -15) print(50 * 30 == 1500) print(21 % 4 == 1) print(110 / 11 == 10) print(97 // 20 == 4) #------------------------------------------------- #------------------------------------------------- # 021 --> 023
#!/usr/bin/python3 ''' Code to lear how isinstance() works ''' def is_kind_of_class(obj, a_class): ''' Verify if obj is an instance of a_class''' return isinstance(obj, a_class)
#!/usr/bin/python3 ''' Project for studying doctest in python''' def matrix_divided(matrix, div): '''Function that divides all elements of a matrix''' if div == 0: raise ZeroDivisionError("division by zero") if isinstance(div, (int, float)) is False: raise TypeError("div must be a number") if isinstance(matrix, list) is False or len(matrix) == 0: raise TypeError("matrix must be a matrix (list of lists) \ of integers/floats") for i in range(len(matrix)): if isinstance(matrix[i], list) is False or len(matrix[i]) == 0: raise TypeError("matrix must be a matrix (list of lists) \ of integers/floats") if len(matrix[i]) != len(matrix[0]): raise TypeError("Each row of the matrix must have the same size") for x in range(len(matrix[i])): if isinstance(matrix[i][x], (int, float)) is False: raise TypeError("matrix must be a matrix (list of lists) \ of integers/floats") new_array = [row[:] for row in matrix] for i in range(len(matrix)): for x in range(len(matrix[i])): new_array[i][x] = round(matrix[i][x] / div, 2) return new_array
#!/usr/bin/python3 ''' Code to learn how to read a file ''' def read_file(filename=""): ''' Read filename ''' with open(filename, encoding='UTF-8') as f: for i in f: print(i, end='')
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): new_matrix = [] for sublist in matrix: new_matrix.append(list(map(lambda n: n ** 2, sublist))) return new_matrix
###################################################################### # This module will read and extract Sudoku image from given picture. # The extracted image will be saved in image directory ###################################################################### import numpy as np import cv2 def image_preprocess(img, skip_dilate=False): ''' Cnvert the image to gray scale, blur image, apply adaptive threshold to highlight main features of the image ''' # Gaussian blur to image with kernal size of (9, 9) img_proc = cv2.GaussianBlur(img, (9, 9), 0) # Adaptive threshold using 11 nearest neighbour pixels img_proc = cv2.adaptiveThreshold(img_proc, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # Invert colours, so gridlines have non-zero pixel values. # Necessary to dilate the image, otherwise will look like erosion instead. img_proc = cv2.bitwise_not(img_proc, img_proc) if not skip_dilate: kernel = np.array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]],np.uint8) img_proc = cv2.dilate(img_proc, kernel) return img_proc def find_largest_contour_points(img): ''' find the largest contour in the image''' # Find contours in the image contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Sort the contours in descending order contours = sorted(contours, key=cv2.contourArea, reverse=True) # Draw contour in image #cv2.drawContours(contours[0], bigContour, -1, (255, 0, 0), 3) # Find the perimeter of the lagest contour perimeter = cv2.arcLength(contours[0], True) # Find the polygon details from the contour get_ploy = cv2.approxPolyDP(contours[0], 0.02 * perimeter, True) # Reorder Contour points points = reorder_points(get_ploy) return points def reorder_points(points): ''' reorder contour points''' # reshape contour points array points = points.reshape((4,2)) #print(f'Contour points : { points }') # array to hold re-ordered points points_new = np.zeros((4,1,2), np.int32) # (right, bottom) (left, top) add = points.sum(axis=1) points_new[0] = points[np.argmin(add)] points_new[2] = points[np.argmax(add)] # (lef, bottom) (right, top) diff = np.diff(points, axis = 1) points_new[1] = points[np.argmin(diff)] points_new[3] = points[np.argmax(diff)] return points_new def calculate_distance(pt1, pt2): # calculate distance between two points distance = np.sqrt(((pt1[0][0] - pt2[0][0]) ** 2 ) + ((pt1[0][1] - pt2[0][1]) ** 2)) #print(f'Distance calculated { distance }') return distance def get_warp(image, contour_points): ''' function to corp and warp the image''' # calculate the maximum value of side length side = max([calculate_distance(contour_points[0], contour_points[1]), calculate_distance(contour_points[1], contour_points[2]), calculate_distance(contour_points[2], contour_points[3]), calculate_distance(contour_points[3], contour_points[0])]) #print(f'Side Calculated : { side }') # points source array for perspective transformation pts1 = np.float32(contour_points) # points destination array for perspective transformation pts2 = np.float32([[0, 0], [int(side)-1, 0], [int(side)-1, int(side)-1], [0, int(side)-1]]) # Gets the transformation matrix for skewing the image to fit a square by comparing the 4 before and after points matrix = cv2.getPerspectiveTransform(pts1, pts2) # Performs the transformation on the original image image_out = cv2.warpPerspective(image, matrix, (int(side), int(side))) return image_out def get_digit_boxes(img): ''' function to find the corners of individual sqaures''' digit_boxes = [] side_length = img.shape[:1] side_length = side_length[0] / 9 # the rectangles are stored in the list reading left-right instead of top-down for j in range(9): for i in range(9): # Top left corner of a bounding box pt1 = (i * side_length, j * side_length) # Bottom right corner of bounding box pt2 = ((i +1 ) * side_length, (j + 1) * side_length) digit_boxes.append((pt1, pt2)) return digit_boxes def cut_from_rect(image, box): return image[int(box[0][1]):int(box[1][1]), int(box[0][0]):int(box[1][0])] def find_largest_feature(digit, scan_top_left, scan_btm_rght): height, width = digit.shape[:2] max_area = 0 seed_point = (None, None) if scan_top_left is None: scan_top_left = [0, 0] if scan_btm_rght is None: scan_btm_rght = [height, width] # Loop through the image for x in range(scan_top_left[0], scan_btm_rght[0]): for y in range(scan_top_left[1], scan_btm_rght[1]): if digit.item(y, x) == 255 and x < width and y < height: area = cv2.floodFill(digit, None, (x, y), 64) if area[0] > max_area: max_area = area[0] seed_point = (x, y) # Colour everything grey for x in range(width): for y in range(height): if digit.item(y, x) == 255 and x < width and y < height: cv2.floodFill(digit, None, (x, y), 64) # Mask that is 2 pixels bigger than the image mask = np.zeros((height + 2, width + 2), np.uint8) # Highlight the main feature if all([p is not None for p in seed_point]): cv2.floodFill(digit, mask, seed_point, 255) top, bottom, left, right = height, 0, width, 0 for x in range(width): for y in range(height): if digit.item(y, x) == 64: # Hide anything that isn't the main feature cv2.floodFill(digit, mask, (x, y), 0) # Find the bounding parameters if digit.item(y, x) == 255: top = y if y < top else top bottom = y if y > bottom else bottom left = x if x < left else left right = x if x > right else right # bounding box bbox = [[left, top], [right, bottom]] return np.array(bbox, dtype='float32'), seed_point def scale_and_centre(img, size, margin=0, background=0): """Scales and centres an image onto a new background square.""" h, w = img.shape[:2] def centre_pad(length): """Handles centering for a given length that may be odd or even.""" if length % 2 == 0: side1 = int((size - length) / 2) side2 = side1 else: side1 = int((size - length) / 2) side2 = side1 + 1 return side1, side2 def scale(r, x): return int(r * x) if h > w: t_pad = int(margin / 2) b_pad = t_pad ratio = (size - margin) / h w, h = scale(ratio, w), scale(ratio, h) l_pad, r_pad = centre_pad(w) else: l_pad = int(margin / 2) r_pad = l_pad ratio = (size - margin) / w w, h = scale(ratio, w), scale(ratio, h) t_pad, b_pad = centre_pad(h) img = cv2.resize(img, (w, h)) img = cv2.copyMakeBorder(img, t_pad, b_pad, l_pad, r_pad, cv2.BORDER_CONSTANT, None, background) return cv2.resize(img, (size, size)) def extract_digit(image, box, size): '''Extracts a digit (if one exists) from a Sudoku square.''' # Get the digit box from the whole square digit = cut_from_rect(image, box) # use floodfill feature to find the largest feature in the rectange h, w = digit.shape[:2] margin = int(np.mean([h, w]) / 2.5) bbox, seed = find_largest_feature(digit, [margin, margin], [w - margin, h - margin]) digit = cut_from_rect(digit, bbox) # Scale and pad the digit so that it fits a square of the digit size we're using for machine learning w = bbox[1][0] - bbox[0][0] h = bbox[1][1] - bbox[0][1] # Ignore any small bounding boxes if w > 0 and h > 0 and (w * h) > 100 and len(digit) > 0: return scale_and_centre(digit, size, 4) else: return np.zeros((size, size), np.uint8) def get_digit_images(image, digit_boxes, size=28): digit_images = [] image = image_preprocess(image, skip_dilate=True) for digit_box in digit_boxes: digit_images.append(extract_digit(image, digit_box, size)) return digit_images def show_image(img): """Shows an image until any key is pressed""" #cv2.imshow('image', img) # Display the image cv2.imwrite('images/extract_sudoku.jpg', img) #cv2.waitKey(0) # Wait for any key to be pressed (with the image window active) #cv2.destroyAllWindows() # Close all windows return img def show_digits(digits, colour=255): """Shows list of 81 extracted digits in a grid format""" rows = [] with_border = [cv2.copyMakeBorder(img.copy(), 1, 1, 1, 1, cv2.BORDER_CONSTANT, None, colour) for img in digits] for i in range(9): row = np.concatenate(with_border[i * 9:((i + 1) * 9)], axis=1) rows.append(row) img = show_image(np.concatenate(rows)) return img def extract_sudoku(path): image = cv2.imread(path, cv2.IMREAD_GRAYSCALE) imgContour = image.copy() # preprocess image image_process = image_preprocess(image) # find the corner points of largest image contour_points = find_largest_contour_points(image_process) # crop and warp image image_cropped = get_warp(image, contour_points) cv2.imwrite('images/Cropped_sudoku.jpg', image_cropped) # find the corners of individual digit boxes in puzzle digit_boxes = get_digit_boxes(image_cropped) # get the individual images from the cropped original and resize for machine learning compatibility digit_images = get_digit_images(image_cropped, digit_boxes, size=28) final_image = show_digits(digit_images) return final_image
import esper class Position: def __init__(self, x=0.0, y=0.0): self.x = x self.y = y class Velocity: def __init__(self, x=0.0, y=0.0): self.x = x self.y = y class MovementProcessor(esper.Processor): def __init__(self, minx, maxx, miny, maxy): super().__init__() self.minx = minx self.maxx = maxx self.miny = miny self.maxy = maxy def process(self): # This will iterate over every Entity that has BOTH of these components: for ent, (vel, pos) in self.world.get_components(Velocity, Position): pos.x += vel.x pos.y += vel.y # An example of keeping the sprite inside screen boundaries. Basically, # adjust the position back inside screen boundaries if it tries to go outside: pos.x = max(self.minx, pos.x) pos.y = max(self.miny, pos.y) pos.x = min(self.maxx, pos.x) pos.y = min(self.maxy, pos.y)
#---------------# # DAY 6 # #---------------# def cycle(LS): index = LS.index(max(LS)) steps = LS[index] LS[index] = 0 for i in range(1, steps+1): LS[(index+i)%len(LS)] += 1 ## Part 1 seenPossibilities = set() currentState = [4,10,4,1,8,4,9,14,5,1,14,15,0,15,3,5] totalCycles = 0 while (tuple(currentState) not in seenPossibilities): totalCycles += 1 seenPossibilities.add(tuple(currentState)) cycle(currentState) print("Total cycles =", totalCycles) ## Part 2 seenPossibilities = dict() currentState = [4,10,4,1,8,4,9,14,5,1,14,15,0,15,3,5] totalCycles = 0 while (tuple(currentState) not in seenPossibilities): totalCycles += 1 seenPossibilities[tuple(currentState)] = totalCycles cycle(currentState) print("Previously seen =", seenPossibilities[tuple(currentState)]) print("Cycles since last seen =", totalCycles-seenPossibilities[tuple(currentState)]+1)
def print_reverse(string): print(string[::-1]) print_reverse("python") def print_score(score_list): print(sum(score_list)/len(score_list)) print_score([1,2,3]) def print_even(even_list): for i in even_list: if i%2 == 0: print(i) def print_keys(dic): for keys in dic.keys(): print(keys) def print_value_by_key(dic,key): print(dic[key]) my_dict = {"10/26" : [100, 130, 100, 100], "10/27" : [10, 12, 10, 11]} print_value_by_key(my_dict,"10/26") def print_5xn(line): num = int(len(line)/5) for i in range(num+1): print(line[i*5:i*5+5]) def print_mxn(line,num): number = int(len(line)/num) for i in range(number+1): print(line[i*num:i*num+num]) def calc_monthly_salary(mon): money = int(mon/12) return money def my_print (a, b) : print("왼쪽:", a) print("오른쪽:", b) my_print(a=100, b=200) def my_print (a, b) : print("왼쪽:", a) print("오른쪽:", b) my_print(b=100, a=200)
Power = False # 전원 : false - off, true - on Volume = 10 # 볼륨 : 1 ~ 20 Channel = 1 # 채널 : 1 ~ 10 def power() : global Power if Power == False : Power = True print("| 전원을 켰습니다. |") else : Power = False print("| 전원을 껐습니다. |") def setVolumnUp(size) : global Volume Volume += size if Volume < 1 : Volume = 1 def setVolumnDown(size) : global Volume Volume -= size if Volume > 20 : Volume = 20 def setChannelUp(size) : global Channel Channel += size if Channel < 1 : Channel = 1 def setChannelDown(size) : global Channel Channel -= size if Channel > 10 : Channel = 10 def getNow() : print("==========================") print("현재의 상태를 출력합니다.") print("TV의 전원 : ") if Power == True : print("켜져있습니다.") else : print("꺼져있습니다.") print("TV의 볼륨 : " + str(Volume)) print("TV의 채널 : " + str(Channel)) print("==========================") while True : print("======================================") print("1. 전원 끄기") print("2. 전원 켜기") print("3. 볼륨 조절") print("4. 채널 조절") print("5. 현재의 상태 출력") print("6. 프로그램 종료") print("======================================") order = int(input("원하는 기능의 번호를 입력하세요 >> ")) if order == 1: if Power == False : print("이미 꺼져있습니다.") else : power() elif order == 2 : if Power == True : print("이미 켜져있습니다.") else : power() elif order == 3 : if Power == False : print("TV가 꺼져있습니다.") else : size = int(input("볼륨을 조정합니다 :: 범위 1~20\n조절하고자 하는 값을 입력하세요 >> ")) if size > 0 : setVolumnUp(size) else : setVolumnDown(size * -1) elif order == 4 : if Power == False : print("TV가 꺼져있습니다.") else : size = int(input("채널을 조정합니다 :: 범위 1~10\n조절하고자 하는 값을 입력하세요 >> ")) if size > 0 : setChannelUp(size) else : setChannelDown(size * -1) elif order == 5 : getNow() elif order == 6 : print("프로그램을 종료합니다.") break else : print("기능의 번호를 잘 못 누르셨습니다. 범위는 1 ~ 6입니다. ")
book = {} book["파이썬"] = "최근에 가장 떠오르는 프로그래밍 언어" book["변수"] = "데이터를 저장하는 메모리 공간" book["함수"] = "작업을 수행하는 문장들의 집합에 이름을 붙인 것" book["리스트"] = "서로 관련이 없는 항목들의 모임" print("다음은 어떤 단어에 대한 설명일까요\n") print("==================================") for key in book.keys(): print(book[key],"?") i = 1 for probloem in book.keys(): print(str("(") + str(i) + str(")"), probloem ,end="\t") i += 1 a = input("\n>> ") if a == key: print("정답입니다!") else: print("오답입니다.")
__author__ = 'Deeplayer' # 6.15.2016 # import numpy as np import matplotlib.pyplot as plt from TwoLayerNN import TwoLayerNet from data_utils import load_CIFAR10 # Load the data def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000): """ Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for the two-layer neural net classifier. These are the same steps as we used for the SVM, but condensed to a single function. """ # Load the raw CIFAR-10 data cifar10_dir = 'E:/PycharmProjects/ML/CS231n/cifar-10-batches-py' X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir) # Subsample the data mask = range(num_training, num_training + num_validation) X_val = X_train[mask] # (1000,32,32,3) y_val = y_train[mask] # (1000L,) mask = range(num_training) X_train = X_train[mask] # (49000,32,32,3) y_train = y_train[mask] # (49000L,) mask = range(num_test) X_test = X_test[mask] # (1000,32,32,3) y_test = y_test[mask] # (1000L,) # Normalize the data: subtract the mean image mean_image = np.mean(X_train, axis=0) X_train -= mean_image X_val -= mean_image X_test -= mean_image # Reshape data to rows X_train = X_train.reshape(num_training, -1) # (49000,3072) X_val = X_val.reshape(num_validation, -1) # (1000,3072) X_test = X_test.reshape(num_test, -1) # (1000,3072) return X_train, y_train, X_val, y_val, X_test, y_test # Invoke the above function to get our data. X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data() print 'Train data shape: ', X_train.shape print 'Train labels shape: ', y_train.shape print 'Validation data shape: ', X_val.shape print 'Validation labels shape: ', y_val.shape print 'Test data shape: ', X_test.shape print 'Test labels shape: ', y_test.shape # To train our network we will use SGD with momentum. In addition, we will # adjust the learning rate with an exponential learning rate schedule as optimization proceeds; # after each epoch, we will reduce the learning rate by multiplying it by a decay rate. input_size = 32 * 32 * 3 hidden_size = 50 num_classes = 10 net = TwoLayerNet(input_size, hidden_size, num_classes) # Train the network stats = net.train(X_train, y_train, X_val, y_val, num_epochs=4, batch_size=200, mu=0.5, mu_increase=1.0, learning_rate=1e-4, learning_rate_decay=0.95, reg=0.5, verbose=True) # Predict on the validation set val_acc = (net.predict(X_val) == y_val).mean() print 'Validation accuracy: ', val_acc # Debug the training. """ With the default parameters we provided above, you should get a validation accuracy of about 0.29 on the validation set. This isn't very good. - One strategy for getting insight into what's wrong is to plot the loss function and the accuracies on the training and validation sets during optimization. - Another strategy is to visualize the weights that were learned in the first layer of the network. In most neural networks trained on visual data, the first layer weights typically show some visible structure when visualized. """ # Plot the loss function and train / validation accuracies plt.subplot(2, 1, 1) plt.plot(stats['loss_history']) plt.title('Loss history') plt.xlabel('Iteration') plt.ylabel('Loss') plt.subplot(2, 1, 2) plt.plot(stats['train_acc_history'], label='train') plt.plot(stats['val_acc_history'], label='val') plt.title('Classification accuracy history') plt.xlabel('Epoch') plt.ylabel('Classification accuracy') plt.legend(bbox_to_anchor=(1.0, 0.4)) plt.show() # Visualize the weights of the network from vis_utils import visualize_grid def show_net_weights(net): W1 = net.params['W1'] W1 = W1.reshape(32, 32, 3, -1).transpose(3, 0, 1, 2) plt.imshow(visualize_grid(W1, padding=3).astype('uint8')) plt.gca().axis('off') plt.show() show_net_weights(net)
from data_utils import load_CIFAR10 import matplotlib.pyplot as plt from Linear_Classifier import * import numpy as np def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000, num_dev=500): """ Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for the linear classifier. These are the same steps as we used for the SVM, but condensed to a single function. """ # Load the raw CIFAR-10 data cifar10_dir = 'E:/PycharmProjects/ML/CS231n/cifar-10-batches-py' X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir) # subsample the data mask = range(num_training, num_training + num_validation) X_val = X_train[mask] y_val = y_train[mask] mask = range(num_training) X_train = X_train[mask] y_train = y_train[mask] mask = range(num_test) X_test = X_test[mask] y_test = y_test[mask] mask = np.random.choice(num_training, num_dev, replace=False) X_dev = X_train[mask] y_dev = y_train[mask] # Preprocessing: reshape the image data into rows X_train = np.reshape(X_train, (X_train.shape[0], -1)) X_val = np.reshape(X_val, (X_val.shape[0], -1)) X_test = np.reshape(X_test, (X_test.shape[0], -1)) X_dev = np.reshape(X_dev, (X_dev.shape[0], -1)) # Normalize the data: subtract the mean image mean_image = np.mean(X_train, axis = 0) X_train -= mean_image X_val -= mean_image X_test -= mean_image X_dev -= mean_image # add bias dimension and transform into columns X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))]) X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))]) X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))]) X_dev = np.hstack([X_dev, np.ones((X_dev.shape[0], 1))]) return X_train, y_train, X_val, y_val, X_test, y_test, X_dev, y_dev # Invoke the above function to get our data. X_train, y_train, X_val, y_val, X_test, y_test, X_dev, y_dev = get_CIFAR10_data() print 'Train data shape: ', X_train.shape print 'Train labels shape: ', y_train.shape print 'Validation data shape: ', X_val.shape print 'Validation labels shape: ', y_val.shape print 'Test data shape: ', X_test.shape print 'Test labels shape: ', y_test.shape print 'dev data shape: ', X_dev.shape print 'dev labels shape: ', y_dev.shape from Softmax import softmax_loss_naive import time # Generate a random softmax weight matrix and use it to compute the loss. W = np.random.randn(3073, 10) * 0.0001 loss, grad = softmax_loss_naive(W, X_dev, y_dev, 0.0) # As a rough sanity check, our loss should be something close to -log(0.1). print 'loss: %f' % loss print 'sanity check: %f' % (-np.log(0.1)) tic = time.time() loss_naive, grad_naive = softmax_loss_naive(W, X_dev, y_dev, 0.00001) toc = time.time() print 'naive loss: %e computed in %fs' % (loss_naive, toc - tic) from Softmax import softmax_loss_vectorized tic = time.time() loss_vectorized, grad_vectorized = softmax_loss_vectorized(W, X_dev, y_dev, 0.00001) toc = time.time() print 'vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic) # As we did for the SVM, we use the Frobenius norm to compare the two versions # of the gradient. grad_difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro') print 'Loss difference: %f' % np.abs(loss_naive - loss_vectorized) print 'Gradient difference: %f' % grad_difference results = {} best_val = -1 best_softmax = None learning_rates = [1e-7, 5e-7] regularization_strengths = [5e4, 1e4] iters = 1500 for lr in learning_rates: for rs in regularization_strengths: soft = Softmax() soft.train(X_train, y_train, learning_rate=lr, reg=rs, num_iters=iters) Tr_pred = soft.predict(X_train.T) acc_train = np.mean(y_train == Tr_pred) Val_pred = soft.predict(X_val.T) acc_val = np.mean(y_val == Val_pred) results[(lr, rs)] = (acc_train, acc_val) if best_val < acc_val: best_val = acc_val best_soft = soft # Print out results. for lr, reg in sorted(results): train_accuracy, val_accuracy = results[(lr, reg)] print 'lr %e reg %e train accuracy: %f val accuracy: %f' % ( lr, reg, train_accuracy, val_accuracy) print 'best validation accuracy achieved during cross-validation: %f' % best_val # Evaluate the best svm on test set. Ts_pred = best_soft.predict(X_test.T) test_accuracy = np.mean(y_test == Ts_pred) # about 37.1% print 'LinearSVM on raw pixels of CIFAR-10 final test set accuracy: %f' % test_accuracy
import random MOTS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") mot = random.choice(MOTS) mot_choisi = mot mot_masque = mot_choisi[0:-1]+"_" chance=3 while chance>0: print(f"Le mot choisi est {mot_masque} ") devinette=input("Trouver la derniere lettre: ") if (devinette == mot_choisi[-1]): print("Bravo! Vous avez bien trouve la lettre qui termine cette phrase") break else: chance-=1 print(f"desole vous avez perdu , il vous reste {chance} chance(s)")
#This is a guess the number game. import random guessesTaken = 0 print ('System: Hello! What is your name?') myName = input("Me: ") number = random.randint (1, 20) print('System: Well, '+myName+', I am thinking of a number between 1 and 20') while guessesTaken < 6: guess = int(input("System: Take a guess: ")) guessesTaken = guessesTaken + 1 if guess < number: print('Your guess is too low.') if guess > number: print ('System: Your guess is too high') if guess == number: break if guess == number: guessesTaken = str(guessesTaken) print('System: Good job,'+myName+'! You guessed my number in '+guessesTaken+' guesses.') if guess !=number: number = str(number) print ('System: Nope. The number i was thinking was '+number)
class MagicDictionary: def __init__(self): """ Initialize your data structure here. """ self.words = {} def buildDict(self, dict: List[str]) -> None: """ Build a dictionary through a list of words """ for w in dict: self.words[w] = 1 def search(self, word: str) -> bool: """ Returns if there is any word in the trie that equals to the given word after modifying exactly one character """ for w in self.words: if len(w) == len(word): if w == word: continue # Check if replaceable for i, l in enumerate(w): for c in range(ord('a'), ord('z') + 1): formed = (w[:i] + chr(c) + w[i+1:]) # print(formed) if formed == word: return True return False # Your MagicDictionary object will be instantiated and called as such: # obj = MagicDictionary() # obj.buildDict(dict) # param_2 = obj.search(word)
''' # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail ''' def summation(n): if (n==0): return 0; if (n&1): return (int((n + 1) // 2)**2 + summation(int(n // 2))) else: return (int(n // 2)**2 + summation(int(n // 2))) n = int(input()) for _ in range(n): N,M = list(map(int, input().split())) s = 0 print(summation(N)%M)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: parents = {} # key is TreeNode, value: TreeNode that is the parent moves = 0 def traverse(self, node): if (node): if node.left != None: self.parents[node.left] = node if node.right != None: self.parents[node.right] = node self.traverse(node.left) self.traverse(node.right) def fill(self, node): if (node): if (node.val == 0): self.moves += self.findspare(node, node, {}, 0) # Go to children afterwards self.fill(node.left) self.fill(node.right) def findspare(self, node, curnode, seen, travelled): # print("find spare") # Found spare already if node.val == 1: return 999 if curnode in seen and seen[curnode] < travelled: return 999 else: seen[curnode] = travelled # Move upwards and two ways downwards to find a spare coin node if (curnode): if curnode.val > 1: curnode.val -= 1 node.val += 1 # self.moves += travelled return travelled else: lef = self.findspare(node, curnode.left, seen, travelled + 1) rig = self.findspare(node, curnode.right, seen, travelled + 1) up = 999 # find parent if curnode in self.parents: up = self.findspare(node, self.parents[curnode], seen, travelled + 1) return min(lef, rig, up) return 999 def distributeCoins(self, root): """ :type root: TreeNode :rtype: int """ self.traverse(root) self.fill(root) return self.moves
#! /usr/bin/python3 import sys import math line = sys.stdin.readline() date = line.split() if (date[0] == "OCT" and date[1] == "31") or (date[0] == "DEC" and date[1] == "25"): print("yup") else: print("nope")
class TimeMap: def __init__(self): """ Initialize your data structure here. """ self.ht = {} # key: key of set, value: dict of: key: timestamp, value: value def set(self, key: 'str', value: 'str', timestamp: 'int') -> 'None': if key not in self.ht: self.ht[key] = { timestamp: value } else: self.ht[key][timestamp] = value def get(self, key: 'str', timestamp: 'int') -> 'str': if key not in self.ht: return "" else: # print("searching") previous = -1 for ts, value in sorted(self.ht[key].items()): # print(ts, value) if ts > timestamp: if previous == -1: return "" return self.ht[key][previous] previous = ts if previous == -1: return "" return self.ht[key][previous] # Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key,value,timestamp) # param_2 = obj.get(key,timestamp)
# class LLNode: # def __init__(self, val, next=None): # self.val = val # self.next = next class Solution: def solve(self, node): # Write your code here fast = node slow = node vals = [slow.val] j = 0 while fast != None and fast.next != None: fast = fast.next.next slow = slow.next vals.append(slow.val) j += 2 if fast != None: j += 1 vals.pop() # pop last one is midpoint? head = slow # slow is now mid i = len(vals)-1 if j % 2 == 1: slow = slow.next # skip on odd fold over while slow != None: slow.val += vals[i] slow = slow.next i -= 1 return head
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ oneleng = 0 pt = l1 while(pt != None): pt = pt.next oneleng += 1 twoleng = 0 pt = l2 while(pt != None): pt = pt.next twoleng += 1 ans = 0 while(oneleng != twoleng): if oneleng > twoleng: ans *= 10 ans += l1.val l1 = l1.next oneleng -= 1 else: ans *= 10 ans += l2.val l2 = l2.next twoleng -= 1 while(oneleng > 0): ans *= 10 ans += (l1.val + l2.val) oneleng -= 1 twoleng -= 1 l1 = l1.next l2 = l2.next a = None f = a for digit in str(ans): if a == None: a = ListNode(int(digit)) a.next = None f = a else: b = ListNode(int(digit)) a.next = b a = b return f
class Solution(object): def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ counter = 1 odd = 1 while(counter <= num): if(counter == num): return True odd += 2 counter += odd print(counter) return False
class Solution: def findIntegers(self, num): """ :type num: int :rtype: int """ total = num saved = num if(num == 1): return 2 if(num == 2): return 3 if(num == 3): return 3 maxi = 0 num = num // 3 if (num < 1): maxi = 0 elif (num == 0): maxi = 0 else: maxi = 1 while(num > 2): num = num // 2 maxi += 1 if(num == 0): maxi -= 1 else: total += 1 # maxi is the number of zeroes counter = maxi total += saved for z in range(0, maxi): total -= ((2**counter) - 1) counter -= 1 return total
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA p2 = headB while p1 != None and p2 != None: p1 = p1.next p2 = p2.next # p1 is shorter if p2 == None: p1, p2 = p2, p1 headA, headB = headB, headA adj = 0 while p2 != None: p2 = p2.next adj += 1 # New run with adj p1 = headA p2 = headB for i in range(0, adj): p2 = p2.next while p1 != None and p2 != None: if p1.val == p2.val: return p1 p1 = p1.next p2 = p2.next return None
n = int(input()) for i in range(n): num = int(input()) if num % 2 == 0: print(str(num) + " is even") else: print(str(num) + " is odd")
# -*- coding: utf-8 -*- """ Created on Wed Dec 30 01:14:25 2020 @author: user """ day=input("請輸入月及日為:").split() m=day[0] d=day[1] m=int(m) d=int(d) if(m==1): if(d>20): print("星座為Aquarius") else: print("星座為Capricorn") elif(m==2): if(d>18): print("星座為Pisces") else: print("星座為Aquarius") elif(m==3): if(d>20): print("星座為Aries") else: print("星座為Pisces") elif(m==4): if(d>20): print("星座為Taurus") else: print("星座為Aries") elif(m==5): if(d>21): print("星座為Gemini") else: print("星座為Taurus") elif(m==6): if(d>21): print("星座為Cancer") else: print("星座為Gemini") elif(m==7): if(d>22): print("星座為Leo") else: print("星座為Cancer") elif(m==8): if(d>23): print("星座為Virgo") else: print("星座為Leo") elif(m==9): if(d>23): print("星座為Libra") else: print("星座為Virgo") elif(m==10): if(d>23): print("星座為Scorpio") else: print("星座為Libra") elif(m==11): if(d>22): print("星座為Sagittarius") else: print("星座為Scorpio") elif(m==12): if(d>21): print("星座為Capricorn") else: print("星座為Sagittarius")
# -*- coding: utf-8 -*- """ Created on Mon Dec 28 15:31:05 2020 @author: user """ x=input("輸入查詢學號為:") st={"123":"Tom DTGD","456":"Cat CSIE","789":"Nana ASIE","321":"Lim DBA","654":"Won FDD"} if x in st: print("學生資料為:"+x,st[x]) else: print("無該名學生")
num = [] num1 = int(input("How many number do you want to write (range is 1-20)?")) if num1 < 1 or num1 > 20: print("I SAID RANGE IS 1-20... Run again now...") else: for i in range(num1): temp = input("Enter Number " + str(i + 1) + ": ") num.append(temp) flag = 0 num2 = num[:] num2.sort() if (num == num2): flag = 1 if (flag): print("List is sorted") else: print("List is not sorted") num2.sort(reverse=True) top5 = [] for i in range(min(5, len(num2))): top5.append(num2[i]) print(top5)
import cv2 from evaluation import * import pickle def rectangle_area(rect): x, y, w, h = rect return w*h def contour2rectangle(contours): # Get bounding rectangle for each found contour and sort them by area rects = [] for i in contours: y, x, h, w = cv2.boundingRect(i) rects.append([x, y, w, h]) rects = sorted(rects, key=rectangle_area, reverse=True) return rects def inside_rectangle(rectangle_a, rectangle_b): # Return false if the position of one point of rectangle B is inside rectangle A. Rectangle = [x,y,w,h] xa,ya,wa,ha = rectangle_a xb,yb,wb,hb = rectangle_b if xb>=xa and xb<=(xa+wa) and yb>=ya and yb<=(ya+ha): # Point xb,yb is inside A return True elif (xb+wb)>=xa and (xb+wb)<=(xa+wa) and yb>=ya and yb<=(ya+ha): # Point xb+wb,yb is inside A return True elif xb>=xa and xb<=(xa+wa) and (yb+hb)>=ya and (yb+hb)<=(ya+ha): # Point xb,yb+hb is inside A return True elif (xb+wb)>=xa and (xb+wb)<=(xa+wa) and (yb+hb)>=ya and (yb+hb)<=(ya+ha): # Point xb+wb,yb+hb is inside A return True xa,ya,wa,ha = rectangle_b xb,yb,wb,hb = rectangle_a if xb>=xa and xb<=(xa+wa) and yb>=ya and yb<=(ya+ha): # Point xb,yb is inside A return True elif (xb+wb)>=xa and (xb+wb)<=(xa+wa) and yb>=ya and yb<=(ya+ha): # Point xb+wb,yb is inside A return True elif xb>=xa and xb<=(xa+wa) and (yb+hb)>=ya and (yb+hb)<=(ya+ha): # Point xb,yb+hb is inside A return True elif (xb+wb)>=xa and (xb+wb)<=(xa+wa) and (yb+hb)>=ya and (yb+hb)<=(ya+ha): # Point xb+wb,yb+hb is inside A return True return False # Returns true if restrictions are satisfied def satisfy_restrictions(rectangle, shape_image): min_prop_area = 0.2 min_ratio = 0.25 max_ratio = 4 x, y, w, h = rectangle # rect has a minimum area if w * h < (shape_image[0]*min_prop_area)*(shape_image[1]*min_prop_area): return False # ratio of h/w isn't smaller than 1/4 ratio = w / h if ratio <= min_ratio or ratio >= max_ratio: return False return True def compute_contours(image): # Convert image to HSV an use only saturation channel (has most information) img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # We apply an gaussian filter to remove possible noise from the image img_hsv_blur = cv2.GaussianBlur(img_hsv[:, :, 1], (5, 5), 0) # Get edges using Canny algorithm # edged = cv2.Canny(img_hsv_blur, 0, 255) edged = cv2.Canny(img_hsv_blur, 60, 120) # edged = cv2.Canny(img_hsv_blur, 80, 140) # Apply close transformation to eliminate smaller regions kernel = np.ones((5,5),np.uint8) edged = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel) # find contours contours, hierarchy = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)/v.CHAIN_APPROX_SIMPLE return contours # Subtracts de background from the image and returns cropped_img and mask (mask = rectangle) def compute_mask(image): contours = compute_contours(image) bbx = [] # If contours not found, pass whole image if not contours: mask = np.ones(image.shape) else: rects = contour2rectangle(contours) x1,y1,w1,h1 = rects[0] # Search for a second painting found = False rects = rects[1:] cnt2 = [] cmpt = 0 while not found and (cmpt<len(rects)): if inside_rectangle([x1, y1, w1, h1], rects[cmpt]) or not satisfy_restrictions(rects[cmpt],image.shape): cmpt = cmpt+1 else: cnt2 = rects[cmpt] found = True # Initialize mask & activate the pixels inside the rectangle mask = np.zeros(image.shape[:2],np.uint8) mask[x1:x1+w1, y1:y1+h1] = 1 bbx.append([x1, y1, w1, h1]) # Save rectangle points if len(cnt2)>0: x2, y2, w2, h2 = cnt2 mask[x2:x2 + w2, y2:y2 + h2] = 1 if x2<x1 or y2<y1: # Order rectangles from left to right or top to bottom bbx = [[x2, y2, w2, h2], [x1, y1, w1, h1]] else: bbx.append([x2, y2, w2, h2]) # Save rectangle points # Mask multiplied *255 to equal the values of the groundtruth images return bbx, mask*255 # Subtracts de background from the image and returns cropped_img and mask (mask = rectangle) def compute_croppedimg(image): contours = compute_contours(image) cropped_images = [] coord_images = [] # If contours not found, pass whole image if not contours: cropped_images.append(image) else: rects = contour2rectangle(contours) # for x in rects: # cv2.rectangle(image,(x[1],x[0]),(x[1]+x[3],x[0]+x[2]),(0,0,0),3) # plt.subplot(133), plt.imshow(image) # plt.show() x1, y1, w1, h1 = rects[0] if (w1*h1)<(1/10)*(np.size(image,0)*np.size(image,1)): x1 = 0 y1 = 0 w1 = np.size(image,0) h1 = np.size(image,1) # Search for a second painting found = False cnt1 = rects[0] rects = rects[1:] cnt2 = [] cnt3 = [] cmpt = 0 while not found and (cmpt < len(rects)): if inside_rectangle([x1, y1, w1, h1], rects[cmpt]) or not satisfy_restrictions(rects[cmpt], image.shape): cmpt = cmpt + 1 else: cnt2 = rects[cmpt] rects.pop(cmpt) found = True if len(cnt2) > 0: x2, y2, w2, h2 = cnt2 cmpt = 0 found = False while not found and (cmpt < len(rects)): if inside_rectangle([x1, y1, w1, h1], rects[cmpt]) or \ inside_rectangle([x2, y2, w2, h2], rects[cmpt]) or \ not satisfy_restrictions(rects[cmpt], image.shape): cmpt = cmpt + 1 else: cnt3 = rects[cmpt] found = True # Initialize mask & activate the pixels inside the rectangle mask = np.zeros(image.shape[:2], np.uint8) mask[x1:x1 + w1,y1:y1 + h1] = 1 if len(cnt2) > 0: x2, y2, w2, h2 = cnt2 mask[x2:x2 + w2,y2:y2 + h2] = 1 if len(cnt3) > 2: x3, y3, w3, h3 = cnt3 mask[x3:x3 + w3, y3:y3 + h3] = 1 sorted_paintings = orderPaintings(cnt1, cnt2, cnt3) for sp in sorted_paintings: cropped_images.append(image[sp[0]:sp[0]+sp[2],sp[1]:sp[1]+sp[3]]) x1 = sp[1] y1 = sp[0] x2 = x1 + sp[3] y2 = y1 x3 = x2 y3 = y2 + sp[2] x4 = x1 y4 = y3 coords = [(x1,y1), (x2,y2), (x3,y3), (x4,y4)] coord_images.append(coords) return cropped_images, coords def orderPaintings(cnt1,cnt2,cnt3): # if cnt2 != []: # if (cnt1[2]+cnt1[0])<cnt2[0]: # # cnt1 is on the left side of cnt2 # # cropped_images = [image[cnt1[0]:cnt1[0] + cnt1[2], cnt1[1]:cnt1[1] + cnt1[3],:], image[cnt2[0]:cnt2[0] + cnt2[2], cnt2[1]:cnt2[1] + cnt2[3],:]] # if cnt3 != []: # # # if x2 < x1 or y2 < y1: # Order rectangles from left to right or top to bottom # cropped_images = [image[x2:x2 + w2, y2:y2 + h2:], image[x1:x1 + w1, y1:y1 + h1, :]] # else: # cropped_images.append(image[x2:x2 + w2, y2:y2 + h2, :]) # Save rectangle points if cnt3: sortedcnt = sorted([cnt1,cnt2,cnt3], key=lambda x: x[1]) elif cnt2: sortedcnt = sorted([cnt1, cnt2], key=lambda x: x[1]) else: sortedcnt = [cnt1] return sortedcnt # Subtracts de background from a list of images and returns a list of masks def get_mask_array(imgarray): masks = [] for i in imgarray: masks.append(compute_mask(i)[1]) return masks # Gets boundingboxes from the pictures in the images (Max: 2 pictures/image) def get_pictbbs_array(imgarray): masks = [] for i in imgarray: masks.append(compute_mask(i)[0]) return masks # returns cropped images, separated paintings not images def crop_imgarray(imgarray): cropped_imgs = [] coords_imgs = [] for i in imgarray: paints_img = [] coords_paint = [] crpimg, coords = compute_croppedimg(i) for painting in crpimg: paints_img.append(painting) coords_paint.append(coords) cropped_imgs.append(paints_img) coords_imgs.append(coords_paint) return cropped_imgs, coords_imgs # Return list of images with list of paintings, and also saves it if given a filename def get_result_pkl(imgarray,filename=None): cropped_imgs = [] for i in imgarray: cropped_imgs.append(compute_croppedimg(i)) if filename: outfile = open(filename,'wb') pickle.dump(cropped_imgs,outfile) outfile.close() return cropped_imgs def mask_evaluation(images,masks): PRs = [] RCs = [] F1s = [] for i in range(len(images)): PR, RC, F1 = evaluation(images[i][:,:,0], masks[i]) PRs.append(PR) RCs.append(RC) F1s.append(F1) return PRs, RCs, F1s
""" Creates and adds data to JSON file """ import os import json filename = './url_data.json' class UrlData: def add(self, url, tags): if os.path.isfile(filename): # File already exists, return populated dict. with open(filename) as file: data = json.load(file) data.append({ 'link': url, 'tags': tags }) else: data = [{ 'link': url, 'tags': tags }] with open(filename, 'w') as f: json.dump(data, f)
import random import string class WordList(object): def __init__(self): self.__file_a = "wordsFiles/palavras.txt" self.__file_b = "wordsFiles/words.txt" def createWordList(self, file_choice): """ Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(file_choice, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def get_secret_word(self, option): if option == '1': file_choice = self.__file_a else: file_choice = self.__file_b wordlist = self.createWordList(file_choice) randomWord = random.choice(wordlist).lower() testedWord = self.checkNumberOfLetters(randomWord) return testedWord def checkNumberOfLetters(self, word): while True: if len(word) <= 8: return word
import itertools def zbits(n, k): """ :param n: binary strings of length :param k: k zero bits :return: all binary strings of length n that contain k zero bits, one per line. """ # specify the number of zero num_zero = "0" * k # specify the number of one num_one = "1" * (n-k) string = num_zero + num_one strings_list = set() # use itertools print the permutations of the binary string for i in itertools.permutations(string, n): strings_list.add(''.join(i)) return strings_list if __name__ == '__main__': assert zbits(4, 3) == {'0100', '0001', '0010', '1000'} assert zbits(4, 1) == {'0111', '1011', '1101', '1110'} assert zbits(5, 4) == {'00001', '00100', '01000', '10000', '00010'}
class TBankomat: def __init__(self,n5,n10,n20,n50,n100,n200): self.n5 = n5 self.n10 = n10 self.n20 = n20 self.n50 = n50 self.n100 = n100 self.n200 = n200 @property def max(self): return self.n5 * 5 + self.n10 * 10 + self.n20 * 20 + self.n50 * 50 + self.n100 * 100 + self.n200 * 200 def profit_from_robbery(self): return self.max def min_money_to_take(self): if self.n5 != 0: return 5 elif self.n10 != 0: return 10 elif self.n20 != 0: return 20 elif self.n50 != 0: return 50 elif self.n100 != 0: return 100 elif self.n200 != 0: return 200 else: return "нема" def take_some_money(self,value): '''число має бути кратне 5''' if value > self.max: print('недостатньо грошей') if value % 5 == 0: money = [0 for i in range(6)] while value != 0: if value >= 200 and self.n200 != 0: value -= 200 money[0] += 1 self.n200 -= 1 elif value >= 100 and self.n100 != 0: value -= 100 money[1] += 1 self.n100 -= 1 elif value >= 50 and self.n50 != 0: value -= 50 money[2] += 1 self.n50 -= 1 elif value >= 20 and self.n20 != 0: value -= 20 money[3] += 1 self.n20 -= 1 elif value >= 10 and self.n10 != 0: value -= 10 money[4] += 1 self.n10 -= 1 elif value >= 5 and self.n5 != 0: value -= 5 money[5] += 1 self.n5 -= 1 print('200:{0}\n100:{1}\n50:{2}\n20:{3}\n10:{4}\n5:{5}'.format(money[0],money[1],money[2],money[3],money[4],money[5])) else: print('операція неможлива') Bankomat1 = TBankomat(10,10,10,10,10,10) Bankomat1.take_some_money(1150)
from random import randint #import matplotlib.pylab as plt ALPHABET = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ' def encrypt(plain_text, key): plain_text = plain_text.upper() cipher_text = "" for index, char in enumerate(plain_text): key_index = key[index] char_index = ALPHABET.find(char) cipher_text += ALPHABET[(char_index+key_index)%len(ALPHABET)] return cipher_text def decrypt(cipher_text, key): plain_text = "" for index, char in enumerate(cipher_text): key_index = key[index] char_index = ALPHABET.find(char) plain_text += ALPHABET[(char_index-key_index)%len(ALPHABET)] return plain_text def random_sequence(plain_text): random_sequence = [] for rand in range(len(plain_text)): random_sequence.append(randint(0,len(ALPHABET))) return random_sequence #from 2 Frequency analysis def frequency_analysis(plain_text): plain_text = plain_text.upper() #assign dictionary to count letter frequency pair letter_frequency = {} #initiallize the dictionary content with zero for letter in LETTERS: letter_frequency[letter] = 0 #count each letter using for loop for letter in cipher_text: if letter in LETTERS: letter_frequency[letter] += 1 return letter_frequency def plot_distribution(letter_frequency): centers = range(len(ALPHABET)) plt.bar(centers, letter_frequency.values(), align='center', tick_label=letter_frequency.keys()) plt.xlim([0,len(ALPHABET)-1]) plt.show() if __name__ == "__main__": plain_text = "ji sung park" print("Original message: %s" % plain_text) key = random_sequence(plain_text) cipher_text = encrypt(plain_text, key) print("Encrypted message: %s" % cipher_text) decrypted_text = decrypt(cipher_text, key) print("Decrypted message: %s" % decrypted_text) # plot_distribution(frequency_analysis(cipher_text))
from math import sqrt from math import floor def factor(num): factors = [] limit = floor(sqrt(num)) for n in range(2, limit): if num % n == 0: factors.append(n) factors.append(int(num/n)) return sorted(factors) if __name__ == "__main__": print(factor(210)) print(factor(11))
q = int(input("length: ")) i = int(input("frequency: ")) w = 1 while True: print("a" * w) w += i if w >= q: while w != 1: print("a" * w) w -= i
#!/usr/bin/python while True: s=raw_input('Enter someing:') if s=='quit': break print 'Length of the string is',len(s) print 'Done'
#!/usr/bin/python # -*- coding: UTF-8 -*- import time; import ticks = time.time() print "当前时间戳为:",ticks localtime = time.localtime(time.time()) print "本地时间为:",localtime localtime = time.asctime(time.localtime(time.time())) print "本地时间为:",localtime print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) print time.strftime("%a %b %d %H:%M:%S %Y",time.localtime()) a = "Sat Mar 28 22:24:24 2016" print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
#This module defines a subclass of Dealer. """ Class ------ Dealer attributes: inherits from Player methods overriding: get_strategy: dealer's strategy. show_result:print hand and values """ from players.player import Player class Dealer(Player): @classmethod def get_strategy(cls,hand): if hand.value < 17: return 'H' else: return 'S' def show_result(self,hand): final_hand = [card.value for card in hand.cards] print("Dealer's hand:", final_hand) print("Dealer's total values:", hand.value)
#This module defines a basic class of card and deck. #Current game version, one standard 52-card deck. """ Class ------ Card ------ Deck attribute: deck: a list of standard 52 cards. method: init_deck: append 52 cards shuffle deal: pop 1 card """ from random import shuffle from data.enum import suits,values class Card: def __init__(self,suit,name,value): self.suit = suit self.name = name self.value = value class Deck: def __init__(self): self.deck = [] def init_deck(self): for suit in suits: for name in values.keys(): self.deck.append(Card(suit,name,values[name])) self.shuffle() def shuffle(self): shuffle(self.deck) def deal(self): return self.deck.pop()
def solution(record): answer = [] uidList = dict() for rec in record: cmd = rec.split(" ") if cmd[0] == "Enter" or cmd[0] == "Change": uidList[cmd[1]] = cmd[2] for rec in record: cmd = rec.split(" ") str = uidList[cmd[1]] if cmd[0] == "Enter": str += "님이 들어왔습니다." answer.append(str) elif cmd[0] == "Leave": str += "님이 나갔습니다." answer.append(str) return answer
x = "Hello World" # str print(type(x)) x = 20 # int print(type(x)) x = 20.5 # float print(type(x)) x = 1j # complex print(type(x)) x = ["apple", "banana", "cherry"] # list print(type(x)) x = ("apple", "banana", "cherry") # tuple print(type(x)) x = range(6) # range print(type(x)) x = {"name" : "John", "age" : 36} # dict print(type(x)) x = {"apple", "banana", "cherry"} # set print(type(x)) x = frozenset({"apple", "banana", "cherry"}) # frozenset print(type(x)) x = True # bool print(type(x)) x = b"Hello" # bytes print(type(x)) x = bytearray(5) # bytearray print(type(x)) x = memoryview(bytes(5)) # memoryview print(type(x)) print("++++++++++++++++++++++ Python Casting +++++++++++++++++++++++++") x = str("Hello World") # str print(type(x)) x = int(20) # int print(type(x)) x = float(20.5) # float print(type(x)) x = complex(1j) # complex print(type(x)) x = list(("apple", "banana", "cherry")) # list print(type(x)) x = tuple(("apple", "banana", "cherry")) # tuple print(type(x)) x = range(6) # range print(type(x)) x = dict(name="John", age=36) # dict print(type(x)) x = set(("apple", "banana", "cherry")) # set print(type(x)) x = frozenset(("apple", "banana", "cherry")) # frozenset print(type(x)) x = bool(5) # bool print(type(x)) x = bytes(5) # bytes print(type(x)) x = bytearray(5) # bytearray print(type(x)) x = memoryview(bytes(5)) # memoryview print(type(x))
# wordScrambler.py scrambles individual words in words.txt. Keeps periods at # the ends of words. from random import shuffle f = open('words.txt', 'r') l = f.read().split(' ') for x in range (0,len(l)): word1 = l[x] word = list(word1) shuffle(word) l[x] = ''.join(word) for x in range (0,len(l)): if '.' in l[x]: l[x] = l[x].replace('.','') l[x] += '.' print ' '.join(l)
# x = 1 # y = 5 # # if x<y: # # print('Yes') # if x: # print('Yes') # LOGIN # password = '123qwert' # username = 'owambe21' # input_username = input('Please enter username : ') # input_password = input('Please enter password : ') # if input_username == username: # print('Weldone, your username exists') # print('Checking password, hold on') # print() # if input_password == password: # print('Congrats you are signed in') # elif input("Recover password ? (y/n): ") == 'y': # print('Your password is', password) # elif input("Recover username ? (y/n): ") == 'y': # print('Your username is', username) # LARGER NUMBER # a = int(input('Please enter first number : ')) # b = int(input('Please enter second number : ')) # if a>b: # print('A is the larger number') # else: # print('B is the larger number') # CLASS WORK PASS OR FAIL # score = int(input("Please enter your score : ")) # grade = 'Passed' if score >= 50 else 'Failed' # print(grade) # salutation # gender = 'male' # offering = 'gift' # # txt = 'Hello there Mr/Mrs Adelabi, thank you for the gift/food you gave, it was so nice or sweet, I enjoy/ enjoyed eating/using it ' # txt = f"Hello there {'Mr' if gender == 'male' else 'Mrs'} Adelabi, thank you for the {offering} you gave it was so {'nice' if offering == 'gift' else 'sweet'}. I {'enjoy' if offering == 'gift' else 'enjoyed'} {'using' if offering == 'gift' else 'eating'} it." # print(txt) # CLASSWORK # text = "Hello (Mr) (Adams), we realized that you recently signed up for our weight loss program, we see that you are (130kgs) and (5ft) tall which gives you a BMI of (23) and by standards is (good) hence we recommend the (sustainance) package for you today, Buy now at (200)naira " # gender = 'female' # full_name = 'Adunni Olori' # weight = 85 # height = 1.6 # BMI = (weight)/(height**2) # text = f"Hello {'Mr' if gender == 'male' else 'Mrs'} {full_name}, we realized that you recently signed up for our weight loss program, we see that you are {weight} kgs and {height} ft tall which gives you a BMI of {BMI} and by standards is {'good' if BMI <= 25 else 'bad'} hence we recommend the {'sustainance package' if BMI <=25 else 'weight loss package'} for you today, Buy now at {'200 Naira' if BMI<=25 else '1000 Naira'} only." # print(text) # ASSIGNMENT # if character variable taxCode is ’T’, increase price by adding the taxRate per- # centage of price to it. # price = int(input('Please enter price : ')) # taxcode = input('Please enter your taxcode : ') # if taxcode == 'a': # print('Your total price is', price*1.1) # elif taxcode == 'b': # print('Your total price is', price*1.15) # elif taxcode == 'c': # print('Your total price is', price*1.2) # # If integer variable opCode has the value 1, read in double values for X and Y and # # calculate and print their sum. # x = 100 # y = 20 # opcode = 1 # if opcode == 1: # print(x+y) # # If integer variable currentNumber is odd, change its value so that it is now 3 # # times currentNumber plus 1, otherwise change its value so that it is now half of # # currentNumber (rounded down when currentNumber is odd). # currentnumber = int(input('Please enter number : ')) # odd_no_check = currentnumber%2 # if bool(odd_no_check): # print((currentnumber*3) + 1) # else: # print(currentnumber*0.5) # # Assign true to the boolean variable leapYear if the integer variable year is a # # leap year. (A leap year is a multiple of 4, and if it is a multiple of 100, it must # # also be a multiple of 400.) # yob = int(input('Please enter your year of birth : ')) # leap_year = yob%4 # if not bool (leap_year): # yob = 'true' # print(yob) # else: # yob = 'false' # print(yob) # # Assign a value to double variable cost depending on the value of integer variable # # distance as follows: # # Distance Cost # # 0 through 100 5.00 # # More than 100 but not more than 500 8.00 # # More than 500 but less than 1,000 10.00 # # 1,000 or more 12.00 # distance = int(input('Please input the distance : ')) # if distance <= 100: # print('Cost is 5.00') # elif distance <= 500 > 100 : # print('Cost is 8.00') # elif distance < 1000 > 500 : # print('Cost is 10.00') # elif distance > 1000: # print('Cost is 12.00') #CHECK UP name = input("Please enter your name : ") q1 = input("Feeling good? >y/n : ") if q1 == 'y': print("Bye") else: q2 = input("Do you have a headache? >y/n : ") if q2 == 'n': print('Drink water and mind your business') else: q3 = input('Stressed lately? >y/n : ') if q3 == 'y': print('Have some rest') else: q4 = input('Do you have fever? >y/n : ') if q4 == 'y': print('Call NCDC') else: print('Sorry cant help now') # LOGIN # password = '123qwert' # username = 'owambe21' # input_username = input('Please enter username : ') # input_password = input('Please enter password : ') # if input_username == username: # print('Weldone, your username exists') # print('Checking password, hold on') # print() # if input_password == password: # print('Congrats you are signed in') # elif input("Recover password ? (y/n): ") == 'y': # print('Your password is', password) # elif input("Recover username ? (y/n): ") == 'y': # print('Your username is', username) #CHECKUP 2 name = input("Please enter your name : ") if input("Feeling good? (y/n) : ") == 'y': print("Bye") elif input("Do you have a headache? (y/n) : ") == 'n': print('Drink water and mind your business') elif input('Stressed lately? (y/n) : ') == 'y': print('Have some rest') elif input('Do you have fever? (y/n) : ') == 'y': print('Call NCDC') else: print('Sorry cant help now')
# ##DECLARE FILENAME AND OPEN FILE FOR READING # file_name = "functions/words.txt" # file = open(file_name, "r") # ## READ FILE # data = file.read().split(',') # ##IMPORT THE RANDOM MODULE FOR RANDOM VALUE SELECTIONS # import random # ## SELECT A RANDOM CHOICE FROM THE LIST OF WORDS READ FROM THE FILE # selected_word = random.choice(data) # guessed_character = [] # print("I have selected a word") # ##CREATE A PLACE HOLDER TO HOLD SUCCESSFULLY GUESSED CHARACTERS # guessed_chars_list = [] # ##DECLARE THE MAXIMUM NUMBER OF TURNS POSSIBLE # turns = 5 # ##WHILE LOOP IS DECLARED WITH TURNS TO LIMIT NUMBER OF TURNS A USER HAS # while turns: # ## COLLECT GUESSED WORD FROM USER # guessed_char = input("Please guess a char : ") # ##CHECK IF CHARACTER GUESSED BY USER IS IN WORD THAT HAS BEEN SELECTED BY THE COMPUTER # if guessed_char in selected_word: # ##IF CHAR IS GUESSED RIGHT, THEN ADD THE CHAR TO THE LIST OF SUCCESSFULLY GUESSED CHARS # guessed_chars_list.append(guessed_char) # else: # ## IF CHAR IS GUESSED WRONG, THEN REDUCE NUMBER OF TURNS # turns -= 1 # for character in selected_word: # ## PRINT CHARACTER IF IT HAS BEEN GUESSED CORRECTLY # if character in guessed_chars_list: # print(character, end ="") # else: # ##PRINT DASH IF IT WAS GUESSED WRONG # print("_", end = "") # print() # ## PRINT NUMBER OF TURNS LEFT # print(f"You have {turns} tries left.!!!") # ## CHECK IF ALL CHARS OF THE SELECTED WORD HAVE BEEN GUESSED CORRECTLY AND IF SO END THE PROGRAM # if set(guessed_chars_list) == set(selected_word): # print('Congrats!!!') # break import random selected_word = "" guessed_chars_list = [] def get_random_text(): file_name = "functions/words.txt" file = open(file_name, "r") data = file.read().split(',') selected_word = random.choice(data) return selected_word def check_guess(guessed_char): global selected_word global guessed_chars_list if guessed_char in selected_word: guessed_chars_list.append(guessed_char) return True else: return False def display(): global selected_word global guessed_chars_list for character in selected_word: if character in guessed_chars_list: print(character, end ="") else: print("_", end = "") print() def check_if_guess_complete(): global guessed_chars_list global selected_word if set(guessed_chars_list) == set(selected_word): print('Congrats!!!') return True else: return False
''' This file is your implementation of a Blokus Playing Agent for the tournament. - Change ids to your own. - Choose a name for your AI player. - Don't forget to create your shapes file by the name specified. - Implement the two functions move() and setup(). ''' from GameAgent import GameAgent class BlokusCompetitionAgent (GameAgent): ids = ('300923000', '305625626') # insert your ID numbers here instead. # ids = '012345678' # In case you are a single submitter. agentName = 'AI_' + str(ids[0][-2:]) + '_' + str(ids[1][-2:]) # replace this name with any nice name you choose for your AI player shapesFile = 'TournamentShapes.txt' # Create the shapes file used in the tournament by this name # Do not change the name defined here def move(self, gameState): ''' This is the method called by the runner of this agent. It includes the code that decides the next move. @param gameState: The current game state. @return: The GameAction that the agent will execute in its next move. ''' raise NotImplementedError() def setup(self, player, gameState, timeLimit): ''' This is method is called once at the beginning of the game, and enables the agent to prepare for things to come. @param player: Your player. @param gameState: The initial game state. @param timeLimit: The time that will be allocated for a game. ''' raise NotImplementedError()
a = input() b = input() c = input() if ((a>=b) and (a>=c)): print(a) elif ((b>=a) and (b>=c)): print(b) elif ((c>=a) and (c>=b)): print(c)