text
stringlengths
37
1.41M
import sys # 한번만 정렬하는 알고리즘 def insertionSort1_Best(n, arr): target = arr[-1] idx = n-2 while (target < arr[idx]) and (idx >= 0): print(target, arr[idx], idx) arr[idx+1] = arr[idx] print(' '.join(map(str, arr))) idx -= 1 arr[idx+1] = target print(' '.join(map(str, arr))) #내건 전체 다 정렬하는 알고리즘 def insertionSort1(n, arr): for rvidx in range(len(arr)-1, 0, -1): stored = arr[rvidx] for cp_rvidx in range(rvidx-1, -1, -1): if stored >= arr[cp_rvidx]: if arr[cp_rvidx+1] == stored: break arr[cp_rvidx+1] = stored stored = arr[cp_rvidx] print(*arr) break else: arr[cp_rvidx+1] = arr[cp_rvidx] print(*arr) if arr[0] > stored : arr[0] = stored print(*arr) if __name__ == "__main__": n = 1 #arr = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 1] arr = [1,3,5,9,13,22,27,35,46,51,55,83,87,23] insertionSort1(n, arr)
#!/bin/python3 # https://www.hackerrank.com/challenges/jumping-on-the-clouds import math import os import random import re import sys # Complete the jumpingOnClouds function below. # 문제가 제대로 이해 안되어서 시간이 오래걸림. 인덱스 0과 1인 지점에 모두 0이 있으면 1부터 시작해도 되지만, # 마지막 스텝에 0이 있으면 무조건 밟고 지나가야함! 중요한 조건인데 왜 안적혀있지? def jumpingOnClouds(c): skipnext = False idx, jump = 0, 0 while idx < len(c): if c[idx] == 0: if idx != 0: jump += 1 if idx+2 < len(c): if c[idx+2] == 0: idx += 1 idx += 1 elif c[idx] == 1: idx += 1 continue return jump if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) c = list(map(int, input().rstrip().split())) result = jumpingOnClouds(c) fptr.write(str(result) + '\n') fptr.close()
def print_twod(arr): print('-------') for row in arr: print(row) print('-------') while True: col, row = map(int, input().split()) if col is 0 or row is 0: break soil = [] for _ in range(col): soil.append(list(input())) mark = [[0]*row for _ in range(col)] group = 0 for c in range(col): for r in range(row): if mark[c][r] is not 0: continue if soil[c][r] is '*': mark[c][r] = -1 else: group += 1 mark[c][r] = group for cadd in range(-1, 2): if c+cadd < 0 or c+cadd >= col: continue for radd in range(-1, 2): if r+radd < 0 or r+radd >= row: continue if soil[c+cadd][r+radd] is '@': if mark[c+cadd][r+radd] is 0: mark[c+cadd][r+radd] = group elif mark[c+cadd][r+radd] < group: mark[c][r] = mark[c+cadd][r+radd] group -= 1 else: mark[c+cadd][r+radd] = -1 #print_twod(mark) # print_twod(mark) # print_twod(soil) groups = [] for ls in mark: groups.append(max(ls)) print(max(groups) if max(groups) > 0 else 0)
''' Place green-stained images inside some directory and run with python 3 NOTE: ensure that there are only images of interest in selected directory. Other files will crash the program Then select output format when promted: 1. a CSV file can be generatre 2. the file and print out the data in the command line Input images can be in most formats but only PNG/JPG/TIF have been tested Program is used to detect areas of tissue that has been stained and unstained To determine ratio of stained to unstained images, two images must be used: 1. an image of only stained area (edit min/max in ImageJ to be the same ~40-50) 2. an image of all stained area (edit min/max in ImageJ to be 0) Currently WIP to eliminate the imageJ steps If stain is not green, edit FLATTEN and IS_BLACK functions Tom Ding 2020 | [email protected] ''' import cv2 import numpy as np from matplotlib import pyplot as plt from os import listdir import time import tkinter as tk from tkinter import filedialog import csv # Set a time counter for time taken for code to run begin = time.perf_counter() # Load image named NAME from user selected directory def load_img(name): img = cv2.imread("images/" + name) return cv2.blur(img,(3,3)) # Checks pixel A. only if value of A is less than N, the threshold value, A is considered to be black def is_black(a, n): if a[1] < n: return True return False # Takes image IMAGE, and some threshold THRESH (deafult to 110), and returns array: [number not black pixels, number black pixels] def count_black(image, thresh=110): not_black = 0 black = 0 for row in image: for pixel in row: if is_black(pixel, thresh): black += 1 else: not_black += 1 return [not_black, black] # Takes image IMAGE, a 2D array of triplets [R, G, B] and flattens to a 1D array where R and B are discarded and only G is kept. Order may not be kept def flatten(image): combined = [] for row in image: for pixel in row: combined += [pixel[1]] return combined # Helper function for FIND_PEAKS(A). Takes in flattened array A, low starting peak estimate MIN_VAL, high starting peak estimate MAX_VAL def find_peak_helper(a, min_val, max_val): left = [] right = [] for num in a: if max_val - num > num - min_val: left += [num] else: right += [num] new_min = sum(left) / len(left) new_max = sum(right) / len(right) if abs(new_min - min_val) <= 4 and abs(new_max - max_val) <= 4: return [new_min, new_max] else: return find_peak_helper(a, new_min, new_max) # Given flattened array A, find center points for A, which is assumed to be a dual-peak distribution def find_peaks(a): min_val = min(a) max_val = max(a) return find_peak_helper(a, min_val, max_val) ''' Combines all above helper functions to take an image named NAME from selected directory and executes the following functions: 1. load image into python and apply some gaussian blur 2. find low and high peaks of the dual-peak distribution of blurred image 3. find threshold between black and stained 4. count number of black and stained pixels in blurred image ''' def process_img(name): blur = load_img(name) peaks = find_peaks(flatten(blur)) thresh = (peaks[0] + peaks[1]) / 2 count = count_black(blur, thresh) return count[0] # Asks user where their images are located. User must select a single directory def ask_path(): root = tk.Tk() root.withdraw() return filedialog.askdirectory(title="Select image directory") # Asks user for where to save CSV file. Input is where to start looking for destination directory def ask_output_dest(init_path='/'): root2 = tk.Tk() root2.withdraw() return filedialog.asksaveasfilename(initialdir = init_path,title = "Select output file/destination",filetypes = (("csv files","*.csv"),("all files","*.*"))) # Makes sure that the name of the output file is in CSV format, creates the file, opens it, and sets header. Takes DEST, file path with file as input def create_output(dest): if dest[-4:] != ".csv": dest = dest + ".csv" f = open(dest, "w") f.write("image name,pixels stained\n") return f # Helper function to write processed data (image name IMAGE_NAME and pixels stained NUM_PIXELS) into CSV file FILE def write_to_output(file, image_name, num_pixels): file.write(str(image_name) + "," + str(num_pixels) + "\n") ''' Function that runs all the helper functions in the correct order: 1. asks user for directory with images 2. processes all images in directory and saves in dictionary RESULT 3. asks user if output should be command line print or CSV file 4a. if CSV selected, asks for save file, creates file, writes to it 4b. if CSV not selected, prints image and number pixels stained pairs 5. ouputs the number of files printed/written to CSV file ''' def initialize_all(): counter = 0 image_directory = ask_path() result = {} for name in listdir(image_directory): result[name] = process_img(name) while True: to_csv = input("Would you like to save data to csv file (spreadsheet)? [Y/N]") if to_csv not in ["N", "n", "Y", "y"]: print ("Input not accepted. Please enter either 'Y' or 'N'") else: break if to_csv == "Y" or "y": dest_file = create_output(ask_output_dest(image_directory)) for key in result: write_to_output(dest_file, key, result[key]) counter += 1 elif to_csv == "N" or "n": for key in result: print ("For image " + str(key) + " stained area (pixels) is " + str(result[key])) counter += 1 return counter # Prints length of time program took to run and number of files processed counter = initialize_all() print ("Program took " + str(time.perf_counter() - begin) + " seconds to complete successfully") print ("Processing completed on " + str(counter) + "files") ''' ------------------------------------------------------------------------------ PLEASE IGNORE EVERYTHING BELOW - THEY ARE EARLIER TESTS AND OTHER TEST CASES ------------------------------------------------------------------------------ peaks = find_peaks(flatten(blur)) thresh = (peaks[0] + peaks[1]) / 2 print (thresh) count2 = count_black(blur, thresh) count = count_black(blur) print(count) print(count2) flat = flatten(blur) d = {} for i in flat: d.setdefault(i, 0) d[i] += 1 print (d) flat = flatten(cv2.imread("images/image_test.tif")) flat2 = [] for i in flat: if i>120: flat2 += [i] plt.hist(flat, bins = 255) plt.show() # Runs program and prints out the program return values # image_directory = ask_path() # for name in listdir(image_directory): # print ("For image " + name + " stained area (pixels) is " + str(process_img(name))) # counter += 1 plt.subplot(121),plt.imshow(img),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(blur),plt.title('Blurred') plt.xticks([]), plt.yticks([]) plt.show() from PIL import Image, ImageEnhance, ImageFilter img = Image.open("images/one_p.jpg") img.show() def adjust_contrast_brightness(image, contrast, brightness): contrast_enhancer = ImageEnhance.Contrast(image) img2 = contrast_enhancer.enhance(contrast) brightness_enhancer = ImageEnhance.Brightness(img2) img3 = brightness_enhancer.enhance(brightness) return img3 def count_pixel(image): print("not implemented") '''
#!/usr/bin/env python # -*- coding: utf-8 -*- # # game_functions.py # import sys import pygame from bullet import Bullet def check_keydown_events(event, ai_settings, screen, ship, bullets): """响应按键""" if event.key == pygame.K_UP: ship.moving_up = True elif event.key == pygame.K_DOWN: ship.moving_down = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, screen, ship, bullets) def fire_bullet(ai_settings, screen, ship, bullets): """如果还没有达到限制,就发射一颗子弹""" # 创建新子弹并将其加入到编组bullets中 if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def check_keyup_events(event, ship): """响应松开""" if event.key == pygame.K_UP: ship.moving_up = False elif event.key == pygame.K_DOWN: ship.moving_down = False def check_events(ai_settings, screen, ship, bullets): """响应按键和鼠标事件""" # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event,ai_settings,screen,ship,bullets) elif event.type == pygame.KEYUP: check_keyup_events(event, ship) def update_screen(ai_settings, screen, ship, bullets): """更新屏幕上的图像,并切换到新屏幕""" # 每次循环时都重绘屏幕 screen.fill(ai_settings.bg_color) # 先填充背景色后绘制其他元素 # 在飞船和外星人后面重绘所有子弹 for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() # 让最近绘制的屏幕可见 pygame.display.flip() def update_bullets(ai_settings, bullets): """更新子弹的位置,并删除已消失的子弹""" # 更新子弹的位置 bullets.update() # 对编组调用update(),自动对每个精灵调用 # 删除已消失的子弹 for bullet in bullets.copy(): ### for遍历时不应修改遍历对象!!故遍历副本 if bullet.rect.left >= ai_settings.screen_width: bullets.remove(bullet) #print(len(bullets)) # 验证子弹被正确删除,运行不应保留,写入终端拖慢速度
#!/usr/bin/env python # -*- coding: utf-8 -*- # # homework2_favnumber.py def get_stored_favnum(): """如果存储了喜欢的数字,就获取它""" filename = 'favnumber.txt' try: with open(filename) as f_obj: favnum = json.load(f_obj) except FileNotFoundError: return None else: return favnum def get_new_favnum(): """提示输入喜欢的数字""" favnum = input("Pleas input your favorite number. ") filename = 'favnumber.txt' with open(filename, 'w') as f_obj: json.dump(favnum, f_obj) return favnum def show_favnum(): """打印喜欢的数字""" favnum = get_stored_favnum() if favnum: print("I know your favorite number! It's " + str(favnum) +"!") else: favnum = get_new_favnum() print("Your favorite number is " + str(favnum) +". I'll remember it.") if __name__ == '__main__': import json show_favnum()
import math def func(x): return pow(x,2)-2 a = float(input('input a : ')) b = float(input('input b : ')) e = pow(10,-7) c = 0 count = 0 if (func(a)*func(b) < 0) : while(abs(func(c))) >= e: c = (a+b)/2 if(func(a)*func(c) > 0): a = c else : b = c count = count+1 print(count , c)
''' def d(n): array = [] i = 1 while i < n: if n % i == 0: # print i array.append(i) i += 1 return array def isPrime(n): i = 2 while (i < round(n /2)): if (n % i == 0): return False i += 1 return True exceed = [] i = 2 while i <= 28123: if isPrime(i): i += 1 continue if sum(d(i)) > i: exceed.append(i) i += 1 print ','.join([str(x) for x in exceed]) ''' readLine = open("exceed.txt").readline() exceeds = [int(x) for x in readLine.split(',')] # print exceeds sumArray = {} for a in exceeds: for b in exceeds: sumArray[a+ b] = 1 i = 1 s = 0 while i <= 28123: if i not in sumArray: s += i i += 1 print s
from tkinter import * root=Tk() wenben=Text(root) wenben.insert(INSERT,"woshiyiduanwenben hhhhhh") wenben.insert(INSERT,"_______________________") wenben.insert(END,"BYEBYE~") wenben.insert(INSERT,"_______________________") wenben.pack() root.mainloop()
#!/usr/bin/python s="snoopy" print "input is:" + s x = len(s); print "String length:" + str(x) for j in range(x): substr = s[:j+1] print substr
import xlsxwriter workbook = xlsxwriter.Workbook('Example3.xlsx') worksheet = workbook.add_worksheet("My sheet") for row in range(1,3): print("Enter Name, USN, marks in 3 subjects of student "+str(row)) for col in range(5): ele=input() worksheet.write(row,col,ele)
import requests import json from decimal import * def get_exchange_rate(date): """ gets the GBP/ILS exchange rate for a specified date """ response = requests.get( 'https://api.exchangeratesapi.io/' + date + '?symbols=GBP,ILS') binary = response.content output = json.loads(str(binary, 'utf-8')) GBP, ILS = (output['rates']['GBP']), (output['rates']['ILS']) return Decimal(GBP / ILS) print(get_exchange_rate('2019-01-22'))
import numpy as np import math vetor = [] for i in range (10): if (i % 2 == 0 ): valor = 3**i+7*(math.factorial(i)) else: valor = 2**i+4*(math.log(i)) vetor.append(valor) print("A posição do maior elemento é",np.argmax(vetor)) print("A média dos elementos é",np.mean(vetor))
"""The Rules and Setup for Chess.""" # Starting board for new game starting_board = [ ["R", "N", "B", "Q", "K", "B", "N", "R"], ["P", "P", "P", "P", "P", "P", "P", "P"], ["", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", ""], ["", "", "", "", "", "", "", ""], ["p", "p", "p", "p", "p", "p", "p", "p"], ["r", "n", "b", "q", "k", "b", "n", "r"], ] # Group pieces by colour white_pieces = ["P", "R", "N", "B", "Q", "K"] black_pieces = ["p", "r", "n", "b", "q", "k"] # Piece dictionary piece_dictionary = { "P": "Pawn", "R": "Rook", "N": "Knight", "B": "Bishop", "Q": "Queen", "K": "King", "p": "Pawn", "r": "Rook", "n": "Knight", "b": "Bishop", "q": "Queen", "k": "King", }
money = int(input()) coin_values = [500, 100, 50, 10] print('money to exchange: %d won' % money) for val in coin_values: print('coin of %d won: %d' % (val, money // val)) money %= val print('change left: %d won' % money)
class point: def __init__(self,stroka="0,0"): self.x = float(stroka[:stroka.index(",")]) self.y = float(stroka[stroka.index(",")+1:]) def __add__(self,other): return(str(self.x + other.x) + ','+str(self.y + other.y)) def __str__(self): return('(' + str(self.x) + ',' + str(self.y)+')') def rast(self): return float((self.x**2 + self.y**2)**0.5) maximum = None for i in range(int(input())): A = point(input()) if maximum == None or maximum.rast() < A.rast(): maximum = A print(maximum)
from singleLinkedList import Node, LinkedList def mergedLists(firstlist, secondlist, mergedList): currentFirst = firstlist.head currentSecond = secondlist.head while 1: if currentFirst is None: mergedList.insertLast(currentSecond) break if currentSecond is None: mergedList.insertLast(currentFirst) break if currentFirst.data < currentSecond.data: currentFirstNext = currentFirst.next currentFirst.next = None # mergeslist = 1->None mergedList.insertLast(currentFirst) currentFirst = currentFirstNext else: currentSecondNext = currentSecond.next currentSecond.next = None mergedList.insertLast(currentSecond) currentSecond = currentSecondNext #creating first list a = Node(1) b = Node(3) c = Node(4) firstlist = LinkedList() firstlist.insertLast(a) firstlist.insertLast(b) firstlist.insertLast(c) #creating second list d = Node(2) e = Node(5) f = Node(7) secondlist = LinkedList() secondlist.insertLast(d) secondlist.insertLast(e) secondlist.insertLast(f) print("Printing first list") firstlist.PrintList() print("Printing second list") secondlist.PrintList() mergedList = LinkedList() mergedLists(firstlist, secondlist, mergedList) print("Printing merged list") mergedList.PrintList()
arr = [1,2,3,1,3] def findDuplicate(arr): mydict = {} for i in range(len(arr)): if(arr[i] not in mydict): mydict[arr[i]] = 1 else: mydict[arr[i]] = mydict[arr[i]] + 1 #else saglanirsa duplicate vardir. #print(mydict) if(mydict[arr[i]] > 1): print("Duplicate olan sayi", arr[i]) findDuplicate(arr)
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self,new_data): new_data = Node(new_data) if self.head == None: self.head = new_data return else: current = self.head while current.next is not None: current = current.next current.next = new_data def reverse(self): if self.head == None: return "Empyt list" else: prev = None current = self.head while current is not None: #until the end of the list nxt = current.next current.next = prev prev = current current = nxt self.head=prev def printList(self): if self.head == None: return "Empyt list" else: current = self.head while current is not None: print(current.data) current = current.next mylist = LinkedList() print("Normal list: ") mylist.append("A") mylist.append("B") mylist.append("C") mylist.append("D") mylist.printList() print("Reversed List:") mylist.reverse() mylist.printList()
"""A palindrome is a word or a sequence that is the same from the front as from the back.""" class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def append(self,new_data): new_data = Node(new_data) if self.head == None: self.head = new_data return else: current = self.head while current.next is not None: current = current.next current.next = new_data def isPalindrome(self): stack = [] current = self.head while current: stack.append(current.data) current = current.next current = self.head while current: node = stack.pop() if current.data != node: return False current = current.next return True def printList(self): if self.head == None: return "Empyt list" else: current = self.head while current is not None: print(current.data) current = current.next mylist = LinkedList() mylist.append("A") mylist.append("B") mylist.append("C") mylist.append("D") print(mylist.isPalindrome()) mylist_two = LinkedList() mylist_two.append("R") mylist_two.append("A") mylist_two.append("D") mylist_two.append("A") mylist_two.append("R") print("For second list:") print(mylist_two.isPalindrome())
class Animal(): # Parent Class Attribute def __init__(self): print("insde the constructor of Animal") def show( self ): print('Hello From Animal') class Dog(Animal): # CLASS OBJECT ATTRIBUTE species = 'mammal' def __init__( self, breed, name ): self.breed = breed self.name = name self.species = 'hello' def sayHello( self ): self.show() print('hello master: ' + self.name + ' here' + self.species) mydog = Dog( "Lab", "Sammy" ) print( mydog.breed ) print( mydog.sayHello() )
checkA = [1,2,3,4] listA = [1,2,3,4,33,4,4,55] #this function checks wether the listA consists the number sequence in list checkA and accordingly return the boolean result def checkPresent( check ): if( len(check) <= len(listA) ): for i in range(0, len(listA) - len(check)+1 ): if( check == listA[ i: i+len(check) ] ): return True return False print(checkPresent(checkA))
#Casandra Villagran #2/20/2020 #Use random.choice to select a day of the week from a list and print that day. import random DaysList= ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"] print ("Random day of the week: ", random.choice(DaysList))
students = {"Alice":["ID0001",26,"A"], "Bob":["ID0002",27,"B"], "Clair":["ID0003",17, "C"], "Dan":["ID0004",21,"D"], "Emma":["ID0005",22,"E"], } print(students) print(students["Clair"]) print(students["Clair"][0]) print(students["Dan"][1:]) #in order to make the dictionary better students = { "Alice":{"ID":"ID0001","age":26,"grade":"A"}, "Bob":{"ID":"ID0002","age":25,"grade":"B"}, "Clair":{"ID":"ID0003","age":29,"grade":"C"}, "Dan":{"ID":"ID0004","age":24,"grade":"D"}, "Emma":{"ID":"ID0005","age":16,"grade":"E"}, } print(students["Dan"]["age"]) print(students["Emma"]["ID"],students["Emma"]["grade"])
# open function file1 = open("C:/Nima/Data_science course/Course 04/Example1.txt","w") print(file1.name) print(file1.mode) file1.close() #with open is better to open the file because it automatically closes the file with open("Example1.txt") as file1: file_stuff = file1.read() print(file_stuff) print(file1.closed) print(file_stuff) # store all the lines in the list with open("Example1.txt") as file1: file_stuff = file1.readlines() print(file_stuff) # Read first four characters with open("Example1.txt", "r") as file1: print(file1.read(4)) # Read certain amount of characters with open("example1.txt", "r") as file1: print(file1.read(4)) print(file1.read(4)) print(file1.read(7)) print(file1.read(15)) #read only first line with open("Example1.txt") as file1: file_stuff=file1.readline() print(file_stuff) # we can use that function twice to read two lines seperately with open("Example1.txt") as file1: file_stuff=file1.readline() print(file_stuff) file_stuff=file1.readline() print(file_stuff) # or we can use the loop with open("Example1.txt") as file1: for line in file1: print(line) #we can specify the number of caracters we would like to read from string as an argument print("hello") with open("Example1.txt","r") as file1: file_stuff=file1.readline(16) print(file_stuff) file_stuff=file1.readline(9) print(file_stuff) file_stuff=file1.readline(5) print(file_stuff) with open("Example1.txt", "r") as File1: file_stuff = File1.readline() print(file_stuff)
class Account: def __init__(self, name, balance, min_balance): self.name = name self.balance = balance self.min_balance = min_balance def deposit(self, amount): self.balance = self.balance + amount def withdraw(self, amount): if self.balance - amount >= self.min_balance: self.balance = self.balance - amount else: print("Sorry there is not enough money in your account") def statement(self): print("Account balance: £{}".format(self.balance)) class Curent(Account): def __init__(self, name, balance): super().__init__(name, balance, min_balance=-1000) def __str__(self): return "{}'s Current Account: Balance: £{}".format(self.name, self.balance) class Saving(Account): def __init__(self, name, balance): super().__init__(name, balance, min_balance=0) def __str__(self): return "{}'s Saving Account: Balance: £{}".format(self.name, self.balance) x = Curent("Nima", 500) print(x.name) print(x.balance) x.deposit(300) x.statement() x.withdraw(700) x.statement() x.deposit(1000) print(x.balance) x.statement() print(x) y = Saving("Pardis", 86000) print(y.name) y.deposit(14000) y.statement() print(y)
#Creating a SET set1 = {"A", "AB", "A"} #There are no duplicate values in a set print(set1) #Change a list to a set list = ["Nima", "Afshar", "Nima", 1984] set = set(list) print(set) #Add item to the set set1.add("C") print(set1) #remove an item from the set set1.remove("C") print(set1) #check if the item is in the set print("AA" in set1) print("AB" in set1) #Find the intersectin of two sets Album1 = {"AC/DC", "Thriller", "Back in Black"} Album2 = {"The dark side of the moon", "Thriller", "Back in Black"} Album3 = Album1 & Album2 print(Album3) #combine all the elements of two sets Album4 = Album1.union(Album2) print("Album4 is:", Album4) #to check if a set is a subset of other set print(Album3.issubset(Album4)) Album5 = Album4.difference(Album1) print(Album5) Album6 = Album1.intersection(Album4) print(Album6) print("Thriller" in Album2) print(Album5 in Album1)
import pandas as pd csv_path = 'C:/Users/nafs080/work/codes/python_packages/python_tutorial/Python for Data Science/file1.csv' df = pd.read_csv(csv_path) df.head() songs = {"Album":["Thriller","Back in Black"],"Released":["1982","1980"]} songs_frame = pd.DataFrame(songs) print(songs_frame) x = songs_frame[['Released']] print(x) #loc is primarily label based; when two arguments are used, you use column headers and row indexes to select the data you want. loc can also take an integer as a row or column number. print(songs_frame.loc[0,"Album"]) #iloc is integer-based. You use column numbers and row numbers to get rows or columns at particular positions in the data frame. print(songs_frame.iloc[0,0]) #By default, ix looks for a label. If ix doesn't find a label, it will use an integer. This means you can select data by using either column numbers and row numbers or column headers and row names using ix. #make slice with loc and iloc slice = songs_frame.iloc[0:2,0:2] print(slice) slice = songs_frame.loc[0:2,'Album':'Released'] print(slice) csv_path = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%204/Datasets/TopSellingAlbums.csv' df = pd.read_csv(csv_path) # Print first five rows of the dataframe print(df.head()) # Access to the column "Length" x = df[['Length']] print(x) # Get the column as a series x = df['Length'] print(x) # Get the column as a dataframe x = type(df[['Artist']]) print(x) # # Access to multiple columns y = df[['Artist','Length','Genre']] print(y)
#local scope can only be seen in an specific local scope but global scope can be see anywhere in the code, only function can make a local scope # a is now defined in a global scope but if we move that into the function f1() then it is not going to work for f(2) a = 100 def f1(): print(a) def f2(): print(a) f1() f2() def f1(): a = 50 print(a) def f2(): a = 150 print(a) f1() f2() def word(): new_word = input("Write down a word please").strip().capitalize() print("The new word is {}".format(new_word)) word() #When the function can not find the variable inside the local scope it is going to look for that variable outside the scope
my_int = 4 my_float = 2.34 print(my_float) print(type(my_int)) result = my_int + my_float print(result) result = my_int - my_float print(result) result = my_int * my_float print(result) result = my_int / my_float print(result) result = my_int // my_float print(result) #exponents and powers result = 3 ** 2 print(result) #modulus operator print(3%2) print(10%2) #order of operation print(3*2+4+(3-2)-1/2) #shortcuts my_int = 4 my_int = my_int + 1 print(my_int) #or my_int = 4 my_int += 1 print(my_int) my_int = 4 my_int = my_int * 1 print(my_int) #or my_int = 4 my_int *= 1 print(my_int) #Absolute and round values print(abs(-12)) print(round(3.24)) print(round(3.7)) print(round(3.7365, 2)) #comparison operators print(2==3) print(3<4) print(2!=3) print(2>=3) #type casting my_string_num = '100' my_string_num2 = '200' sum = my_string_num + my_string_num2 print(sum) sum = int(my_string_num) + int(my_string_num2) print(sum)
import string import operator class Question1_Solver: def __init__(self, cpt): self.cpt = cpt; return; ##################################### # ADD YOUR CODE HERE # Pr(x|y) = self.cpt.conditional_prob(x, y); # A word begins with "`" and ends with "`". # For example, the probability of word "ab": # Pr("ab") = \ # self.cpt.conditional_prob("a", "`") * \ # self.cpt.conditional_prob("b", "a") * \ # self.cpt.conditional_prob("`", "b"); # query example: # query: "ques_ion"; # return "t"; def solve(self, query): prob = {} pre = "`" query += "`" for cur in query: if cur == "_": for c in string.ascii_lowercase: prob[c] = self.cpt.conditional_prob(c, pre) if pre == "_": for c in prob.keys(): prob[c] *= self.cpt.conditional_prob(cur, c) break pre = cur return max(prob.iteritems(), key = operator.itemgetter(1))[0]
import sys class Question3_Solver: def __init__(self): return; # Add your code here. # Return the centroids of clusters. # You must use [(30, 30), (150, 30), (90, 130)] as initial centroids def solve(self, points): centroids=[(30, 30), (150, 30), (90, 130)] # centroids = [(30, 60), (150, 60), (90, 130)] old_centroids=[(0,0),(0,0),(0,0)] while not is_end(centroids,old_centroids): #for i in range(1, 100): old_centroids=centroids centroids=update(points,centroids) return centroids def is_end(old,new): sum=0 L=len(old) for i in range(L): sum=sum+caldistance(old[i],new[i]) if sum==0: return True return False ''' return set(old)==set(new) ''' def update(points,centroids): dataclustered=[[],[],[]] for i in range(len(points)): tempdis=float("inf") templabel=-1 for j in range(len(centroids)): dis=caldistance(points[i],centroids[j]) if dis<tempdis: tempdis=dis templabel=j dataclustered[templabel].append(points[i]) for p in range(len(centroids)): centroids[p]=calcenter(dataclustered[p]) return centroids def caldistance(a,b): d=((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5 return d def calcenter(data): ''' l=len(data)*1.0 x=1 y=1 for item in data: x=x*item[0] y=y*item[1] x=x**(1.0/l) y=y**(1.0/l) return (x,y) ''' l=len(data) x=0 y=0 for item in data: x=x+item[0] y=y+item[1] x=x/l y=y/l return (x,y)
################################################################################ # File: hw1_written2.py # HW 1, CS5785 # Neil Lakin # # Purpose: Draw some plots for homework 1, written exercise 2. # ################################################################################ import numpy as np from matplotlib import pyplot as plt from sklearn import linear_model as lm def main(): fig = plt.figure() ax = fig.add_subplot(1,1,1) # Get set of points between 0 and 100 x = np.arange(0,50,.5) # Make an 'error' vector of random values between -3 and 3 r = np.random.uniform(-3,3,x.shape[0]) # Make y values by calculating y = 2x y = 2*x + r # replace some point with an outlier y[5]=100 #plot them ax.scatter(x,y, color = 'black', s = 4) # draw least squares regression lsr = lm.LinearRegression() lsr.fit(x.reshape(x.shape[0],1), y) ax.plot(x, lsr.predict(x.reshape(x.shape[0],1)), color = 'blue', linewidth = 3) fig.suptitle('Nearly-linear data with one outlier') fig.show() figb = plt.figure() axb = figb.add_subplot(1,2,1) axb2 = figb.add_subplot(1,2,2) xb = np.array([1, 1, 2, 3, 3]) yb = np.array([2, 0, 1, 2, 0]) axb.scatter(xb, yb, color = 'black', s = 5) axb2.scatter(xb, yb, color = 'black', s = 5) axb2.plot([1,3], [0,2], color = 'red', linewidth = 1) axb2.plot([1,3], [2,0], color = 'red', linewidth = 1) lsrb = lm.LinearRegression() lsrb.fit(xb.reshape(5,1), yb) axb2.plot(xb, lsrb.predict(xb.reshape(5,1)), color = 'blue', linewidth = 1) figb.suptitle('Single L2 solution, multiple L1 solutions') figb.show() if __name__ == '__main__': main()
def Longest_Repeated_Subsequence(n,string): LR=[[0 for i in range(n+1)] for j in range(n+1)] for i in range(1,n+1): for j in range(1,n+1): if string[i-1]==string[j-1] and i!=j: LR[i][j]=1+LR[i-1][j-1] else: LR[i][j]=max(LR[i][j-1],LR[i-1][j]) i,j,ans=n,n,"" while i>0 and j>0: if LR[i][j]==LR[i-1][j-1]+1: ans+=string[i-1] i-=1 j-=1 elif LR[i][j]==LR[i-1][j]: i-=1 else: j-=1 return "".join(ans[::-1]) n=int(input()) string=input() print(Longest_Repeated_Subsequence(n,string))
# p1.py - find the maximum clique in a graph # by K. Brett Mulligan # 27 Aug 2014 # CSU CS440 # Dr. Asa Ben-Hur ############################################## import itertools, copy, re DO_TESTING = False DO_VERBOSE_PARSING = False prohibited_chars = ['{', '}', '/'] class Graph: name = "" # id of graph edges = [] # list of edges amatrix = [] # adjacency matrix nodes = [] # list of node ids cliques = [] # list of Graph objects which are cliques for this graph def __init__(self, fn): if (fn != ''): self.edges, self.name = self.read_graph(fn) self.nodes = list(self.get_nodes()) self.amatrix = [ [0 for i in range(self.num_nodes())] for j in range(self.num_nodes()) ] self.init_edges() else: self.name = '' def read_graph (self, filename): name = '' edges = [] gf = open(filename, 'r') if gf == None: print "Error: Could not open file." else: title = gf.readline() # read title if title != "": name = title.strip("\n {") for line in gf: # read edges if line != "": gData = line if DO_VERBOSE_PARSING: print "\nRaw : ", gData.rstrip('\n') if gData[0:2] == '/*': gData = '' if DO_VERBOSE_PARSING: print "There's a comment only line!!!" gData = gData.split(";")[0] # remove everything after ";") if DO_VERBOSE_PARSING: print "All after ; removed : ", gData tokens = gData.split("--") # split on -- if DO_VERBOSE_PARSING: print "Split along '--'' : ", tokens clean_tokens = [t.strip() for t in tokens] # remove whitespace if DO_VERBOSE_PARSING: print "Whitespace removed : ", clean_tokens edge = [x for x in clean_tokens if x if x not in prohibited_chars] # remove prohibited chars if DO_VERBOSE_PARSING: print "Non-nodes removed : ", edge if edge and edge not in edges: edges.append(edge) gf.close() return edges, name def get_name(self): return self.name def get_matrix(self): return list(self.amatrix) def get_edges(self): return list(self.edges) def print_edges(self): for edge in self.edges: self.print_edge(edge) def print_edge (self, edge): print '--'.join(edge) def num_nodes(self): return len(self.nodes) def get_size(self): return self.num_nodes() def get_nodes(self): nodes = [] for edge in self.edges: for node in edge: if (node not in nodes): nodes.append(node) return nodes def get_node_index(self, node_id): return self.nodes.index(node_id) def get_node_id(self, node_index): return self.nodes[node_index] def put_edge_in_matrix (self, edge): if (len(edge) > 1): self.amatrix[self.get_node_index(edge[0])][self.get_node_index(edge[1])] = 1 # do edge self.amatrix[self.get_node_index(edge[1])][self.get_node_index(edge[0])] = 1 # do reciprocal self.amatrix[self.get_node_index(edge[0])][self.get_node_index(edge[0])] = 1 # do first node self.amatrix[self.get_node_index(edge[1])][self.get_node_index(edge[1])] = 1 # do second node else: self.amatrix[self.get_node_index(edge[0])][self.get_node_index(edge[0])] = 1 def init_edges(self): for edge in self.edges: # add each edge to the matrix self.put_edge_in_matrix(edge) # for node in self.nodes: # add all nodes that didn't have an explicit edge for themselves # if list(node) not in self.edges: # self.edges.append(list(node)) def remove_node(self, index): to_remove = self.get_node_id(index) # get id first self.remove_edges_with_node(to_remove) # remove edges self.nodes.remove(to_remove) # remove node if (len(self.amatrix) > 1): # adjust matrix for y in range(len(self.amatrix)): self.amatrix[y].pop(index) # remove index in each row self.amatrix.pop(index) # remove index row return def remove_edges_with_node(self, node): to_remove = [] for edge in self.edges: if node in edge: to_remove.append(edge) for edge in to_remove: self.edges.remove(edge) return def print_matrix(self): print ' ' + ' '.join(self.nodes) for x in range(self.get_size()): print self.nodes[x], self.amatrix[x] def is_clique(self): clique = True for y in self.get_matrix(): for x in y: if (x == 0): clique = clique and False return clique def add_clique(self, cg): if cg not in self.cliques: self.cliques.append(cg) return def get_cliques(self): return self.cliques # given 2 node indices, returns true if they are connected def nodes_connected(self, n1, n2): adjacent = False if (self.amatrix[n1][n2] == 1): adjacent = True else: pass return adjacent # given 2 node id's, returns true if they are connected def nodes_connected_id(self, id1, id2): return self.nodes_connected(self.get_node_index(id1), self.get_node_index(id2)) # given a node and a list of nodes, return true if that node is connected to all nodes in list def node_connected_to_list(self, node_a, nodes_list): connected = True for node in nodes_list: if self.nodes_connected_id(node_a, node): connected = connected and True else: connected = connected and False return connected # returns combination object of all node combinations with 1 node removed def node_combinations(self): return itertools.combinations(self.get_nodes(), self.get_size()-1) def generate_all_node_combinations(self): all_combinations = [] for x in range(1, self.get_size()+1): combos_length_x = itertools.combinations(self.get_nodes(), x) all_combinations.extend(combos_length_x) return all_combinations def find_cliques(self): cliques = [] all_combos = self.generate_all_node_combinations() for combo in all_combos: if (self.is_combo_clique(combo)) and (combo not in cliques): cliques.append(combo) self.cliques = cliques return cliques def is_combo_clique(self, combo): connected = False if (len(combo) == 1): connected = True elif (len(combo) == 2): connected = self.nodes_connected_id(combo[0], combo[1]) else: connected = self.node_connected_to_list(combo[0], combo[:]) and self.is_combo_clique(combo[1:]) return connected def get_max_clique(self): self.find_cliques() max_cliq = '' max_size = 0 sizes = [len(cliq) for cliq in self.get_cliques()] for cliq in self.get_cliques(): if (len(cliq) > max_size): max_size = len(cliq) max_cliq = cliq # print "Cliques: ", self.get_cliques() # print "Clique sizes: ", sizes # print "Maximum cliques size was ", max_size return max_cliq ################ END CLASS GRAPH ################################ # GRAPH CREATORS def graph_from_edges(new_edges): g = Graph('') g.edges = list(new_edges) g.nodes = list(self.get_nodes()) g.amatrix = [ [0 for i in range(self.num_nodes())] for j in range(self.num_nodes()) ] g.init_edges() return g def graph_from_matrix(new_matrix): g = Graph('') g.name = "_dyn" g.amatrix = list(new_matrix) g.nodes = list(range(len(g.amatrix))) return g def graph_from_graph(parent): g = Graph('') g.name = parent.name g.amatrix = list(parent.get_matrix()) g.nodes = list(range(len(g.amatrix))) g.edges = list(parent.get_edges()) return g def maximum_clique(g): # standalone function that returns max clique of graph return len(g.get_max_clique()) def do_graph(g): print "---------------\\\\" print g.get_name() g.print_edges() print "Nodes: " + str(g.num_nodes()) print "Clique: " + str(g.is_clique()) g.print_matrix() print "---------------//" ################ TESTING ############################### test_files = [ "graph.gv", "graph0.gv", "graph1.gv", "graph2.gv", "graph3.gv", "graph4.gv", "graph5.gv", "graphex.gv", "file3.gv", "file4.dot", "file5.dot", "file6.dot" ] if DO_TESTING: for test in test_files: print test , " -> ", maximum_clique(Graph(test))
from Node import Node class Edge: def __init__(self, n1: Node, n2: Node, w: int): """Initialize the edge with the two nodes and the weight""" self.node1 = n1 self.node2 = n2 self.weight = w def get_weight(self): return self.weight def get_nodes(self): return self.node1, self.node2
class Animals: fullness = 'hungry' location = 'at home' cleanliness = 'dirty' voice = '' def __init__(self, name, weight): self.name = name self.weight = weight def feed(self): self.fullness = 'full' return print('onomnomnom') def walking(self): self.location = 'outside' def wash(self): self.cleanliness = 'clean' def speak(self): return print(self.voice) class Birds(Animals): egg_basket = 'full' def get_egg(self): self.egg_basket = 'empty' return print('you got eggs') class Chiken(Birds): animal_type = 'Курица' voice = 'ko-ko-ko' class Duck(Birds): animal_type = 'Утка' voice = 'krya-krya-krya' class Goose(Birds): animal_type = 'Гусь' voice = 'ga-ga-ga' class Hornet_cattle(Animals): milk = 'full of milk' def get_milk(self): self.milk = 'you got milk' return print('milk is collected') class Cow(Hornet_cattle): animal_type = 'Корова' voice = 'moo-moo' class Goat(Hornet_cattle): animal_type = 'Коза' voice = 'be-be-be' class Ship(Animals): animal_type = 'Барашек' wool = 'a lot' voice = 'meeeeeh' def cut(self): self.wool = 'you got a wool' return print('wool is collected') goose_0 = Goose('Серый', 4) goose_1 = Goose('Белый', 3.5) cow = Cow('Манька', 450) ship_0 = Ship('Барашек', 70) ship_1 = Ship('Кудрявый', 90) chiken_0 = Chiken('Ко-Ко', 0.8) chiken_1 = Chiken('Кукареку', 1) goat_0 = Goat('Рога', 50) goat_1 = Goat('Копыта', 45) duck = Duck('Кряква', 1) animal_list = [goose_0, goose_1, ship_0, ship_1, cow, chiken_0, chiken_1, goat_0, goat_1, duck] list_for_weight = [] list_for_name = [] total_weight = 0 for animal in animal_list: total_weight = total_weight + animal.weight list_for_name.append(animal.animal_type) list_for_weight.append(animal.weight) list1 = list(zip(list_for_weight, list_for_name)) a = (max(list1)) print(f' Самое тяжелое животное на ферме - {a[1]} ') print(f' Общий вес всех животных на ферме составляет {total_weight} кг')
from typing import Iterable from .data import parse_zip_codes from .zip_code import ZIPCode def create_map_url(zip_codes: Iterable[ZIPCode], title: str) -> str: zips = ",".join(str(z) for z in zip_codes) return f"https://www.randymajors.com/p/customgmap.html?zips={zips}&title={title}" def main(body: str, title: str) -> int: # Parse zip codes from file zips = parse_zip_codes(body) # Print URL to map of zip code boundaries print(create_map_url(zips, title)) # Finish with no errors return 0
# -*- coding: utf-8 -*- """ Created on Fri Sep 13 04:52:16 2019 @author: dina list of dictionary objects not good because: - place for key name that is same for all dictionaries - can change values that is not right so use collections library to get immutable data structure and put the data in a tuple because don't want to delete the values and the objects """ import collections peoples = [{'name': 'dana', 'age':23, 'id':123}, {'name': 'hana', 'age':41, 'id':343}] print("all peoples list info ") for people in peoples: print (people) peoples[0]['name'] = 'moshe' print ("\nfirst dictionary info key changed. the dictionary is : ", peoples[0]) #use collection that use tuple instead of dictionary PeoplesCollection = collections.namedtuple('PeoplesCollection', [ 'name', 'age', 'id' ]) ela = PeoplesCollection(name ='Ela Stam', age = 45, id = 4545) if ela.age in range(40, 60): print (ela.name, ela.id) #get immutable data so cann't change key and value info # put the collections in list so can del objects from the list # del we use list peoplesL = [PeoplesCollection(name ='Ela Stam', age = 45, id = 4545), PeoplesCollection(name ='Efy Stam', age = 13, id = 12345), PeoplesCollection(name ='Ted Stam', age = 45, id = 3421)] print ('\n\ndata') for people in peoplesL: print (people) #delete object from the list del peoplesL[1] print ("\n\n delete second object from the list") print (peoplesL) # use collections and tuple because don't want to delete peoplesT = [PeoplesCollection(name ='Haim Levy', age = 55, id = 123), PeoplesCollection(name ='Varda Cohen', age = 13, id = 456), PeoplesCollection(name ='Ada Qa', age = 6, id = 789)] print('\n info tuple') print (peoplesT)
# -*- coding: utf-8 -*- """ Created on Sun Nov 3 08:55:38 2019 Keras API save img() function to save an image to file. The function takes the path to save the image and the image data in NumPy array format. The file format is inferred from the filename but can also be specified via the file format argument. The example below loads the photograph image in grayscale format, converts it to a NumPy array, and saves it to a new file name. @author: dina """ from keras.preprocessing.image import load_img from keras.preprocessing.image import save_img from keras.preprocessing.image import img_to_array #load image img = load_img('bondi_beach.jpg', color_mode='grayscale') # convert image to a numpy array img_array = img_to_array(img) # save the image with a new filename save_img('bondi_beach_grayscale.jpg', img_array) # load the image to confirm it was saved correctly img = load_img('bondi_beach_grayscale.jpg') #print image details print(type(img)) print('image format: ', img.format) #image format JPEG OR PNG print('image mode: ', img.mode) #pixel channel format (RGB or CMYK) print('image size ', img.size) #the dimention of the image in pixels img.show()
import sqlite3 import os conn = sqlite3.connect(os.path.dirname(os.path.realpath(__file__)) + '\\test.db') print ("Opened database successfully"); cursor = conn.execute('SELECT max(id) FROM test') # print(cursor.fetchall()) #for row in cursor: # print(row) while True: word = input ('Bitte gib mir nur ein Wort:') if word == '': break else: conn.execute('INSERT INTO test(id, data) VALUES (?,?)', (2,'test')) conn.commit() cursor = conn.execute('SELECT * FROM test') # print(cursor.fetchall()) for row in cursor: print(row) conn.close()
summe = 0 anzahl = 0 while summe <= 50: try: user_input = int(input("Bitte eine Zahl eingeben:")) anzahl += 1 summe += user_input except: break if anzahl > 0: print ("Summe: ", summe, "Anzahl: ", anzahl) print ("Durchschnitt = ", summe / anzahl)
try: user_input = int(input("Bitte eine Zahl eingeben: ")) except: exit("eine Zahl du x#%&§@!") if user_input > 10: print ("user_input > 10") elif user_input == 10: print("user_input == 10") else: print("user_input < 10") print("fertig")
# PROBLEM: Code a Program which will help the user in Printing a Star Pattern according to their wish of style. print("Select the Pattern from the Two Options given below. \n") print("Here's Option 1:-") R = 5 while R >= 1: print(R * "*") R = R - 1 print() print("Option 2 on your Screen:-") H = 1 while H <= 5: print(H * "*") H = H + 1 print() print("Enter either 1 or 2, according to your preference.") Style = int(input()) print("OK, now Input the no. of Rows.") Rows = int(input()) print() print("Here we go.") while Rows >= 1 and Style == 1: print(Rows * "*") Rows = Rows - 1 One = 1 while One <= Rows and Style == 2: print(One * "*") One = One + 1
def factorial(n):return reduce(lambda x,y:x*y,[1]+range(1,n+1)) numbers=[] for key in str(factorial(100)): numbers.append(int(key)) print sum(numbers)
# coding: utf-8 # # Slicing Ends verse min/max # # If you have an order list of numbers how best to return the min and max values. # In[ ]: list min max list [] np min max np [] # In[ ]: # Slicing the first and last elements is faster than np.min(), np.max() if you know that the list is ordered #min_dwl = wl2[1:]-wl2[:-1] #%timeit np.min(wl2) ## min/max ~15 µs #%timeit np.max(wl2) ## min/max ~15 µs #%timeit wl2[0] ## [] ~300ns #%timeit wl2[-1] ## [] ~300ns #%timeit [np.min(wl2)-2*min_dwl, np.max(wl2)+2*min_dwl] ## ~ 70 µs #%timeit [wl2[0]-2*min_dwl, wl2[-1]+2*min_dwl] ## ~ 40 µs # In[ ]: # In[ ]:
import random import statistics as stats n = 10 lst = [random.random() for x in range(n)] def carloloop(nums): if nums <= 0.05: ## print("nine") nine.append(1) result = 9 elif 0.05 < nums <= .15: ## print('ten') ten.append(1) result = 10 elif .15 < nums <= .3: ## print('eleven') eleven.append(1) result = 11 elif .3 < nums <= .5: ## print('twelve') twelve.append(1) result = 12 elif .5 < nums <= .6: ## print('thirteen') thirt.append(1) result = 13 elif .6 < nums <= .7: ## print('fourteen') fourt.append(1) result = 14 elif .7 < nums <= .8: ## print('fifteen') fift.append(1) result = 15 elif .8 < nums <= .9: ## print('sixteen') sixt.append(1) result = 16 elif .9 < nums <= .95: ## print('seventen') sevt.append(1) result = 17 else: ## print('eighteen') eigt.append(1) result = 18 return result def profit(pre,last): return (pre*4000)+(last*10000) def cprofit(pre,last,total): salvage = total-pre-last return (pre*4000)+(last*10000)+(salvage*2500) def simulate(seed): avgrevs =[] stds = [] revs = [] stds = [] varz = [] for i in range(0,26): print('\n \n') print('----------------------') print(str(i)+' slots presold') print('----------------------') presoldrevs= [] for n in range(0,len(seed)): seedval = seed[n] last = carloloop(seedval) if last + i > 25: last = 25-i print(str(last) +' simulated last minute sales') rev = profit(i,last) revs.append(rev) presoldrevs.append(rev) print('revenue '+str(rev)+'\n') x = sum(revs)/len(revs) print('----------------------') print('avg rev ' + str(x)) std = stats.stdev(revs) print('std ' + str(std)) var = (1.984*std)/10 print('var ' + str(var)) print('----------------------') avgrevs.append(x) stds.append(std) varz.append(var) return [avgrevs,stds,varz] def csimulate(seed): avgrevs =[] stds = [] revs = [] stds = [] varz = [] for i in range(0,26): print('\n \n') print('----------------------') print(str(i)+' slots presold') print('----------------------') presoldrevs= [] for n in range(0,len(seed)): seedval = seed[n] last = carloloop(seedval) if last + i > 25: last = 25-i print(str(last) +' simulated last minute sales') rev = cprofit(i,last,25) revs.append(rev) presoldrevs.append(rev) print('revenue '+str(rev)+'\n') x = sum(revs)/len(revs) print('----------------------') print('avg rev ' + str(x)) std = stats.stdev(revs) print('std ' + str(std)) var = (1.984*std)/10 print('var ' + str(var)) print('----------------------') avgrevs.append(x) stds.append(std) varz.append(var) return [avgrevs,stds,varz] def test(): print(len(nine)/n) print(len(ten)/n) print(len(eleven)/n) print(len(twelve)/n) print(len(thirt)/n) print(len(fift)/n) print(len(sixt)/n) print(len(sevt)/n) print(len(eigt)/n) print(len(eigt)+len(sevt)+len(sixt)+len(fift)+len(fourt)+len(thirt)+len(twelve)+len(eleven)+len(ten)+len(nine)) nine = [] ten = [] eleven = [] twelve = [] thirt = [] fourt = [] fift = [] sixt = [] sevt = [] eigt = [] sim = [nine,ten,eleven,twelve,thirt,fourt,fift,sixt,sevt,eigt] sim1 = simulate(lst) sim2 = csimulate(lst)
def multiply_string(n): n = n + 1 return n if __name__ == '__main__': try: n = int(input("Enter the number")) except ValueError as err: print("ValueError found!!") else: print("Python!" * n) # age = 5 # print(multiply_string(age)) # print(age)
# ============================================================================= # Exercise-11 with Solution # Write a Python program to check the sum of three elements (each from an array) from three arrays is equal to a target value. Print all those three-element combinations. # # Sample data: # /* # X = [10, 20, 20, 20] # Y = [10, 20, 30, 40] # Z = [10, 30, 40, 20] # target = 70 # */ # ============================================================================= import itertools from functools import partial X = [10, 20, 20, 20] Y = [10, 20, 30, 40] Z = [10, 30, 40, 20] T = 70 def check_sum_array(N, *nums): if sum(x for x in nums) == N: return (True, nums) else: return (False, nums) pro = itertools.product(X,Y,Z) func = partial(check_sum_array, T) sums = list(itertools.starmap(func, pro)) result = set() for s in sums: if s[0] == True and s[1] not in result: result.add(s[1]) print(result)
# ============================================================================= # 6. Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers. Go to the editor # Sample data : 3, 5, 7, 23 # Output : # List : ['3', ' 5', ' 7', ' 23'] # Tuple : ('3', ' 5', ' 7', ' 23') # ============================================================================= inputuser = str(input('sequence of comma-separated numbers: ', )) list = inputuser.split(',') tuple = tuple(list) print('List : ', list) print('Tuple : ', tuple)
# -*- coding: utf-8 -*- """ Created on Thu Jul 13 21:11:01 2017 @author: Wizard """ import sqlite3 queries = { "a": "SELECT * FROM nodes_tags WHERE key='city' and value LIKE '%, WA%'"} # query the database and return results as rows def ask_question(query): db = sqlite3.connect("openmaps.db") c = db.cursor() c.execute(query) rows = c.fetchall() return rows db.close() # takes in a query as its order and completes the query using the given key def give_order(order, key): db = sqlite3.connect("openmaps.db") c = db.cursor() c.execute(order, [key]) db.commit() rows = c.fetchall() return rows db.close() # store results of query in [values] def compiler(query): values = [] for row in ask_question(query): values.append(row) return values # remove , WA and update entry def modifier(query): original = compiler(query) for e in original: value = e[2][:e[2].rfind(", WA")] give_order("UPDATE nodes_tags SET value='"+value+"' WHERE key ='"+e[1]+"' and id=?", e[0]) modifier(queries['a'])
import sys from task import Task from task_search import tasks_search MAIN_MENU_PROMPT = "WORK_LOG\nWhat would you like to do?\na) add new entry\n" \ "b) Search in existing entries\nc) Quit program\n" def app_menu(): """Application menu""" while True: prompt_res = input(MAIN_MENU_PROMPT).upper() if prompt_res == "A": Task() elif prompt_res == "B": tasks_search() elif prompt_res == "C": sys.exit() else: print("Error: Please provide a valid input: a,b or c\n") if __name__ == '__main__': app_menu()
# Class representing a population of individuals # Author Fan Zhang import random from Individual import Individual class Population: # Actual standard ctor. # param map The map. # param initialSize The initial size of the population. def __init__(self, map, initialSize): self.vector = [] for i in range(initialSize): self.vector.append(Individual(map)) # Randomly selects an individual out of the population # proportionally to its fitness. # return The selected individual. def randomSelection(self): # TODO implement random selection # an individual should be selected with a probability # proportional to its fitness Individual = random.choices(self.vector) return Individual[0]
""" Increase the output of a single neuron Taken from http://karpathy.github.io/neuralnets/ and refactored a bit Pending questions: - How can this be generalized to vectors? Should every element in every vector be considered as a variable? - How is the gradient calculated for dot and matrix products? """ import math class Unit: def __init__(self, value, grad): # value computed in the forward pass self.value = value # the derivative of circuit output w.r.t this unit, computed in backward pass self.grad = grad class MultiplyGate: def forward(self, in0, in1): self.in0 = in0 self.in1 = in1 self.out = Unit(in0.value * in1.value, 0.0) return self.out def backward(self): # `out.grad` is the gradient of the outer function # cf. Chain rule: outer gradient w.r.t inner function * inner gradient # In this case, in*.grad is the inner and out.grad is the outer gradient # ∂/∂in0[in0*in1]=in1 # ∂/∂in1[in0*in1]=in0 self.in0.grad += self.in1.value * self.out.grad self.in1.grad += self.in0.value * self.out.grad class AddGate: def forward(self, in0, in1): self.in0 = in0 self.in1 = in1 self.out = Unit(self.in0.value + self.in1.value, 0.0) return self.out def backward(self): # ∂/∂in0[in0+in1]=1 # ∂/∂in1[in0+in1]=1 self.in0.grad += 1 * self.out.grad self.in1.grad += 1 * self.out.grad class SigmoidGate: def sig(self, x): return 1 / (1 + math.exp(-x)) def forward(self, in0): self.in0 = in0 self.out = Unit(self.sig(self.in0.value), 0.0) return self.out def gradient(self, x): # The gradient of σ is weird because the output is used in its calculation # i.e. ∂σ/∂x=σ(x)(1-σ(x)) return self.sig(x) * (1 - self.sig(x)) def backward(self): self.in0.grad += self.gradient(self.in0.value) * self.out.grad if __name__ == '__main__': """ Calculate the gradient of σ(ax+by+c) and increase the result ∂σ/∂a = ∂σ/∂(ax+by+c) * ∂(ax+by+c)/∂a ∂(ax+by+c)/∂a = ∂(ax+by+c)/∂(ax+by) * ∂(ax+by)/∂a ∂(ax+by)/∂a = ∂(ax+by)/∂(ax) * ∂(ax)/∂a a <- a + α(∂σ/∂a) Notice the chain rule is being applied backwards with the gradient of the outer most function calculated first. """ a = Unit(1.0, 0.0) b = Unit(2.0, 0.0) c = Unit(-3.0, 0.0) x = Unit(-1.0, 0.0) y = Unit(3.0, 0.0) mul_gate_0 = MultiplyGate() mul_gate_1 = MultiplyGate() add_gate_0 = AddGate() add_gate_1 = AddGate() sig_gate = SigmoidGate() def forward_prop(): ax = mul_gate_0.forward(a, x) by = mul_gate_1.forward(b, y) axby = add_gate_0.forward(ax, by) axbyc = add_gate_1.forward(axby, c) return sig_gate.forward(axbyc) s = forward_prop() print('initial result', s.value) def backward_prop(): s.grad = 1 sig_gate.backward() add_gate_1.backward() add_gate_0.backward() mul_gate_1.backward() mul_gate_0.backward() print(a.grad, b.grad, c.grad, x.grad, y.grad) step_size = 0.01 a.value += step_size * a.grad b.value += step_size * b.grad c.value += step_size * c.grad x.value += step_size * x.grad y.value += step_size * y.grad backward_prop() # should be higher than initial value print('updated value', forward_prop().value)
def solution(S): parentheses = 0 for element in S: if element == "(": parentheses += 1 else: parentheses -= 1 if parentheses < 0: return 0 if parentheses == 0: return 1 else: return 0
def solution(T): if T.l == None and T.r == None: # Has no subtree return 0 elif T.l == None: # Only has right subtree return 1 + solution(T.r) elif T.r == None: # Only has left subtree return 1 + solution(T.l) else: # Have two subtrees return 1 + max(solution(T.l), solution(T.r))
class Train: def __init__(self, name , fare, seats): self.name = name self.fare = fare self.seats = seats def getStatus(self): print('************************') print(f"The Name Of Train is {self.name}") print(f"The Seats In Train is:{self.seats}") def fareInfo(self): print('************************') print(f"The Fare Of Train is {self.fare}") def bookTicket(self): if (self.seats>0): print(f"Your Seat is Booked!! Your Seat Number is {self.seats}") self.seats = self.seats - 1 else: print("Sorry This train is full kindly try in Tatkal") def cancelTicket(self): pass intercity = Train("Intercity Express : 12012019", 90, 2) intercity.fareInfo() intercity.bookTicket() #Booked First Ticket intercity.bookTicket() #Booked Second Ticket intercity.bookTicket() #Try To books Tickets Ticket intercity.getStatus()
name = input("Enter your Name:\n") marks = int(input("Enter your marks:\n")) phone = input("Enter your phone:\n") template = "The name of student is {}, his marks are {} and phone number is {}" output = template.format(name,marks,phone) print(output)
class Employee: company = "Google" def getSalary(self): print(f"Salary for this employee working in {self.company} is {self.salary}") ayush = Employee() ayush.salary = 1000000 ayush.getSalary() #---> automatically convert into below code the self (function) # Employee.getSalary(ayush)
class Person: country = 'India' def takeBreath(self): print("I am breathing....") class Employee(Person): company = "Honda" def getSalary(self): print(f"Salary is {self.salary}") def takeBreath(self): print("I am employee and luckily breathing...") class Programmer(Employee): company = 'Fiverr' def getSalary(self): print("No Salary to programmers") def takeBreath(self): print("I am employee and breathing++..") p = Person() p.takeBreath() # print(p.company) # Throws error e = Employee() print(e.company) e.takeBreath() pr = Programmer() pr.takeBreath() print(pr.company) print(pr.country)
L1 = [1,5,22,4,122,42,55,1111] print(L1) # L1.sort() ---> Sorts The List # L1.reverse() --->Reverse The List # L1.append(45) --->Appends The List add 45 at end of list # L1.insert(1,544) --->Inserts 544 at index 1 # L1.pop(2) --->Pops Out (Remove) Index 2 from lists # L1.remove(55) ---> Removes 55 from list print(L1)
cont = True i = 1 with open('/home/cyberboyayush/Documents/Python/Practise/Chapter 9/log.txt') as f: while cont: i+=1 cont= f.readline().lower() # reads full file as lower so that our program can detect it print(cont) if 'python' in cont: print(cont) print('Yes Python is present') print(i) i+=1
b = set() print(type(b)) # Addding values to empty set b.add(4) b.add(5) b.add(6) b.add(5) #Adding a value repeatidly does not change a set # Note : We Cannot add list or dict in sets #Accessing Elements print(b) #Find Length print(len(b)) #Removing Element b.remove(5) #Removes 5 from set b # b.remove(15) #Throws an error while removing 15 print(b) print(b.pop())
#!/usr/bin/env python3 """Um exemplo mais claro, observe que a ordem dos paramentros nao eh obedecida""" def printinfo(name, age): "This prints a passed info into this function." print("Name: ",name) print("Age: ",age) return # Chamando a funcao printinfo printinfo(age=43, name="Fabio")
#!/usr/bin/python3 str = "this is string example....wow!!!" print (str.title()) """The title() method returns a copy of the string in which first characters of all the words are capitalized.""" #s.title(), retorna a primeira letra de cada palavre em maiusculo. # print('the sun also rises'.title()) # print()
#!/usr/bin/env python3 from tkinter import * root = Tk() B1 = Button(root, text='circle', relief=RAISED, cursor='circle') B2 = Button(root, text='plus', relief=RAISED, cursor='plus') B1.pack() B2.pack() root.mainloop()
import os import time """The files and directories to be backed up are specified in a list Example on Windows OS: source = ['"C:\\My Documents"', 'C:\\Code'] Example on Unix: source = ['/Users/nome/Documents'] """ source = '/home/fabio/Pictures' """The backup must be stored in a main backup directory Example Windows: target_dir ='E:\\Backup' Example Unix: target_dir='/Users/nome/Backup""" target_dir = '/home/fabio/backup' """The files are backed up into a zip file. The name of the zip archive is the current date and time. Example: target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'""" # target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' """Create target directory if it is not present if not os.path.exists(target_dir): os.mkdir(target_dir) """ if not os.path.exists(target_dir): os.mkdir(target_dir) # make directory """the files are backed up into a zip file. The current day is the name of the subdirectory.""" today = target_dir + os.sep + time.strftime('%Y%m%d') # The current time is the name of the zip archive. now = time.strftime('%H%M%S') # Take a comment from the user to create the name # of the zip file comment = input('Enter the comment: ==> ') # Check if the comment was entered if len(comment) == 0: target = today + os.sep + now + '.zip' else: target = today + os.sep + now + '_' + comment.replace(' ', '_') + '.zip' # Create the subdirectory if isn't already there if not os.path.exists(today): os.mkdir(today) print('Successfully created directory.', today) """Use the zip command to put the files in zip archive Example: zip_command = "zip -r {0} {1}".format(target, ' '.join(source))""" zip_command = "zip -r {0} {1}".format(target, ''.join(source)) # Run the backup print("Zip command is: ") print(zip_command) print("Running") if os.system(zip_command) == 0: print("Successful backup to", target) else: print('Backup Failed')
#!/usr/bin/env python3 """O método asctime () converte uma tupla ou struct_time representando uma hora como retornada por gmtime () ou localtime () para uma cadeia de 24 caracteres da seguinte forma: 'Ter 17 de fev 23:21:05 2009 '. Sintaxe: time.asctime([t])) """ import time t = time.localtime() print("asctime: ", time.asctime(t))
#!/usr/bin/python3 """The islower() method checks whether all the case-based characters (letters) of the string are lowercase. """ str = "THIS is string example....wow!!!" print(str.islower()) str = "this is string example....wow!!!" print(str.islower()) print() print('abcdef'.islower()) print('abcde$f'.islower()) print('Abcde$f'.islower())
#!/usr/bin/env python3 a = ['foo', 'bar', 'baz', 'qux', 'quux', 'courge'] a.insert(3, 3.14159) # 3 = indice, 3.14159 = valor print(a)
#!/usr/bin/python3 """Description The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Syntax str.count(sub, start= 0,end=len(string)) """ str="this is string example....wow!!!" sub='i' print ("str.count('i') : ", str.count(sub)) sub='exam' print ("str.count('exam', 10, 40) : ", str.count(sub,10,40)) print() # s.count(<sub>[,<start>[,<end>]]) , conta a ocorrencia de uma substring em uma string alvo. # print('foo goo moo'.count('oo')) # print('foo goo moo'.count('oo', 0, 8)) # print()
"""cria um generator""" def main(): for i in inclusive_range(0,25): print(i, end=" ") print() def inclusive_range(*args): "Cria um range incluindo o ultimo numero." numargs = len(args) start=0 step=1 if numargs < 1: raise TypeError("Esperado ao menos 1 argumento, recebido {}".format(numargs)) elif numargs == 1: stop = args[0] elif numargs == 2: start = args[0] stop = args[1] #(start, stop) = args elif numargs == 3: (start, stop, step) = args else: raise TypeError("Esperado 3 argumentos, recebido {}".format(numargs)) #Generator i = start while i <= stop: yield i i += step if __name__=="__main__":main()
from tkinter import * janela = Tk() # W x H + L + T janela.geometry("400x300+200+200") def bt_click(): print('bt_click clicado') lb['text'] = 'E ganhe Super Poderes' bt = Button(janela, width=20, text="ok", command=bt_click) bt.place(x=100, y=100) lb = Label(janela, text='Aprenda Python') lb.place(x=150, y=150) janela.mainloop()
#!/usr/bin/env python3 """A rolodex of friends""" rolodex = { 'Aaron':5556069, 'Bill':5559824, 'Dad':5552603, 'David':5558381, 'Dillon':5553538, 'Jim':5555547, 'Mom':5552603, 'Olivia':5556397, 'Verne':5555309 } # # print(rolodex["Verne"]) # print(hash('Verne')) # Adding new person rolodex['Amanda'] = 5559988 #print(rolodex['Amanda']) rolodex['David'] = (5558381, 5558866) #print(rolodex['David']) def caller_id(lookup_number): for name, num in rolodex.items(): if num == lookup_number: return name print(caller_id(5559988)) print(caller_id(5552603))
#!/usr/bin/python3 """Equivale a invocar lstrip() e rstrip() sucessivamente. Sintaxe: str.strip([chars]); """ str = "*****this is string example....wow!!!*****" print(str.strip( '*' )) print() s = ' foo bar baz\t\t\t' print(s.lstrip().rstrip()) print('www.realpython.com'.strip('w.com'))
#!/usr/bin/python3 str = "this2016" print (str.isdecimal()) str = "23443434" print (str.isdecimal()) """The isdecimal() method checks whether the string consists of only decimal characters. This method are present only on unicode objects."""
#!/usr/bin/env python3 ages = [12, 19, 39, 87, 7,2] for age in ages: isAdult = age > 17 if isAdult: print('Being: ' + str(age) + " make you an adult") if not isAdult: print("Being: " + str(age) + " does not make you an adult.")
#!/usr/bin/env python3 #Exemplos utilizando operadores booleanos (and, or, not, in, not in, is , is not). a = True b = False x = ('bear', 'bunny', 'tree', 'sky','rain') y = 'bear' if y in x: # y (bear) in x (bear ...) print('Expression is true') else: print('Expression is false')
#!usr/bin/python3 import sys lista = [1,2,3,4] it = iter(lista) # this builds an iterator object print(next(it)) #prints next available element in iterator #Iterator object can be traversed using regular for statement # for x in it: print (x, end=" ") #or using next() function # while True: # try: # print(next(it)) # except StopIteration: # sys.exit() #you have to import sys module for this
#!/usr/bin/env python3 # Trocando os valores de duas variaveis , SWAP a = 'foo' b = 'bar' #print(a,b) # Primeira maneira, utilizando um variavel temporaria # temp = a # a = b # b = temp # print('Valor de a: "{}" e valor de b: "{}".'.format(a, b)) # De maneira mais Pythonica a, b = b, a print('Valor de a: "{}" e valor de b: "{}".'.format(a, b))
#!/usr/bin/env python3 """O método sleep () suspende a execução pelo número de segundos especificado. O argumento pode ser um número de ponto flutuante para indicar um tempo de sleep mais preciso. Sintaxe:time.sleep(t) """ import time print("Start: %s" % time.ctime()) time.sleep(3) print("End: %s" % time.ctime())
from tkinter import * root = Tk() var = IntVar() var.set(0) # inicializando com a opção Python marcada languages = [ "Python", "Perl", "Java", "C++", "C", ] def ShowChoice(): print(var.get()) # captura o valor da opção escolhida l1 = Label(root, text="""Escolha sua linguagem de programação favorita:""", justify=LEFT, padx=20).pack() for val, language in enumerate(languages): r1 = Radiobutton(root, text=language, indicatoron=0, padx=20, variable=var, command=ShowChoice, value=val).pack(anchor=W) root.mainloop() """Em vez de ter botões de rádio com orifícios circulares contendo espaço em branco, podemos ter botões de opção com o texto completo em uma caixa. Podemos fazer isso definindo a opção indicatoron (significa "indicador ligado") como 0, o que significa que não haverá indicador de botão de opção separado. O padrão é 1."""
#!/usr/bin/env python3 print('Listas_________') minhaLista = ['ABCD', 2.33, 'efgh', 'bola', 'copo'] print(minhaLista[0]) print(minhaLista[1]) print(minhaLista[2]) print(minhaLista[-1]) #Adicionando um elemento no final da lista utilizamos append minhaLista.append('Fogo') print(minhaLista) # Para adicionar e escolher a posição utilizamos insert minhaLista.insert(5, 'Terra') print(minhaLista) print() # deletando o ultimo elemento da lista del minhaLista[-1] print(minhaLista) print("Deletando todos os elementos de uma lista") del minhaLista[:] print(minhaLista) print("Deletando toda a lista") del minhaLista #print(minhaLista) # NameError: name 'minhaLista' is not defined print() print("Tupla_________") minhaTupla = ('ABCD', 2.33, 'efgh', 'bola', 'copo') print(minhaTupla[0]) print(minhaTupla[1]) print(minhaTupla[-1]) #del minhaTupla[0] # Error #minhaTupla.append('Fogo') # Error #minhaTupla.insert(5, 'Terra') # Error # del minhaTupla # print(minhaTupla) # NameError: name 'minhaTupla' is not defined print() print('Dicionarios_________') dict = {'one': 1, 'two': 2, 'tree': 3} print(dict['one']) print(dict['two']) dict['Four'] = 4 dict.update({'Five': 5}) print(dict) del dict['one'] print(dict) dict.pop('two') print(dict) pessoa = {"Nome": "fabio", "Identidade": "000000", "Idade": 43,"telefone": '9999-8888'} print(pessoa['Nome']) print(pessoa['Identidade']) del pessoa['Identidade'] print(pessoa) # Deleta todos os elementos do dicionario pessoa.clear() print(pessoa) # Deletando todo o dicionario del pessoa print(pessoa) # NameError: name 'pessoa' is not defined
#!/usr/bin/env python3 import tkinter window = tkinter.Tk() window.title("Mouse click events") # definindo 3 diferente funções para eventos def left_click(event): tkinter.Label(window, text="Left Click").pack() def middle_click(event): tkinter.Label(window, text="Middle click").pack() def right_click(event): tkinter.Label(window, text="Right click").pack() window.bind("<Button-1>", left_click) window.bind("<Button-2>", middle_click) window.bind("<Button-3>", right_click) window.mainloop()
#!/usr/bin/env python3 # -*- coding:utf-8 -*- a = 21 b = 10 c = 0 c = a + b print ("Line 1 - Value of c is ", c) c = a - b print("Line 2 - Value of c is ", c ) c = a * b print("Line 3 - Value of c is ", c) c = a / b print("Line 4 - Value of c is ", c ) c = a % b print("Line 5 - Value of c is ", c) a = 2 b = 3 c = a**b print("Linne 6 - Value of c is ", c) a = 10 b = 5 c = a//b print("Line 7 - Value of c is ", c) print(pow(a, c)) print(pow(10, 3))
nome = 'Fabio' idade = 42 peso = 72 altura = 1.70 code = 'Python' versao = 2.7 ano = 2018 # place holder """"% python 2.7, place holder %s (strings) , %d(inteiros) %f(floats)""" print('Meu nome eh %s meu codigo eh %s, versao: %d'%(nome, code, versao)) #formato Python versao 3.0 #print('Vamos programar em {} versao {:.1f}, ano {}'.format(code,versao, ano )) # versao 3.5.6 # format{} #print(f'Vamos programar em {code} versao {versao:.1f} ano {ano}')
#!/usr/bin/python3 """The rjust() method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). """ str = "this is string example....wow!!!" print (str.rjust(50, '*')) print() print('foo'.rjust(10)) print('foo'.rjust(10, '-'))
'''A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these comma-separated values between parentheses also.''' tup1 = ('physics', 'chemistry', 1997, 2000) tup2 = (1,2,3,4,5) tup3 = 'a', 'b', 'c', 'd', 'e' print(type(tup1),',', type(tup2),',', type(tup3)) '''Esvaziando uma tupla''' tup1 = () print(tup1) tup1 = (50, ) # escrevendo uma tupla com um unico valor necessario incluir uma virgula # print(tup1) '''Acessando valores''' # print(tup2[0]) # print(tup2[1:5]) '''Updanting Tuples''' # print(tup1) # print(tup2) # tup4 = tup1 + tup2 # concatenacao # print(tup4) '''Deletando elementos de uma tupla Nao e possivel deletar elementos individualmente.''' # print('tup4') # print(tup4) # del tup4 #print(tup4) # NameError: name 'tup4' is not defined '''Operacoes basicas''' # print(len(tup2)) # # tup5 = tup1+tup2+tup3 # print(tup5) # concatenacao # # print((tup1) * 4) #repeticao # # print(3 in tup2) # Operador in verifica se 3 eh membro de tup2 # # for x in tup2:print(x, end=',') # interacao # print() '''Indices, Fatias e Matriz''' # T = ('C++', 'Java', 'Python') # print(T[2]) # print(T[-2]) # print(T[1:]) '''len() method''' tupla1, tupla2 = (123, 'xyz', 'zara'), (456, 'abc') print('First tuple length: ', len(tupla1)) print('Second tuple length: ', len(tupla2)) '''max() method''' tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200) print('Max value element: ', max(tuple1)) print('Max value element: ', max(tuple2)) '''min() method''' print('Min value element: ', min(tuple1)) print('Min value element: ', min(tuple2)) '''tuple() methods - converts a list into tuples ''' lista1 = ['maths','che', 'phy', 'bio'] novaTupla = tuple(lista1) print(novaTupla, type(novaTupla))
#!/usr/bin/env python3 a = ['foo', 'bar', 'baz', 'qux', 'quux', 'courge'] a.pop() # a.pop() simply removes the last item in the list print(a) print(a.pop(1)) # 'bar'
#!/usr/bin/env python3 # multiplos diretorios e arquivos import os for dirpath, dirnames, files in os.walk('.'): print('-' * 70) print(f'Diretorios e arquivos encontrados: {dirpath}') for file_name in files: print(file_name)
#!/usr/bin/env python3 import tkinter window = tkinter.Tk() window.title("Label") # definindo 3 labels simples contendo texto simples # sufficient width tkinter.Label(window, text = "Sufficient width", fg="white", bg="purple").pack() # width of x tkinter.Label(window, text="Width of x", fg="white", bg="green").pack(fill="x") # height of y tkinter.Label(window, text="Height of y", fg="white", bg='black').pack(side='left', fill='y') window.mainloop()
#!/usr/bin/env python3 """Criando um dicionario a partir de duas listas usando a função zip""" questions = ['name', 'questions', 'favourite color'] answer = ['Lancelot', 'the holy grail', 'blue'] for q, a in zip(questions, answer): print("What's yours {}? It's {}".format(q, a))
#!/usr/bin/env python3 fo = open('foo3.txt', 'r') # modo leitura r/read print("Nome do arquivo: ", fo.name) for index in range(5): line = next(fo) print(f'Line No {index} - {line}') fo.close()
#!/usr/bin/python3 str = "this is string example....wow!!!" print ("Length of the string: ", len(str)) """The len() method returns the length of the string. Syntax len( str )"""
#!/usr/bin/env python3 """Sempre que usamos a palavra reservada yield , estamos criando uma funcao geradora. A funcao geradora gera um valor toda vez em que e “chamada”, e aqui, usamos aspas, pois não e uma chamada comum. Por padrão, as funções geradoras podem ser iteradas no comando for""" def get_generator(): for i in range(10): yield i # Substitua yeild por return Erro: TypeError: 'int' object is not iterable for number in get_generator(): print(number) """Para obtermos o mesmo resulta utilizando a declaracao return, precisamos salvar o numeros gerados em uma lista""" print() # def get_list(): # numbers = [] # Lista onde sera salva os numeros # for i in range(10): # numbers.append(i) # return numbers # # # for number in get_list(): # print(number)
from tkinter import * root = Tk() var = IntVar() l1 = Label(root, text="Escolha uma linguagem de programação:", justify=LEFT, padx=20).pack() r1 = Radiobutton(root, text="Python", padx=20, variable=var, value=1).pack(anchor=W) r2 =Radiobutton(root, text="Perl", padx=20, variable=var, value=2).pack(anchor=W) root.mainloop()
from tkinter import * def write_slogan(): print("Tkinter is use to learn!!!!") root = Tk() frame = Frame(root) frame.pack() button = Button(frame, text="QUIT", fg="red", command=quit) button.pack(side=LEFT) slogan = Button(frame, text="Hello", command=write_slogan) slogan.pack(side=LEFT) root.mainloop()
from player import Player class Human(Player): def __init__(self): super().__init__() def choose_gesture(self): self.chosen_gesture = input("Pick a gesture: rock, paper, scissors, lizard, spock ") if (self.chosen_gesture == "rock" or self.chosen_gesture == "paper" or self.chosen_gesture == "scissors" or self.chosen_gesture == "lizard" or self.chosen_gesture == "spock"): print(self.chosen_gesture) else: print("Not a valid gesture, please try again") self.choose_gesture()
from turtle import Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=800, height=600) screen.bgcolor("black") screen.title("Pong") screen.tracer(0) scoreboard = Scoreboard() screen.listen() paddle1 = Paddle(1) paddle2 = Paddle(2) ball = Ball() screen.onkey(paddle1.go_up, "Up") screen.onkey(paddle1.go_down, "Down") screen.onkey(paddle2.go_up, "w") screen.onkey(paddle2.go_down, "s") screen.onkey(scoreboard.start_game, "space") game_is_on = True while game_is_on: time.sleep(ball.move_speed) screen.update() if scoreboard.game_start: paddle1.showturtle() paddle2.showturtle() ball.showturtle() ball.move() # Detect collision with the wall then bounce if ball.ycor() > 280 or ball.ycor() < -280: ball.bounce() # Detect collision the paddle then bounce if ball.distance(paddle1) < 50 and ball.xcor() > 320 or ball.distance(paddle2) < 50 and ball.xcor() < -320: ball.bounce_paddle() # Restart the game if anyone miss the ball if ball.xcor() > 400: scoreboard.player2_score += 1 scoreboard.update_score() ball.new_round() if ball.xcor() < -400: scoreboard.player1_score += 1 scoreboard.update_score() ball.new_round() if scoreboard.player1_score > 3 or scoreboard.player2_score > 3: if scoreboard.player1_score > scoreboard.player2_score: winner_name = "Player on the right hand side " else: winner_name = "Player on the left hand side " scoreboard.show_winner(winner_name) game_is_on = False screen.exitonclick()
from src.algorithms.node import Node # Given a list of integers as the leafs of a binary tree, create a balanced binary tree, in which # the sum of a node's children will equal the node's value. # Return the root of the binary tree. # # Print the binary tree as the following: # For example, given the list [1, 2, 3, 3, 4, 10] # Print the following balanced binary tree # [23, # 9, 14, # 3, 6, 14, 0 # 1, 2, 3, 3, 4, 10, 0, 0] def create_balanced_binary_tree(): list_first_line = list(input().split()) list_first_line = list(map(int, list_first_line)) list_first_line.sort() known_leaves = len(list_first_line) total_leaf_size = 2**((len(list_first_line)-1).bit_length()) tree = [] tree.extend([0]*(total_leaf_size-1)) tree.extend(list_first_line) tree.extend([0]*(total_leaf_size-known_leaves)) start_at = total_leaf_size-2 while start_at>= 0: tree[start_at] = tree[2*start_at+1] + tree[2*start_at+2] start_at -= 1 print(tree)