text
stringlengths 37
1.41M
|
---|
def bubblesort(a):
j = 0
while j != (len(a)-1):
j = 0
for i in range(0, (len(a)-1)):
first = a[i]
second = a[i+1]
if first > second:
a[i] = second
a[i+1] = first
else:
j = j+1
print (a)
return a
a = [9,2,7,1,6,3,7,8]
bubblesort(a) |
class Road():
def __init__(self, length=1000, curve=0):
self.length = length
self.curve = curve
def road_loop(self, car_list, car, next_car):
if next_car.position[0] - 5 < 6:
car.position[0] = 1000
car.speed = 0
else:
car.position[0] -= 1000
car_list.insert(0, car_list.pop())
car.collision_check(next_car)
return car_list
|
import os
import random
def clear_output():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
'Queen':10, 'King':10, 'Ace':11}
values_visual = {'Two':'2 ', 'Three':'3 ', 'Four':'4 ', 'Five':'5 ', 'Six':'6 ', 'Seven':'7 ', 'Eight':'8 ',
'Nine':'9 ', 'Ten':'10', 'Jack':'J ', 'Queen':'Q ', 'King':'K ', 'Ace':'A '}
class Card:
def __init__(self,rank,suit):
self.rank = rank
self.suit = suit
def __str__(self):
return self.rank + ' of ' + self.suit
class Deck:
def __init__(self):
self.deck = [] # start with an empty list
for rank in ranks:
for suit in suits:
self.deck.append(Card(rank,suit)) # build Card objects and add them to the list
def __str__(self):
deck_comp = '' # start with an empty string
for card in self.deck:
deck_comp += '\n '+card.__str__() # add each Card object's print string
return deck_comp
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = []
self.value = 0
self.aces = 0 # add an attribute to keep track of aces
self.tens = 0
def add_card(self,card):
self.cards.append(card)
self.value += values[card.rank]
if card.rank == 'Ace':
self.aces += 1 # add to self.aces
elif card.rank == 'Ten' or card.rank == 'Jack' or card.rank == 'Queen' or card.rank == 'King':
self.tens += 1
def adjust_for_ace(self):
while self.value > 21 and self.aces:
self.value -= 10
self.aces -= 1
class Chips:
def __init__(self,total=100):
self.total = total
self.bet = 0
def win_blackjack_bet(self):
self.total += round(self.bet * 1.5)
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
chips.bet = int(input('How many chips would you like to bet? '))
except ValueError:
print('Please enter a whole number.')
else:
if chips.bet > chips.total:
print("Sorry, your bet can't exceed " + str(chips.total))
elif chips.bet <= 0:
print('Please place a bet.')
else:
break
def hit(deck,hand):
hand.add_card(deck.deal())
hand.adjust_for_ace()
def hit_or_stand(deck,hand):
global playing # to control an upcoming while loop
while True:
x = input("\nWould you like to Hit or Stand? Enter h or s: ")
if x == 'h':
hit(deck,hand) # hit() function defined above
clear_output()
break
elif x == 's':
print("Player stands. Dealer is playing.")
playing = False
clear_output()
break
else:
print("Sorry, please enter h or s.")
continue
def check_for_blackjack(player):
if len(player.cards) == 2:
if player.tens == 1 and player.aces == 1:
return True
else:
return False
else:
return False
def show_dealer_some(dealer):
print("\nDealer's Hand:")
print(" ------- ")
print(" | {} | ".format(values_visual[dealer.cards[1].rank]))
print(" | | ")
print(" ---| | ")
print(" | ? | | ")
print(" | | {}| ".format(values_visual[dealer.cards[1].rank]))
print(" | ------- ")
print(" | | ")
print(" | ? | ")
print(" ------- ")
print(" {} ".format(dealer.cards[1]))
print(" {} \n".format("? of ?"))
def show_dealer_all(dealer):
if len(dealer.cards) == 2:
print("\nDealer's Hand:")
print(" ------- ")
print(" | {} | ".format(values_visual[dealer.cards[1].rank]))
print(" | | ")
print(" ---| | ")
print(" | {}| | ".format(values_visual[dealer.cards[0].rank]))
print(" | | {}| ".format(values_visual[dealer.cards[1].rank]))
print(" | ------- ")
print(" | | ")
print(" | {}| ".format(values_visual[dealer.cards[0].rank]))
print(" ------- ")
print(" {} ".format(dealer.cards[1]))
print(" {} \n".format(dealer.cards[0]))
elif len(dealer.cards) == 3:
print("\nDealer's Hand:")
print(" ------- ")
print(" | {} |".format(values_visual[dealer.cards[2].rank]))
print(" | |")
print(" ---| |")
print(" | {}| |".format(values_visual[dealer.cards[1].rank]))
print(" | | {}|".format(values_visual[dealer.cards[2].rank]))
print(" ---| ------- ")
print(" | {}| | ".format(values_visual[dealer.cards[0].rank]))
print(" | | {}| ".format(values_visual[dealer.cards[1].rank]))
print(" | ------- ")
print(" | | ")
print(" | {}| ".format(values_visual[dealer.cards[0].rank]))
print(" ------- ")
print(" {} ".format(dealer.cards[2]))
print(" {} ".format(dealer.cards[1]))
print(" {} \n".format(dealer.cards[0]))
elif len(dealer.cards) == 4:
print("\nDealer's Hand:")
print(" ------- ")
print(" | {} |".format(values_visual[dealer.cards[3].rank]))
print(" | |")
print(" ---| |")
print(" | {}| |".format(values_visual[dealer.cards[2].rank]))
print(" | | {}|".format(values_visual[dealer.cards[3].rank]))
print(" ---| ------- ")
print(" | {}| |".format(values_visual[dealer.cards[1].rank]))
print(" | | {}|".format(values_visual[dealer.cards[2].rank]))
print(" ---| ------- ")
print(" | {}| | ".format(values_visual[dealer.cards[0].rank]))
print(" | | {}| ".format(values_visual[dealer.cards[1].rank]))
print(" | ------- ")
print(" | | ")
print(" | {}| ".format(values_visual[dealer.cards[0].rank]))
print(" ------- ")
print(" {} ".format(dealer.cards[3]))
print(" {} ".format(dealer.cards[2]))
print(" {} ".format(dealer.cards[1]))
print(" {} \n".format(dealer.cards[0]))
else:
print("\nDealer's Hand: \n")
for card in dealer_hand.cards:
print(" " + str(card))
def show_player_all(player):
if len(player.cards) == 2:
print(" ------- ")
print(" | {} | ".format(values_visual[player.cards[1].rank]))
print(" | | ")
print(" ---| | ")
print(" | {}| | ".format(values_visual[player.cards[0].rank]))
print(" | | {}| ".format(values_visual[player.cards[1].rank]))
print(" | ------ ")
print(" | | ")
print(" | {}| ".format(values_visual[player.cards[0].rank]))
print(" ------- ")
print(" {} ".format(player.cards[1]))
print(" {} ".format(player.cards[0]))
print("\n Current Bet: {}".format(player_chips.bet))
print(" Total Chips: {}".format(player_chips.total))
print("\nPlayer's Hand:")
elif len(player.cards) == 3:
print(" ------- ")
print(" | {} |".format(values_visual[player.cards[2].rank]))
print(" | |")
print(" ---| |")
print(" | {}| |".format(values_visual[player.cards[1].rank]))
print(" | | {}|".format(values_visual[player.cards[2].rank]))
print(" ---| ------- ")
print(" | {}| | ".format(values_visual[player.cards[0].rank]))
print(" | | {}| ".format(values_visual[player.cards[1].rank]))
print(" | ------- ")
print(" | | ")
print(" | {}| ".format(values_visual[player.cards[0].rank]))
print(" ------- ")
print(" {} ".format(player.cards[2]))
print(" {} ".format(player.cards[1]))
print(" {} ".format(player.cards[0]))
print("\n Current Bet: {}".format(player_chips.bet))
print(" Total Chips: {}".format(player_chips.total))
print("\nPlayer's Hand:")
elif len(player.cards) == 4:
print(" ------- ")
print(" | {} | ".format(values_visual[player.cards[3].rank]))
print(" | | ")
print(" ---| | ")
print(" | {}| | ".format(values_visual[player.cards[2].rank]))
print(" | | {}| ".format(values_visual[player.cards[3].rank]))
print(" ---| ------- ")
print(" | {}| | ".format(values_visual[player.cards[1].rank]))
print(" | | {}| ".format(values_visual[player.cards[2].rank]))
print(" ---| ------- ")
print(" | {}| | ".format(values_visual[player.cards[0].rank]))
print(" | | {}| ".format(values_visual[player.cards[1].rank]))
print(" | ------- ")
print(" | | ")
print(" | {}| ".format(values_visual[player.cards[0].rank]))
print(" ------- ")
print(" {} ".format(player.cards[3]))
print(" {} ".format(player.cards[2]))
print(" {} ".format(player.cards[1]))
print(" {} ".format(player.cards[0]))
print("\n Current Bet: {}".format(player_chips.bet))
print(" Total Chips: {}".format(player_chips.total))
print("\nPlayer's Hand:")
else:
print("\nPlayer's Hand: \n")
for card in player_hand.cards:
print(" " + str(card))
def player_busts(player,dealer,chips):
print("\nPlayer busts!")
chips.lose_bet()
def player_wins_blackjack(player,dealer,chips):
print("\nPlayer wins Blackjack!")
chips.win_blackjack_bet()
def player_wins(player,dealer,chips):
print("\nPlayer wins!")
chips.win_bet()
def dealer_busts(player,dealer,chips):
print("\nDealer busts!")
chips.win_bet()
def dealer_wins(player,dealer,chips):
print("\nDealer wins!")
chips.lose_bet()
def push(player,dealer):
print("\nDealer and Player tie! It's a push.")
game_on = True
intro = True
deal_cards = False
playing = False
while game_on:
while intro:
clear_output()
print("\nWelcome to Blackjack!")
print("\nThis version of Blackjack does not allow splits.")
print("The Dealer hits until 17 or more.")
print("A winning blackjack pays 3:2.")
print("\nYour starting amount of chips is: 100")
player_chips = Chips()
deal_cards = True
break
while deal_cards:
# create & shuffle the deck, deal two cards to each player
deck = Deck()
deck.shuffle()
player_hand = Hand()
player_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand = Hand()
dealer_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
# prompt the Player for their bet
take_bet(player_chips)
clear_output()
# show cards (but keep one dealer card hidden)
show_dealer_some(dealer_hand)
show_player_all(player_hand)
playing = True
break
while playing: # recall this variable from our hit_or_stand function
# prompt Player to Hit or Stand
hit_or_stand(deck,player_hand)
clear_output()
# show cards (but keep one dealer card hidden)
show_dealer_some(dealer_hand)
show_player_all(player_hand)
# if player's hand exceeds 21, run player_busts() and break out of loop
if player_hand.value > 21:
clear_output()
player_busts(player_hand,dealer_hand,player_chips)
break
# if player hasn't busted, play dealer's hand until dealer reaches 17
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck,dealer_hand)
# run different winning scenarios
clear_output()
# check if player got blackjack
if check_for_blackjack(player_hand):
if dealer_hand.value != 21:
player_wins_blackjack(player_hand,dealer_hand,player_chips)
else:
push(player_hand,dealer_hand)
# dealer busts
elif dealer_hand.value > 21:
dealer_busts(player_hand,dealer_hand,player_chips)
# dealer wins
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand,dealer_hand,player_chips)
# player wins
elif dealer_hand.value < player_hand.value:
player_wins(player_hand,dealer_hand,player_chips)
# push
else:
push(player_hand,dealer_hand)
# show all hands & player's total chips
show_dealer_all(dealer_hand)
show_player_all(player_hand)
# if player busts, ask if they want to play again
if player_chips.total == 0:
print("\nSorry, you ran out of chips!")
print("Game Over!\n")
# if player ran out of chips, ask if they want to play again
while player_chips.total == 0:
x = input("Play again? Enter y or n: ")
if x == 'y' or x == 'n':
break
else:
print("Please try again.")
# go back to the intro
if x == 'y':
intro = True
continue
# exit game
else:
print("Thanks for playing!")
break
else:
# if player still has chips, ask if they want to keep playing
while player_chips.total > 0:
x = input("Do you want to play another hand? Enter y or n: ")
if x == 'y' or x == 'n':
break
else:
print("Please try again.")
# skip the intro & deal another hand
if x == 'y':
intro = False
deal_cards = True
continue
#exit game
else:
print("Thanks for playing!")
break |
# -*- encoding: utf-8 -*-
'''
@File : 定长数组实现队列.py
@Time : 2020/06/08 17:47:40
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class MyQueue:
def __init__(self, size):
super().__init__()
self.head = 0
self.tail = 0
self.size = 0
self.cap = size
self.array = [0 for i in range(size)]
def add(self, num):
if self.size >= self.cap:
raise Exception("no space")
else:
self.array[self.tail] = num
self.size += 1
self.tail = (self.tail+1) % self.cap
def addhead(self, num):
if self.size >= self.cap:
raise Exception("no space")
else:
self.array[self.head-1] = num
self.size += 1
self.head -= 1
if self.head < 0:
self.head = self.head+self.cap
def lpop(self):
if self.size <= 0:
raise Exception("no enough money")
else:
num = self.array[self.head]
self.head = (self.head+1) % self.cap
self.size -= 1
return num
def rpop(self):
if self.size <= 0:
raise Exception("no enough money")
else:
num = self.array[self.tail-1]
self.tail -= 1
if self.tail < 0:
self.tail += self.cap
self.size -= 1
return num
if __name__ == "__main__":
x = MyQueue(3)
x.add(1)
x.add(2)
x.addhead(3)
print(x.lpop())
print(x.rpop())
x.add(4)
x.lpop()
x.add(5)
x.lpop()
x.add(6)
x.lpop()
print(x)
|
# -*- encoding: utf-8 -*-
'''
@File : 面试题59 - II. 队列的最大值.py
@Time : 2020/05/09 11:41:43
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
import queue
import queue
class MaxQueue:
def __init__(self):
self.maxqueue = queue.deque()
self.queue = queue.Queue()
def max_value(self) -> int:
if not self.maxqueue:
return -1
return self.maxqueue[0]
def push_back(self, value: int) -> None:
while self.maxqueue and self.maxqueue[-1] < value:
self.maxqueue.pop()
self.maxqueue.append(value)
self.queue.put(value)
def pop_front(self) -> int:
# Your MaxQueue object will be instantiated and called as such:
# obj = MaxQueue()
# param_1 = obj.max_value()
# obj.push_back(value)
# param_3 = obj.pop_front()
if not self.maxqueue:
return -1
res = self.queue.get()
if res == self.maxqueue[0]:
self.maxqueue.popleft()
if __name__ == "__main__":
x = MaxQueue()
print(x.push_back(1))
print(x.push_back(2))
print(x.push_back(3))
print(x.max_value())
print(x.push_back(4))
print(x.max_value())
print(x.pop_front())
print(x.max_value())
|
# -*- encoding: utf-8 -*-
'''
@File : 面试题12. 矩阵中的路径.py
@Time : 2020/06/07 14:44:02
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
m = len(board)
n = len(board[0])
def dfs(i, j, index):
if index == len(word):
return True
if i < 0 or j < 0 or i >= m or j >= n or board[i][j] == '#' or board[i][j]!=word[index]:
return False
temp = board[i][j]
board[i][j] = '#'
res = dfs(i+1, j, index+1) or dfs(i-1, j, index +
1) or dfs(i, j+1, index+1) or dfs(i, j-1, index+1)
board[i][j] = temp
return res
for i in range(m):
for j in range(n):
if word[0] == board[i][j]:
if dfs(i, j, 0):
return True
return False
if __name__ == "__main__":
x = Solution()
print(x.exist(
[["A", "B", "C", "E"], ["S", "F", "C", "S"], ["A", "D", "E", "E"]],
"ABCDE"
))
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None:
return False
p1=head
p2=p1.next
while p2!=p1:
if p1.next is None or p1.next.next is None:
return False
p1=p1.next
p2=p2.next.next
return True |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
res = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return 0
leftlen = helper(root.left)
rightlen = helper(root.right)
self.res = max(self.res, leftlen+rightlen+1)
return max(leftlen, rightlen)+1
helper(root)
return self.res-1
if __name__ == "__main__":
x=Solution()
root=TreeNode(1)
root.left=TreeNode(2)
root.right=TreeNode(3)
# root.left.left=TreeNode(4)
# root.left.right=TreeNode(5)
print(x.diameterOfBinaryTree(root)) |
# -*- encoding: utf-8 -*-
'''
@File : 110. 平衡二叉树.py
@Time : 2020/04/27 21:12:31
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if root is None:
return True
def helper(root) -> int:
if root is None:
return 0
lefth = helper(root.left)
righth = helper(root.right)
if lefth == -1 or righth == -1:
return -1
if abs(lefth-righth) > 1:
return -1
else:
return max(lefth, righth)+1
h = helper(root)
if h != -1:
return True
return False
if __name__ == "__main__":
x = Solution()
root = TreeNode(4)
root.left = TreeNode(2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
root.right = TreeNode(6)
root.right.left = TreeNode(5)
print(x.isBalanced(root))
|
from typing import List
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
maxarea=0
heights=[0]+heights+[0]
stack=[]
for i in range(len(heights)):
# 栈顶元素大于当前元素
while stack and heights[stack[-1]] > heights[i]:
temp=stack.pop()
maxarea=max(maxarea,(i-stack[-1]-1)*heights[temp])
stack.append(i)
return maxarea
if __name__ == "__main__":
x=Solution()
print(x.largestRectangleArea([1]))
|
# -*- encoding: utf-8 -*-
'''
@File : 88. 合并两个有序数组.py
@Time : 2020/04/23 09:24:45
@Author : windmzx
@Version : 1.0
@Desc : For leetcode template
'''
# here put the import lib
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
index=m+n-1
i=m-1
j=n-1
while i>=0 and j>=0:
if nums1[i]>nums2[j]:
nums1[index]=nums1[i]
index-=1
i-=1
else:
nums1[index]=nums2[j]
j-=1
index-=1
while i>=0:
nums1[index]=nums1[i]
index-=1
i-=1
while j>=0:
nums1[index]=nums2[j]
j-=1
index-=1
if __name__ == "__main__":
x=Solution()
print() |
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
length=len(num)
def isactive(num1,num2,k):
num3=num1+num2
index=k+1
while index<=length:
if str(int(num[k:index]))==num[k:index] and int(num[k:index])==num3:
num1=num2
num2=num3
num3=num1+num2
return index==length or isactive(num1, num2, index)
else:
index+=1
return False
for i in range(1,length//2+1):
for j in range(1,length//2+1):
num1=int(num[:i])
if str(int(num[i:i+j]))!=num[i:i+j]:
continue
num2=int(num[i:i+j])
if isactive(num1,num2, i+j):
return True
return False
if __name__ == "__main__":
x=Solution()
print(x.isAdditiveNumber("1203")) |
from typing import List
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
flag=True
while flag:
flag=False
for i in range(1,len(people)):
a1=people[i-1]
a2=people[i]
if a1[0]<a2[0]:
flag=True
people[i]=a1
people[i-1]=a2
elif a1[0]==a2[0]:
if a1[1]>a2[1]:
flag=True
people[i]=a1
people[i-1]=a2
res=[]
for p in people:
res.insert(p[1],p)
return res
if __name__ == "__main__":
x=Solution()
in1=[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
res=x.reconstructQueue(in1)
print(res) |
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
def check(row, col):
com = board[row][col]
for i in range(row//3*3, row//3*3+3):
for j in range(col//3*3, col//3*3+3):
if i == row and j == col:
continue
if board[i][j] != '.' and board[i][j] == com:
return False
# for j in range(-row,0):
# if row+j<0 or row+j>=9 or col+j<0 or col+j>=9:
# pass
# else:
# if board[row+j][col+j]!='.' and board[row+j][col+j]==com:
# return False
# for j in range(1,9-row):
# if row+j<0 or row+j>=9 or col+j<0 or col+j>=9:
# pass
# else:
# if board[row+j][col+j]!='.' and board[row+j][col+j]==com:
# return False
# for j in range(-row,0):
# if row+j<0 or row+j>=9 or col-j<0 or col-j>=9:
# pass
# else:
# if board[row+j][col+j]!='.' and board[row+j][col-j]==com:
# return False
# for j in range(1,9-row):
# if row+j<0 or row+j>=9 or col-j<0 or col-j>=9:
# pass
# else:
# if board[row+j][col+j]!='.' and board[row+j][col-j]==com:
# return False
for j in range(0,9):
if j==col:continue
if board[row][j]!='.' and board[row][j]==com:
return False
for j in range(0, 9):
if j == row:
continue
if board[j][col] != '.' and board[j][col] == com:
return False
return True
for i in range(9):
for j in range(9):
if board[i][j] != '.':
if not check(i, j):
return False
return True
if __name__ == "__main__":
x = Solution()
print(x.isValidSudoku(
[
["7", ".", ".", ".", "4", ".", ".", ".", "."],
[".", ".", ".", "8", "6", "5", ".", ".", "."],
[".", "1", ".", "2", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", "9", ".", ".", "."],
[".", ".", ".", ".", "5", ".", "5", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", "2", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."]]
))
|
from typing import List
class Solution:
def removeInvalidParentheses(self, s: str) -> List[str]:
def isvaild(s:str):
count=0
for i in s:
if i=='(':
count+=1
elif i==')':
count-=1
if count<0:
return False
if count==0:
return True
return False
if isvaild(s):
return [s]
level={s}
while 1:
vaild=list(filter(isvaild,level))
if vaild : return vaild
nextlevel=set()
for item in level:
for i in range(len(item)):
if item[i] in "()":
nextlevel.add(item[:i]+item[i+1:])
level= nextlevel
if __name__ == "__main__":
x=Solution()
s=x.removeInvalidParentheses("")
print(s) |
help(open) #справка по работе функции open()
f = open("files/Толстой.txt", mode="rb") #открыть файл Толстой.txt, лежащий в папке files, лежащей в одной папке с питоновским файлом
f.read(20) #считать первые 20 байт
data = open("files/Толстой.txt", mode="rb").read() #считать файл
print(type(data)) #узнать тип перменной data (он будет списком байтов)
print(data[19]) #вывести значение 20-го байта файла
print("ab\n12")
print(r"ab\n12")
#сравните работу программы с r и без него
f = open("files/Толстой.txt", mode="rb")
f.read(20)
print(f.name)
print(f.readable())
print(f.tell())
print(f.writable())
print(f.seekable())
print(f.mode)
f = open("files/Толстой.txt", encoding="utf-8")
print(f.read(100))
print(f.tell())
print(f.seek(1245))
print(f.read(100))
print(f.tell())
print(f.seek(1246))
print(f.read(1))
f = open("files/Толстой.txt", encoding="utf8")
data = f.read()
print('Type: %s, length: %d' % (type(data), len(data)))
f.close()
f = open("files/Толстой.txt", encoding="utf8")
for i in range(7):
print(f.readline(), end="")
f.close()
#считать все строки файла
f = open("files/Толстой.txt", encoding="utf8")
lines = f.readlines()
print('Type: %s, length: %d' % (type(lines), len(lines)))
print(lines[10])
f.close()
f = open("files/Толстой.txt", encoding="utf8")
for number, line in enumerate(f):
print(line)
if number > 8:
break
f.close()
#записать в файл example.txt значения синусов для чисел 0, 1, ..., 9 с двумя знаками после запятой
from math import sin
f = open("files/example2.txt", 'w')
for i in range(10):
print("%0.2f" % sin(i), file=f)
f.close()
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QLineEdit, QLabel, QFileDialog
from PyQt5.QtGui import QPixmap
import sys
SCREEN_SIZE = [400, 400]
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(400, 400, *SCREEN_SIZE)
self.setWindowTitle('Отображение картинки')
## Изображение
fname = QFileDialog.getOpenFileName(self, 'Выбрать картинку', '', "Картинка(*.png)")[0]
self.pixmap = QPixmap(fname)
self.image = QLabel(self)
self.image.move(80, 60)
self.image.resize(250, 250)
self.image.setPixmap(self.pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec())
=================================================
from PyQt5.QtGui import QPen
from math import pi, cos, sin
from PyQt5.QtCore import Qt
import sys
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtGui import QPainter, QColor
SCREEN_SIZE = [600, 600]
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, *SCREEN_SIZE)
self.setWindowTitle('Рисование')
self.show()
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
self.drawStar(qp)
qp.end()
def drawFlag(self,qp):
qp.setBrush(QColor(255, 255, 255))
qp.drawRect(30, 30, 480, 120)
qp.setBrush(QColor(0, 0, 255))
qp.drawRect(30, 150, 480, 120)
qp.setBrush(QColor(255, 0, 0))
qp.drawRect(30, 270, 480, 120)
def xs(self,x):
return x + SCREEN_SIZE[0] // 2
def ys(self,y):
return SCREEN_SIZE[1] // 2 - y
def drawStar(self,qp):
# Задаем длину стороны и количество углов
RAD = 100
p = 5
# Считаем координаты и переводим их в экранные
nodes = [(RAD * cos(i * 2 * pi / p), RAD * sin(i * 2 * pi / p)) for i in range(p)]
nodes2 = [(self.xs(node[0]), self.ys(node[1])) for node in nodes]
# Рисуем пятиугольник
for i in range(-1, len(nodes2) - 1):
qp.drawLine(*nodes2[i], *nodes2[i + 1])
# Изменяем цвет линии
pen = QPen(Qt.red, 2)
qp.setPen(pen)
# Рисуем звезду
for i in range(-2, len(nodes2) - 2):
qp.drawLine(*nodes2[i], *nodes2[i + 2])
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
============================================
from PIL import Image, ImageFilter
def motion_blur(n):
im = Image.open('image.jpg')
im = im.transpose(Image.ROTATE_270)
im = im.filter(ImageFilter.GaussianBlur(n))
im.save('res.jpg')
|
import numpy as np
# -------------------
# SELECTION OPERATORS
# -------------------
class Selection_Proportionate:
'''
Proportionate selection operator
***WARNING***: This operator will NOT give the expected
results cases where fitness values can be negative.
Another operator must be used in this case.
Possible implementation TRICK:
When you have negative values, you could try to find the smallest
fitness value in your population and add its opposite to every
value. This way you will no longer have negative values, while
the differences between fitness values will remain the same.
'''
pass
class Selection_Stochastic_Universal_Sampling:
pass
class Selection_Ranking:
'''
Ranking selection operator
'''
pass
class Selection_Fitness_Scaling:
pass
class Selection_Tournament:
'''
Tournament selection operator:
1. Random uniform select of K individuals
2. Select the fittest of these K individuals
3. Repeat 1., 2. until the reach the desired number of individuals
'''
def __init__(self, selection_params):
'''
Parameters
----------
selection_parameters includes:
- selective pressure K, used to select number of individual
per tournament. The higher K, the more probability the best
individuals will be selected (-> loss of diversity).
A recommended value is 2.
'''
self.K = selection_params["K"]
def select(self, population):
'''
Parameters
----------
- The current population instance
Return
------
- a numpy array, selection of individuals to serve for reproduction
(crossover)
'''
selection_idxs = []
for _ in range(population.size):
# Select K individuals by index
idxs = np.random.choice(range(population.size),
size=self.K,
replace=False)
# Get the best individual (best fitness) by argsort-ing the
# fitness vector (population.fitness)
# we are expecting minimisation problem, best fitness is index 0
best_idx = idxs[np.argsort(population.fitness[idxs])[0]]
selection_idxs.append(best_idx)
# Return the selected individuals
return(population.individuals[np.array(selection_idxs)])
# -------------------
# CROSSOVER OPERATORS
# -------------------
class Crossover_Ordered:
'''
Ordered crossover operator:
Loop for nb_offsprings to be generated
1. Select (uniform random) two parents from the entire population
2. Roll a (uniform!) dice ! If probability is < than
crossover_proba then perform crossover.
Else the two parents are kept as if for the next generation.
3. Select (uniform random) two crossover points that defines a
sequence of genes to crossover
4. Copy sequence from parent1 to child2 and parent2 to child1
5. Complete child1 sequence with parent1, child2 with parent2
'''
def __init__(self, crossover_params):
'''
- the crossover probability
- the width of the sequence of genes to crossover
'''
self.crossover_proba = crossover_params["crossover_proba"]
self.max_width = crossover_params["sequence_max_width"]
def crossover(self, parents, nb_offsprings):
'''
Perform the crossover
Parameters
----------
- all parents that have been selected for crossover
as numpy ndarray
- the number of offsprings to generate. That depends on the
ratio of elite individuals that will be kept for next
generation.
Return
------
- the offsprings as a numpy ndarray
'''
rng = np.random.default_rng()
parents_size = parents.shape[0]
dim = parents.shape[1]
current_nb_offsprings = 0
while current_nb_offsprings < nb_offsprings:
# randomly (uniform) select two parents
# by selecting two indexes from the
# parents array (with no repetition)
parents_idx = rng.choice(parents_size, size=2, replace=False)
parent1 = parents[parents_idx][0]
parent2 = parents[parents_idx][1]
# Probability of performing crossover
# if < self.crossover_proba perform cross over
# for these 2 parents
if rng.uniform() < self.crossover_proba:
# randomly (uniform) select two crossover points
# distant within [2, self.max_witdh]
invalid_sequence = True
while invalid_sequence:
seq = np.sort(rng.choice(dim, size=2, replace=False))
if ((seq[1] - seq[0]) <= self.max_width) and\
((seq[1] - seq[0]) > 1):
invalid_sequence = False
# initialise a child1, child2 array
child1 = -1*np.ones(dim, dtype=np.int32)
child2 = -1*np.ones(dim, dtype=np.int32)
# copy the genes between crossover points
# from parents1 to child2 and parents2 to child1
child1[seq[0]:seq[1]] = parent2[seq[0]:seq[1]]
child2[seq[0]:seq[1]] = parent1[seq[0]:seq[1]]
# complete the child1 with parent1 and child2 with
# parent2
child1 = self.complete_sequence(child1, parent1, seq, dim)
child2 = self.complete_sequence(child2, parent2, seq, dim)
# else, we keep parents as-is for next generation
else:
child1 = np.copy(parent1)
child2 = np.copy(parent2)
# adding children to the array of offsprings
if current_nb_offsprings == 0:
offsprings = child1
offsprings = np.concatenate((offsprings, child2), axis=0)
current_nb_offsprings = current_nb_offsprings + 2
elif current_nb_offsprings <= (nb_offsprings - 2):
offsprings = np.concatenate((offsprings, child1), axis=0)
offsprings = np.concatenate((offsprings, child2), axis=0)
current_nb_offsprings = current_nb_offsprings + 2
else:
offsprings = np.concatenate((offsprings, child1), axis=0)
current_nb_offsprings = current_nb_offsprings + 1
# reshape offsprings to a (self.nb_offsprings, dimension)
# array
offsprings = offsprings.reshape(-1, dim)
return(offsprings)
def complete_sequence(self, child, parent, cx_point, d):
idx_child = idx_parent = cx_point[1]
not_complete = True
# complete upper range of the sequence first
while not_complete:
# for idx in range(cx_point[1], dim):
if parent[idx_parent] not in child:
child[idx_child] = parent[idx_parent]
if idx_child == (d-1):
idx_child = 0
else:
idx_child = idx_child + 1
if idx_parent == (d-1):
idx_parent = 0
else:
idx_parent = idx_parent + 1
# testing if sequence is complete
# i.e. idx_child = cx_point[0]
if idx_child == cx_point[0]:
not_complete = False
return(child)
# ------------------
# MUTATION OPERATORS
# ------------------
class Mutation_Swap:
'''
The Swap Mutation operator: Two genes are randomly selected
and swapped together.
'''
def __init__(self, mutation_params):
'''
Parameters:
-----------
- the mutation probability
'''
self.mutation_proba = mutation_params["mutation_proba"]
def mutate(self, offsprings):
'''
Perform the swap mutation for all offsprings
1. roll a (uniform!) dice ! If probability is < than
mutation_proba then perform mutation.
2. select (random uniform) two genes (indices)
3. swap them
Parameters
----------
- the offsprings (as a numpy array) on which to apply
the mutation
Return
------
- the modified offsprings (althought not necessary as mutation
is done inplace)
'''
rng = np.random.default_rng()
nb_offsprings = offsprings.shape[0]
dim = offsprings.shape[1]
for i in range(nb_offsprings):
# Probability of performing mutation
# if < self.mutation_proba perform mutation
# else NO mutation for this offspring
if rng.uniform() < self.mutation_proba:
idxs = rng.choice(dim, size=2, replace=False)
temp = offsprings[i][idxs[0]]
offsprings[i][idxs[0]] = offsprings[i][idxs[1]]
offsprings[i][idxs[1]] = temp
return(offsprings)
class Mutation_Inversion:
'''
The Inversion Mutation operator: A sequence of genes is
randomly selected and inversed
'''
def __init__(self, mutation_params):
'''
Parameters:
-----------
- the mutation probability
- the width of the sequence of genes on which to apply
inversion
'''
self.mutation_proba = mutation_params["mutation_proba"]
self.max_width = mutation_params["sequence_max_width"]
def mutate(self, offsprings):
'''
Perform the inversion mutation for all offsprings
1. roll a (uniform!) dice ! If probability is < than
mutation_proba then perform mutation.
2. Select (random uniform) a sequence of genes to inverse
3. Inverse them
Parameters
----------
- The offsprings (as a numpy array) on which to apply
the mutation
Return
------
- the modified offsprings (althought not necessary as mutation
is done inplace)
'''
rng = np.random.default_rng()
nb_offsprings = offsprings.shape[0]
dim = offsprings.shape[1]
for i in range(nb_offsprings):
# !!!
# By ordering the random choice of index, we somehow
# prevent inversion happening on the array bounds,
# i.e. inversion on say indexes 8.9.0.1 -> 1.0.9.8
# will never happen.
# The effect on the quality of this operator is unknown.
# In theory, it will be better to also allow these
# types of inversion, i.e. considering the array as a
# circular array
# Probability of performing mutation
# if < self.mutation_proba perform mutation
# else NO mutation for this offspring
if rng.uniform() < self.mutation_proba:
# Find a sequence of gene to inverse
invalid_sequence = True
while invalid_sequence:
seq = np.sort(rng.choice(dim, size=2, replace=False))
if ((seq[1] - seq[0]) <= self.max_width) and\
((seq[1] - seq[0]) > 1):
invalid_sequence = False
# Inverse the sequence inplace
offsprings[i][seq[0]:seq[1]] = \
offsprings[i][seq[0]:seq[1]][::-1]
return(offsprings)
def mutate_x(self, offsprings):
rng = np.random.default_rng()
nb_offsprings = offsprings.shape[0]
dim = offsprings.shape[1]
for i in range(nb_offsprings):
# Probability of performing mutation
# if < self.mutation_proba perform mutation
# else NO mutation for this offspring
if rng.uniform() < self.mutation_proba:
# Find a sequence of gene to inverse
invalid_sequence = True
while invalid_sequence:
seq = rng.choice(dim, size=2, replace=False)
g1 = seq[0]
g2 = seq[1]
if (abs(g1 - g2) <= self.max_width) and\
(abs(g1 - g2) > 1):
invalid_sequence = False
# if gene1 position is > gene2 position, we need
# to build the sequence to inverse first, that is
# offspring[g1:] + oggspring[:g2]
# then inverse it and insert/replace in offspring
# at the correct position
if g1 > g2:
# Build the reverse sequence
seq1 = offsprings[i][g1:]
seq2 = offsprings[i][:g2]
seq_to_reverse = np.concatenate((seq1, seq2))
seq1_size = seq1.shape[0]
# insert at the correct position
offsprings[i][g1:] = seq_to_reverse[::-1][:seq1_size]
offsprings[i][:g2] = seq_to_reverse[::-1][seq1_size:]
else:
# Inverse the sequence inplace
offsprings[i][g1:g2] = offsprings[i][g1:g2][::-1]
return(offsprings)
class Mutation_Scramble:
'''
The Scramble (or Shuffle) Mutation operator: A sequence of genes
is randomly selected and shuffled
'''
def __init__(self, mutation_params):
'''
Parameters:
-----------
- the mutation probability
- the width of the sequence of genes on which to apply
shuffling
'''
self.mutation_proba = mutation_params["mutation_proba"]
self.max_width = mutation_params["sequence_max_width"]
def mutate(self, offsprings):
'''
Perform the scramble mutation for all offsprings
1. roll a (uniform!) dice ! If probability is < than
mutation_proba then perform mutation.
2. Select (random uniform) a sequence of genes to scramble
3. shuffle them
Parameters
----------
- The offsprings (as a numpy array) on which to apply
the mutation
Return
------
- the modified offsprings (althought not necessary as mutation
is done inplace)
'''
rng = np.random.default_rng()
nb_offsprings = offsprings.shape[0]
dim = offsprings.shape[1]
for i in range(nb_offsprings):
# !!!
# Similarly to the Mutation Inversion operator,
# by ordering the random choice of index, we somehow
# prevent shuffling happening on the array bounds,
# i.e. shuffling on say indexes 8.9.0.1 -> 9.1.0.8
# will never happen.
# The effect on the quality of this operator is unknown.
# In theory, it will be better to also allow these
# types of shuffling, i.e. considering the array as a
# circular array
# Probability of performing mutation
# if < self.mutation_proba perform mutation
# else NO mutation for this offspring
if rng.uniform() < self.mutation_proba:
# Find a sequence of gene to shuffle
invalid_sequence = True
while invalid_sequence:
seq = np.sort(rng.choice(dim, size=2, replace=False))
if ((seq[1] - seq[0]) <= self.max_width) and\
((seq[1] - seq[0]) > 1):
invalid_sequence = False
# Shuffle the sequence inplace
rng.shuffle(offsprings[i][seq[0]:seq[1]])
return(offsprings)
def mutate_x(self, offsprings):
'''
Perform the scramble mutation for all offsprings
1. roll a (uniform!) dice ! If probability is < than
mutation_proba then perform mutation.
2. Select (random uniform) a sequence of genes to scramble
3. shuffle them
Parameters
----------
- The offsprings (as a numpy array) on which to apply
the mutation
Return
------
- the modified offsprings (althought not necessary as mutation
is done inplace)
'''
rng = np.random.default_rng()
nb_offsprings = offsprings.shape[0]
dim = offsprings.shape[1]
for i in range(nb_offsprings):
# !!!
# Similarly to the Mutation Inversion operator,
# by ordering the random choice of index, we somehow
# prevent shuffling happening on the array bounds,
# i.e. shuffling on say indexes 8.9.0.1 -> 9.1.0.8
# will never happen.
# The effect on the quality of this operator is unknown.
# In theory, it will be better to also allow these
# types of shuffling, i.e. considering the array as a
# circular array
# Probability of performing mutation
# if < self.mutation_proba perform mutation
# else NO mutation for this offspring
if rng.uniform() < self.mutation_proba:
# Find a sequence of gene to shuffle
invalid_sequence = True
while invalid_sequence:
seq = np.sort(rng.choice(dim, size=2, replace=False))
if ((seq[1] - seq[0]) <= self.max_width) and\
((seq[1] - seq[0]) > 1):
invalid_sequence = False
# Shuffle the sequence inplace
rng.shuffle(offsprings[i][seq[0]:seq[1]])
return(offsprings)
|
import unittest
from morse_translator.translator import Translator, TranslationException
from morse_translator.dictionary import Dictionary
class TranslatorTests(unittest.TestCase):
def setUp(self):
self.translator = Translator()
def test_constructor(self):
"""
Ensure the constructor returns non-null object of type Translator.
And its property, dictionary, is non-null and of type Dictionary.
"""
self.assertIsNotNone(self.translator)
self.assertIsInstance(self.translator, Translator)
self.assertIsNotNone(self.translator.dictionary)
self.assertIsInstance(self.translator.dictionary, Dictionary)
def test_to_morse_with_valid_input(self):
"""
Ensure to_morse is evaluating correctly with valid inputs.
Fail if an error is raised.
"""
well_formed_input = "Hello world"
expected_result = ". . . . . . _ _ _ . _ _ _ _ _ _ . _ _ _ _ _ . _ . . _ _ _ _ . ."
with self.assertRaises(TranslationException):
result = self.translator.to_morse(well_formed_input)
self.assertEquals(expected_result, result)
def test_to_morse_with_invalid_input(self):
"""
Ensure to_morse throws an error with invalid inputs.
Fail if no error was raised.
"""
invalid_input = "H! th#r3"
with self.assertRaises(TranslationException):
self.translator.to_morse(invalid_input)
def test_exception_attributes(self):
"""
Ensure our error handling is functioning as intended.
It should contain the first character that execution failed with.
"""
invalid_input = "H! th#r3"
with self.assertRaises(TranslationException) as e:
self.translator.to_morse(invalid_input)
exception = e.exception
self.assertEquals(exception.expr, invalid_input)
self.assertEquals(exception.entry, invalid_input[1])
self.assertEquals(exception.msg, "Key not found.")
def main():
unittest.main()
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env python3
# Created by: Lily Liu
# Created on: Oct 2021
# This program will convert °C to °F
def fahrenheit():
# This function will convert °C to °F
# input
user_temp = input("Enter a temperature (°C) : ")
# process & output
try:
user_temp = int(user_temp)
f_temp = round((9 / 5) * user_temp + 32, 2)
print("{0}°C is equal to {1}°F".format(user_temp, f_temp))
except (Exception):
print("Invalid input")
def main():
# call functions
fahrenheit()
print("\nDone.")
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 12:21:55 2020
@author: nmbice
"""
from fol_syntax_semantics import parse, tokenize, evaluate, Model
import re
import string
#model = Model({1,2,3})
#model.interp = {'L': {(1,2), (2,1), (3,1)}, 'E': {2}, 'P': {}, 'G': {(2,1), (3,1), (3,2)}, '=': {(1,1), (2,2), (3,3)}, \
# '1': 1, '2': 2, '3': 3, 'N': {1,2,3}}
#print (evaluate('(Ux=(x,x) ^ (XyG(2,y) > =(2,2)))', model))
#this is the evaluator program, which requests a string from the user as input and either outputs the
#truth-value of the corresponding logical formula or constructs a model
def evaluator():
while True:
e = input('%')
if e == 'model':
print ('Please specify the domain of your model, with objects separated by commas.')
d = input('%')
if len(d) == 0:
print ('A model must have a non-empty domain.')
pass
else:
dom = d.split(',')
model = Model(set([eval(x) for x in dom]))
interpreting = True
while interpreting == True:
print ('Please specify an expression to interpret. Type "done" when there are no more expressions to interpret.')
exp = input('%')
if exp == 'done':
break
print ('Please specify its interpretation, using commas to separate elements.')
i = input('%')
r = re.compile(r'(?:[^,(]|\([^)]*\))+')
inter = r.findall(i)
if (len(exp) == 1 and (exp.islower() or exp in string.digits)) or \
(len(exp) > 1 and (exp[0].islower() or exp[0] in string.digits)):
model.interp[exp] = eval(inter[0])
else:
model.interp[exp] = set([eval(x) for x in inter])
print('Current variables are {}. Would you like to add additional variables? Type "yes" or "no".'.format(model.all_vars))
v = input('%')
if v == 'yes':
print ('Input new variables, separated by commas.')
new_vars = input('%')
if new_vars == '':
pass
new_vars = new_vars.split(',')
for var in new_vars:
model.all_vars.add(var)
#print (model.domain, model.interp, model.all_vars)
else:
pass
elif e == 'exit':
break
elif e == 'evaluate':
#here we use our parser to determine the appropriate syntax tree and then run its eval method and print
#the truth-value of the inputted sentence relative to the model
print ('Please input the sentence to be evaluated relative to the specified model.')
s = input('%')
try:
print (str(parse(tokenize(s))) + ': ', evaluate(s, model))
#if the user inputted an improper string, they will get an error message and the program will continue to run
except AttributeError:
print ('That is not a well-formed sentence.')
except UnboundLocalError:
print ('Model has not been defined.')
else:
print ('Please input "model", "evaluate", or "exit".')
pass
if __name__ == '__main__':
evaluator()
|
"""
Script for importing students by course in Canvas.
"""
from security import canvas_key
import csv
import requests
from datetime import datetime
def course_students(course_id: int):
"""
Takes in a course's ID, and returns a list of students in the course, containing dictionaries with their name and
Quercus ID.
"""
url = 'https://q.utoronto.ca/api/v1/courses/' + str(course_id) + '/students' + '?access_token=' + canvas_key
r = requests.get(url)
convert = r.json()
trimmed_list = []
for student in convert:
trimmed_dict = {}
trimmed_dict["sortable_name"] = student["sortable_name"]
trimmed_dict["id"] = student["id"]
trimmed_list.append(trimmed_dict)
return trimmed_list
def student_list_to_csv(student_list, file_name: str):
"""
Takes in list of students as input, and writes to a CSV file with given name.
(If the file doesn't exist, it creates it). CSV file contains info on students.
"""
mydate = datetime.now()
formatteddate = mydate.strftime("%b%d%Y")
dated_file = file_name + "_" + formatteddate
file = dated_file + '.csv'
with open(file, mode='w') as student_file:
student_writer = csv.writer(student_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
student_writer.writerow(["Full Name", "First Name", "Last Name", "Quercus ID"])
for student in student_list:
student_name = student["sortable_name"]
split_name = student_name.split(", ")
last_name, first_name = split_name[0], split_name[1]
student_id = student["id"]
student_writer.writerow([student_name, first_name, last_name, student_id])
def course_students_csv(course_id: int, file_name: str):
"""
Takes in a the ID of a course as an int, and returns a CSV file with file_name as desired name,
containing information about the students enrolled in the course:
Student's full name, first name, last name, and Quercus ID.
"""
student_list = course_students(course_id)
student_list_to_csv(student_list, file_name)
course_students_csv(69069, "csc258test")
|
import numpy as np
import math
# import functools
class Geometry:
@staticmethod
def distance(point): # shape=(2, ) 支持非ndarray
return np.hypot(*point)
@staticmethod
def distances(points): # shape=(n, 2) or (2, ) 必须为ndarray
return np.hypot(*points.T)
@classmethod
def distance_p2seg(cls, p, p1, p2):
"""点到线段的最短距离"""
p2p1, pp1 = p2 - p1, p - p1
d = np.dot(p2p1, pp1)
if d <= 0.: return cls.distance(pp1)
d2 = np.dot(p2p1, p2p1)
if d >= d2: return cls.distance(p - p2)
return cls.distance(pp1 - p2p1 * d / d2)
@classmethod
def distance_p2arc(cls, p, center, radius, start, extent):
"""点到圆弧的最短距离,类比点到线段的距离"""
# 中间区域的点,在pp1之上,在pp2之下,p1为圆弧起点,p2为圆弧终点,逆时针
assert radius > 0.
# 端点
p1 = center + radius*np.array([np.cos(start), np.sin(start)])
end = start + extent
p2 = center + radius*np.array([np.cos(end), np.sin(end)])
if extent < 0.: # 顺时针,调整为逆时针
p1, p2 = p2, p1
# print('p1: {}, p2: {}'.format(p1, p2))
cp1 = p1 - center
cp2 = p2 - center
cp = p - center
cross1 = np.cross(cp1, cp)
cross2 = np.cross(cp, cp2)
if cross1 > 0. and cross2 > 0.: # 中间区域
dis = abs(radius-cls.distance(cp))
else:
dis1 = cls.distance(p-p1)
dis2 = cls.distance(p-p2)
dis = min(dis1, dis2)
# print(cross1, cross2)
return dis
class Trajectory:
"""过度封装会导致无法批量运算/矩阵运算"""
LINE, ARC = 0, 1
def __init__(self):
self.traj_type = None
self.traj = None
def line2(self, start_pos, end_pos):
self.traj_type = self.LINE
self.traj = start_pos, end_pos
def line(self, start_pos, delta_pos):
self.traj_type = self.LINE
self.traj = start_pos, start_pos+delta_pos
def arc(self, start_pos, start_dir, radius, delta_dir):
"""
delta_dir: 弧以顺时针为正,即右转
radius: 有向半径,逆时针为负
"""
self.traj_type = self.ARC
center = start_pos + radius * np.array([np.sin(start_dir), -np.cos(start_dir)])
start = start_dir + math.pi / 2
if radius < 0.: start -= math.pi
extent = -delta_dir
self.traj = center, abs(radius), start, extent
def __call__(self):
return self.traj
|
# Crie um pacote chamado utilidadesCeV que tenha dois módulos internos chamados moeda e dado
# Transfira todas as funções utilizadas nos DESAFIOS 107, 108 e 109 para o primeiro pacote e mantenha tudo funcionando
from utilitiescev import currency
price = float(input('Digite o preço: R$ '))
rateOfIncrease = int(input('Digite a taxa de aumento: '))
rateOfDecrease = int(input('Digite a taxa de redução: '))
currency.resume(price, rateOfIncrease, rateOfDecrease)
|
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor de seu aumento
# Para salários superiores a R$ 1.250,00, calcule um aumento de 10%
# Para os inferiores ou iguais o aumento é de R$ 15%
currentSalary = float(input('Qual é o salário do funcionário? R$ '))
if currentSalary > 1250:
percentageIncrease = 10
else:
percentageIncrease = 15
newSalary = currentSalary + (currentSalary * percentageIncrease / 100)
print('Quem ganhava R$ {:.2f}, com aumento de {}%, passa a ganhar R$ {:.2f} agora' .format(currentSalary, percentageIncrease, newSalary))
|
# Faça um programa que ajude um jogador da MEGA SENA a criar palpites
# O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta
# Resolução proposta pelo professor
# from random import randint
# from time import sleep
#
# list = []
# games = []
# print('-' * 30)
# print(f'{"JOGA NA MEGA SENA":^30}')
# print('-' * 30)
# quantity = int(input('Quantos jogos você quer que eu sorteie? '))
# total = 1
# while total <= quantity:
# counter = 0
# while True:
# num = randint(1, 60)
# if num not in list:
# list.append(num)
# counter += 1
# if counter >= 6:
# break
# list.sort()
# games.append(list[:])
# list.clear()
# total += 1
# print('-=' * 4, f' SORTEANDO {quantity} JOGOS ', '-=' * 4)
# for i, l in enumerate(games):
# print(f'Jogo {i + 1}: {l}')
# sleep(1)
# print('-=' * 5, ' < BOA SORTE! > ', '-=' * 5)
from time import sleep
from random import sample
numbersMegaSena = []
gamesMegaSena = []
for number in range(1, 61):
numbersMegaSena.append(number)
print('-' * 30)
print(f'{"JOGA NA MEGA SENA":^30}')
print('-' * 30)
quantityGames = int(input('Quantos jogos você quer que eu sorteie? '))
print()
print('-=' * 4, f' SORTEANDO {quantityGames:2} JOGOS ', '-=' * 4)
for i in range(1, quantityGames + 1):
gamesMegaSena.append(sample(numbersMegaSena, 6))
print(f'Jogo {i}: {sorted(gamesMegaSena[i - 1])}')
sleep(1)
print('-=' * 5, ' < BOA SORTE! > ', '-=' * 5)
|
def increase(value, rate):
increased = value + (value * rate / 100)
return increased
def decrease(value, rate):
decreased = value - (value * rate / 100)
return decreased
def double(value):
doubled = value * 2
return doubled
def half(value):
halved = value / 2
return halved
|
# Crie um programa que vai ler vários números e colocar em uma lista
# Depois disso, crie duas listas extras que vão conter apenas os valores pares e o valores ímpares digitados, respectivamente
# Ao final, mostre o conteúdo das três listas geradas
listFull = []
listPairs = []
listOdd = []
while True:
proceed = ' '
listFull.append(int(input('Digite um número: ')))
while proceed not in 'SN':
proceed = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
if proceed == 'N':
break
for number in listFull:
if number % 2 == 0:
listPairs.append(number)
else:
listOdd.append(number)
print()
print('-=' * 30)
print(f'A lista completa é {listFull}')
print(f'A lista de pares é {listPairs}')
print(f'A lista de ímpares é {listOdd}')
|
# Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu preço normal e condição de pagamento:
# - À vista dinheiro/cheque: 10% de desconto
# - À vista no cartão: 5% de desconto
# - Em até 2x no cartão: preço normal
# - 3x ou mais no cartão: 20% de juros
from sys import exit
colors = {
'clear': '\033[m',
'txtRedBold': '\033[1:31m',
'txtYellowBold': '\033[1:33m',
'txtBlueBold': '\033[1:34m',
}
print('{}' .format(colors['txtYellowBold']) + '{:=^40}' .format(' LOJAS LIMA ') + '{}' .format(colors['clear']) + '\n')
purchasePrice = float(input('Preço das compras: R$ '))
print('\n{}' .format(colors['txtBlueBold']) + '{:^30}' .format('FORMAS DE PAGAMENTO:') + '{}' .format(colors['clear']))
print('[1] À vista no dinheiro/cheque')
print('[2] À vista no cartão')
print('[3] 2x no cartão')
print('[4] 3x ou mais no cartão')
paymentMethod = int(input('\nEscolha uma opção: '))
if paymentMethod == 1:
discountRate = 10
finalPrice = purchasePrice - (purchasePrice / 100 * discountRate)
print('\nCom o pagamento à vista no dinheiro/cheque, ganhou {}% de desconto' .format(discountRate), end='')
elif paymentMethod == 2:
discountRate = 5
finalPrice = purchasePrice - (purchasePrice / 100 * discountRate)
print('\nCom o pagamento à vista no cartão, ganhou {}% de desconto' .format(discountRate), end='')
elif paymentMethod == 3:
finalPrice = purchasePrice
parcelQuantity = 2
parcelValue = finalPrice / parcelQuantity
print('\nSua compra será parcelada em {}x de R$ {:.2f} SEM JUROS' .format(parcelQuantity, parcelValue), end='')
elif paymentMethod == 4:
increaseRate = 20
finalPrice = purchasePrice + (purchasePrice / 100 * increaseRate)
parcelQuantity = int(input('\nQuantas parcelas? '))
parcelValue = finalPrice / parcelQuantity
print('\nSua compra será parcelada em {}x de R$ {:.2f} COM JUROS' .format(parcelQuantity, parcelValue), end='')
else:
print('\n{}Opção de pagamento inválida! Tente novamente.{}' .format(colors['txtRedBold'], colors['clear']))
exit(0)
print('\nSua compra de R$ {:.2f} vai custar R$ {:.2f} no final' .format(purchasePrice, finalPrice))
|
# Crie um programa que leia o nome e o preço de vários produtos
# O programa deverá perguntar se o usuário vai continuar
# No final, mostre:
# A) Qual é o total gasto na compra
# B) Quantos produtos custam mais de R$ 1000
# C) Qual é o nome do produto mais barato
colors = {
'clear': '\033[m',
'txtGreenNormal': '\033[0:32m',
'txtBlueNormal': '\033[0:34m',
'txtYellowBold': '\033[1:33m',
}
print('{}' .format(colors['txtYellowBold']))
print('-' * 40)
print('{:^40}' .format('LOJA SUPER BARATÃO'))
print('-' * 40)
print('{}' .format(colors['clear']))
purchaseSum = counterProducts = counterProductsOverThousand = 0
productNameCheapest = ' '
while True:
proceed = ' '
productName = str(input('Nome do Produto: ')).strip()
price = float(input('Preço: R$ '))
counterProducts += 1
purchaseSum += price
if counterProducts == 1 or price < priceLowest:
priceLowest = price
productNameCheapest = productName
if price > 1000:
counterProductsOverThousand += 1
while proceed not in 'SN':
proceed = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
if proceed == 'N':
break
print('-' * 36)
print('{}' .format(colors['txtYellowBold']))
print('{:-^40}' .format(' FIM DO PROGRAMA '))
print('{}' .format(colors['clear']))
print(f'O total da compra foi {colors.get("txtGreenNormal")}R$ {purchaseSum:.2f}{colors.get("clear")}')
if counterProductsOverThousand == 0:
print('Não há produto custando mais de R$ 1000.00')
elif counterProductsOverThousand == 1:
print(f'Temos {counterProductsOverThousand} produto custando mais de R$ 1000.00')
else:
print(f'Temos {counterProductsOverThousand} produtos custando mais de R$ 1000.00')
print(f'O produto mais barato foi {colors.get("txtBlueNormal")}{productNameCheapest}{colors.get("clear")} que custa R$ {priceLowest:.2f}')
|
# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas
# No final do programa, mostre:
# A média de idade do grupo
# Qual é o nome do homem mais velho
# Quantas mulheres tem menos de 20 anos
from sys import exit
counterAge = 0
olderManAge = 0
counterWoman = 0
for i in range(1, 5):
print('\n----- {}ª PESSOA -----' .format(i))
name = str(input('Nome: ')).strip()
age = int(input('Idade: '))
sex = str(input('Sexo [M/F]: ')).strip().upper()
counterAge += age
if sex != 'M' and sex != 'F':
print('\nSexo informado é inválido! Tente novamente.')
exit(0)
if sex == 'M':
if age > olderManAge:
olderManAge = age
olderManName = name
if sex == 'F':
if age < 20:
counterWoman += 1
averageAge = counterAge / 4
print('\nA média de idade do grupo é de {} anos' .format(averageAge))
if olderManAge == 0:
print('Não há homem no grupo informado')
else:
print('O homem mais velho tem {} anos e se chama {}' .format(olderManAge, olderManName))
if counterWoman == 0:
print('Não há mulher com menos de 20 anos' .format(counterWoman))
elif counterWoman == 1:
print('Ao todo há {} mulher com menos de 20 anos' .format(counterWoman))
else:
print('Ao todo há {} mulheres com menos de 20 anos' .format(counterWoman))
|
# Refaça o DESAFIO 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
# - Equilátero: todos os lados iguais
# - Isósceles: dois lados iguais
# - Escaleno: todos os lados diferentes
print('-=' * 12)
print('Analisador de Triângulos')
print('-=' * 12)
n1 = float(input('Primeiro segmento: '))
n2 = float(input('Segundo segmento: '))
n3 = float(input('Terceiro segmento: '))
if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2:
print('\nOs segmentos acima PODEM formar um triângulo ', end='')
if n1 == n2 == n3:
print('EQUILÁTERO')
elif n1 != n2 != n3 != n1:
print('ESCALENO')
else:
print('ISÓSCELES')
else:
print('\nOs segmentos acima NÃO PODEM formar triângulo')
|
# Faça um programa que leia uma frase pelo teclado e mostre:
# Quantas vezes aparece a letra "A"
# Em que posição ela aparece a primeira vez
# Em que posição ela aparece a última vez
phrase = str(input('Digite uma frase: ')).strip()
print('Na frase digitada, a letra "A" aparece {} vezes' .format(phrase.upper().count('A')))
print('A primeira letra "A" aparece na posição {}' .format(phrase.upper().find('A') + 1))
print('A última letra "A" aparece na posição {}' .format(phrase.upper().rfind('A') + 1))
|
# Refaça o DESAFIO 009, mostrando a tabuada de um número que o usuário escolher, só que agora utilizando um laço for
n = int(input('Digite um número para ver sua tabuada: '))
print('\nTABUADA DE {}' .format(n))
for i in range(1, 11):
print('{} x {:>2} = {}' .format(n, i, (n * i)))
|
# Modifique as funções que foram criadas no DESAFIO 107 para que elas aceitem um parâmetro a mais, informando se o valor
# retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no DESAFIO 108
import currency
price = float(input('\nDigite o preço: R$ '))
print(f'A metade de {currency.currency(price)} é {currency.half(price, formatted=True)}')
print(f'O dobro de {currency.currency(price)} é {currency.double(price, True)}')
print(f'Aumentando 10%, temos {currency.increase(price, 10, formatted=True)}')
print(f'Reduzindo 13%, temos {currency.decrease(price, 13, True)}')
|
# Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e
# comprimento) e mostre a área do terreno
def area(width, length):
print(f'A área de um terreno {width}m x {length}m é de {width * length:.1f}m²')
print(' Controle de Terrenos')
print('-' * 22)
w = float(input('LARGURA (m): '))
l = float(input('COMPRIMENTO (m): '))
print()
area(w, l)
|
# Crie um programa que faça o computador jogar Jokenpô com você
from sys import exit
from time import sleep
from random import randint
options = ('PEDRA', 'PAPEL', 'TESOURA')
# Jogada do computador
numberRandom = randint(0, 2)
computerChoice = options[numberRandom]
# Jogada do jogador
print('''Suas opções:
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] TESOURA''')
numberChoice = int(input('\nQual é a sua jogada? '))
if numberChoice < 0 or numberChoice > 2:
print('\nJogada inválida! Tente novamente.')
exit(0)
playerChoice = options[numberChoice]
print('\nJO')
sleep(1)
print('KEN')
sleep(1)
print('PO!!!\n')
print('-=' * 12)
print('Computador jogou {}' .format(computerChoice))
print('Jogador jogou {}' .format(playerChoice))
print('-=' * 12)
# Verifica ganhador
if computerChoice == playerChoice:
print('\nEMPATE')
exit(0)
else:
if computerChoice == 'PEDRA':
if playerChoice == 'PAPEL':
winner = 'JOGADOR'
elif playerChoice == 'TESOURA':
winner = 'COMPUTADOR'
elif computerChoice == 'PAPEL':
if playerChoice == 'PEDRA':
winner = 'COMPUTADOR'
elif playerChoice == 'TESOURA':
winner = 'JOGADOR'
elif computerChoice == 'TESOURA':
if playerChoice == 'PEDRA':
winner = 'JOGADOR'
elif playerChoice == 'PAPEL':
winner = 'COMPUTADOR'
print('\n{} VENCE' .format(winner))
|
def sum_mul(choice, *args):
if choice == "sum":
result = 0
for i in args:
result=result+i
elif choice =="sub":
result = args[0]
for i in args[1:]:
result=result-i
elif choice == "mul":
result =1
for i in args:
result = result*i
elif choice == "div":
result = args[0]
for i in args[1:]:
result = result/i
return result
result4 = sum_mul('sum',1,2,3)
result1 = sum_mul('sub',1,2,3)
result2 = sum_mul('mul',1,2,3)
result3 = sum_mul('div',1,2,3)
print(result4)
print(result1)
print(result2)
print(result3)
|
"""
PROBLEM
Check Permutation:
* Given two strings,write a method to decide if one is a permutation of the
other.
"""
"""
Notes:
* Bit manipulation trick: If all characters in s1 have a corresponding match in s2,
then they are a permutaion of each other
* Base case should be communicated with the inteviewer clearly: Should having empty strings
for s1 and s2 return True or False? 0 also has a value in permutation (0! exists), so
here we consider this case to return True.
* Time Complexity: O(N), N: length of string
* Space Complexity: O(1) -> bit manipulation to the rescue
"""
def check_permutation(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
xor = 0
for i in range(len(s1)):
xor ^= ord(s1[i])
xor ^= ord(s2[i])
if xor == 0:
return True
else:
return False
"""
Notes:
* Alternatively, you can use a hash map as discussed in this chapter
* Time Complexity: O(N), N: length of traversed strings
* Space Complexity: O(1) -> Bit vector has constant size
"""
def check_permutation_alternative(s1: str, s2: str) -> bool:
if len(s1) != len(s2):
return False
hash_map = [0] * 128
for i in range(len(s1)):
index = ord(s1[i])
hash_map[index] += 1
for i in range(len(s2)):
index = ord(s2[i])
hash_map[index] -= 1
if hash_map[index] < 0:
return False
return True
if __name__ == '__main__':
print("TEST CASE #1 : %r" % (check_permutation('abcDe', 'ebDca')))
print("TEST CASE #2 : %r" % (check_permutation('abcDe', 'ebca')))
print("TEST CASE #3 : %r" % (check_permutation('abcDe', 'ebFca')))
print("TEST CASE #4 : %r" % (check_permutation('', '')))
print("TEST CASE #5 : %r" % (check_permutation('a', 'e')))
|
"""
PROBLEM
Palindrome Permutation:
* Given a string, write a function to check if it is a permutation of a palindrome.
* A palindrome is a word or phrase that is the same forwards and backwards.
* A permutation is a rearrangement of letters.
* The palindrome does not need to be limited to just dictionary words.
"""
"""
Notes:
* Bit manipulation trick for finding corresponding characters
* Time Complexity: O(N), 3 passes over the string in the worst case -> O(3*N) = O(N)
* Space Complexity: O(1)
"""
def palindrome_permutation(s : str) -> bool:
xor = 0
s = s.lower()
for c in s:
if c != ' ':
xor ^= ord(c)
if xor == 0:
return True
elif chr(xor) in s:
return True
else:
return False
if __name__ == '__main__':
print("TEST CASE #1 : %r" % (palindrome_permutation('Tact Coa')))
print("TEST CASE #2 : %r" % (palindrome_permutation('Tact CoaB')))
print("TEST CASE #3 : %r" % (palindrome_permutation('Tact Coa ')))
print("TEST CASE #4 : %r" % (palindrome_permutation('')))
print("TEST CASE #5 : %r" % (palindrome_permutation('T'))) |
"""
PROBLEM
Stack of Plates:
* Imagine a (literal) stack of plates. If the stack gets too high, it might topple.
* Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold.
* Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks and
should create a new stack once the previous one exceeds capacity.
* SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack
(that is, pop () should return the same values as it would if there were just a single stack).
FOLLOW UP
* Implement a function popAt (int index) which performs a pop operation on a specific sub-stack.
"""
class StackNode:
def __init__(self, x):
self.data = x
self.next = None
class SetOfStacks:
def __init__(self, node_limit=5):
self.stacks = []
self.node_count = 0
self.node_limit = node_limit
self.top = None
def is_empty(self):
return len(self.stacks) == 0
def push(self, item):
node = StackNode(item)
if self.node_count < self.node_limit:
if self.node_count == 0:
self.stacks.append(node)
else:
node.next = self.top
self.node_count += 1
else:
self.stacks.append(node)
self.node_count = 1
self.top = node
self.stacks[-1] = node
def pop(self):
if self.node_count == 0:
print("Stack is empty, pop() cannot be performed.", end='\n\n')
elif self.node_count == 1:
self.stacks = self.stacks[:-1]
if(len(self.stacks) > 0):
self.node_count = 5
self.top = self.stacks[-1]
else:
self.node_count = 0
else:
self.top = self.top.next
self.stacks[-1] = self.top
self.node_count -= 1
# TO-DO: Define pop at
def pop_at(self):
pass
def pretty_print(stacks):
print("****START-SET-OF-STACKS****")
for s in stacks:
print("---START-STACK---")
while s:
print(" -----")
print(" | |")
print(" | " + str(s.data) + " |")
print(" | |")
print(" -----")
s = s.next
print("---END-STACK---")
print("*****END-SET-OF-STACKS*****", end='\n\n')
if __name__ == '__main__':
s = SetOfStacks()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
pretty_print(s.stacks)
s.pop()
s.pop()
pretty_print(s.stacks)
s.push(3)
s.push(4)
s.push(5)
s.push(4)
s.push(4)
s.push(5)
s.push(6)
s.push(7)
pretty_print(s.stacks)
s.pop()
s.pop()
s.pop()
s.pop()
s.pop()
s.pop()
pretty_print(s.stacks)
s.pop()
s.pop()
s.pop()
s.pop()
pretty_print(s.stacks)
s.pop()
pretty_print(s.stacks)
|
"""
PROBLEM
Animal Shelter:
* An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis.
* People must adopt either the "oldest" (based on arrival time) of all animals at the shelter,
or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type).
* They cannot select which specific animal they would like.
* Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny,
dequeueDog, and dequeueCat.
* You may use the built-in Linked list data structure.
"""
import time
class ListNode:
def __init__(self, x):
self.type = x
self.arrival = time.time()
self.next = None
def print(self):
node = self
print("| %s - Arrived at: %d | " % (node.type, node.arrival))
node = node.next
while(node):
print("-> | %s - Arrived at: %d| " % (node.type, node.arrival))
node = node.next
print()
class AnimalShelter():
def __init__(self):
self.head = None
self.last = None
def enqueue(self, s : str):
node = ListNode(s)
if not self.head:
self.head = node
self.last = self.head
else:
self.last.next = node
self.last = self.last.next
def dequeue_any(self):
node = self.head
self.head = self.head.next
return node
def dequeue_dog(self):
node = self.head
prev = None
while(node and node.type != 'dog'):
prev = node
node = node.next
if node:
if prev: # Previous node exits, update accordingly
prev.next = node.next
else: # Previous node does not exist, returned node is the head
self.head = head.next
if not node.next: # Node is the last node
self.last = prev
return node
else:
print("There are currently no dogs in the animal shelter.")
return None
def dequeue_cat(self):
node = self.head
prev = None
while(node and node.type != 'cat'):
prev = node
node = node.next
if node:
if prev: # Previous node exits, update accordingly
prev.next = node.next
else: # Previous node does not exist, returned node is the head
self.head = head.next
if not node.next: # Node is the last node
self.last = prev
return node
else:
print("There are currently no cats in the animal shelter.")
return None
if __name__ == '__main__':
a = AnimalShelter()
a.enqueue('cat')
time.sleep(1)
a.enqueue('dog')
time.sleep(1)
a.enqueue('cat')
time.sleep(1)
a.enqueue('cat')
time.sleep(1)
a.enqueue('cat')
time.sleep(1)
a.enqueue('cat')
time.sleep(1)
a.enqueue('dog')
time.sleep(1)
a.enqueue('dog')
a.head.print()
a.dequeue_dog()
a.head.print()
a.dequeue_dog()
a.head.print()
a.dequeue_dog()
a.head.print()
a.enqueue('cat')
a.head.print()
a.dequeue_any()
a.head.print()
a.dequeue_dog()
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return []
return self.mergeSort(0,len(lists)-1,lists)
def mergeSort(self,left,right,lists):
if left >= right:
return lists[left]
mid = left + (right - left) // 2
leftArray = self.mergeSort(left,mid,lists)
rightArray = self.mergeSort(mid+1,right,lists)
return self.merge(leftArray,rightArray)
def merge(self,l1,l2):
root = cur = ListNode(1)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1:
cur.next = l1
if l2:
cur.next = l2
return root.next
|
# In Python3, addition can be done very easily with numbers and strings
7 + 2
# By writing 7+2 it directly gives the addition output
# Strings :-
'Hello' + 'World'
# Above code will merge 2 strings and gives output HelloWorld
|
"""
Created by: Gavin Ng
Read README for more information about python-turnip in general and its associated files
"""
# File Imports
import trends
import printer
# Setup for Cycles
cycleconverter = ["Monday AM","Monday PM","Tuesday AM","Tuesday PM","Wednesday AM","Wednesday PM","Thursday AM","Thursday PM","Friday AM","Friday PM","Saturday AM","Saturday PM"]
cyclepoints = {"Monday AM" : None,"Monday PM" : None,"Tuesday AM" : None,"Tuesday PM" : None,"Wednesday AM" : None,"Wednesday PM" : None,"Thursday AM" : None,"Thursday PM" : None,"Friday AM" : None,"Friday PM" : None,"Saturday AM" : None,"Saturday PM" : None}
cycleconvertercounter = 0
# Initial Buy Price Input
while True:
try:buy_price = int(input("How much did you initially pay for each turnip? "))
except ValueError:
print("Turnip Prices are in integer form")
if buy_price >= 90 and buy_price <= 110:
break
else:
print("Turnip buy prices are in the range of 90-110 bells")
# Dictionary Populator
for cycle in range(len(cyclepoints)):
cycleprompt = input("Do you know the buy price of "+cycleconverter[cycle]+"? (y/n)")
if cycleprompt.casefold() == 'y':
while True:
try: cyclepoints[cycleconverter[cycle]] = int(input("What is the buy price of "+cycleconverter[cycle]+"?"))
except ValueError:
print("Please input your turnip price in integer form")
if cyclepoints[cycleconverter[cycle]] <= 660 and cyclepoints[cycleconverter[cycle]] > 9:
break
else:
print("Invalid Input. It is impossible to have a turnip price less than 9 bells or over 660 bells")
elif cycleprompt.casefold() == 'n':
break
else:
print("Invalid input\n")
break
# Trend Determinatior Using Initial Buy Price and Cycle Datapoints
trendtype = trends.trendanalysis(buy_price,cyclepoints)
# Range Output According to Trend Type
cycleoutput = []
if trendtype == 'random':
output = trends.random(buy_price, cyclepoints)
cycleoutput.append(output[0])
cycleoutput.append(output[1])
elif trendtype == 'decreasing':
output = trends.decreasing(buy_price, cyclepoints)
cycleoutput.append(output[0])
cycleoutput.append(output[1])
elif trendtype == 'small_spike':
output = trends.small_spike(buy_price, cyclepoints)
cycleoutput.append(output[0])
cycleoutput.append(output[1])
elif trendtype == 'large_spike':
output = trends.large_spike(buy_price, cyclepoints)
cycleoutput.append(output[0])
cycleoutput.append(output[1])
elif trendtype == None:
output = trends.inconclusive(buy_price,cyclepoints)
cycleoutput.append(output[0])
cycleoutput.append(output[1])
# Generate Output Using printer.py (WIP)
printer.fileprinter(buy_price, cycleoutput,cycleconverter, cyclepoints) |
class Atividade09():
def input(self, string, numRep):
print(string * numRep)
validator = Atividade09()
string = input("Digite a palavra que deseja repetir")
numRep = int(input("Digite a quantidade de repetições que deseja"))
validator.input(string,numRep)
|
def hashFunc(piece):
words = piece.split(" ") #splitting string into words
colour = words[0]
shape = words[1]
poleNum = 0
for i in range(0, 3):
poleNum += ord(colour[i]) - 96
poleNum += ord(shape[i]) - 96
return poleNum
|
# Numbers - Tax Calculator (WIP)
"""
1) User inputs amount.
2) User inputs whether service charge is included. Default 10%.
3) Returns full price.
4) Optional: Splitting of bill by number of people.
5) Optional: Rounding of split bill to nearest dollar.
"""
# Imports
import subprocess
# Sets default variables
GST = 0.07
SvcCharge = 0.10
# Function - Clears screen
def cls():
subprocess.call("cls", shell = True)
# Function - Converts from decimal to percentage
def convertToPercent(input):
output = input * 100
return output
# Function - Converts from percentage to decimal
def convertToDecimal(input):
output = input / 100
return output
# Function - Settings
def progSettings():
global GST
global SvcCharge
settingsLoop = True
while settingsLoop == True:
cls()
print "Tax Calculator - Settings\n"
print "GST - {0:.2%}\nService charge - {1:.2%}\n".format(GST,SvcCharge)
try:
newGST = int(raw_input("\nPlease enter a number from 1 to 100, to set the percentage of GST.\n"))
GST = convertToDecimal(float(newGST))
newSvcCharge = int(raw_input("\nPlease enter a number from 1 to 100, to set the percentage of service charge.\n"))
SvcCharge = convertToDecimal(float(newSvcCharge))
except ValueError:
print "Please input whole numbers only!"
raw_input()
settingsLoop = False
# Loops until user goes to settings or provides a proper input.
inputLoop = True
while inputLoop == True:
# Information for users
cls()
print "Tax calculator - Main\n"
print "GST - {0:.2%}\nService charge - {1:.2%}\n".format(GST,SvcCharge)
print "Input the cost directly, or type 'settings' to change the percentages.\n"
# Requests input and acts accordingly.
userInput = raw_input(">>> ")
if userInput == "settings":
progSettings()
else:
# Makes sure input is a float, continue if so, loop if not.
try:
userInputFloat = float(userInput)
except ValueError:
print "\nPlease enter a valid number.\n"
raw_input()
else:
inputLoop = False
# Input accepted, determine if split.
inputLoop = True
while inputLoop == True:
# Clears and displays some values.
cls()
print "Tax calculator - Details\n"
print "GST - {0:.2%}\nService charge - {1:.2%}".format(GST,SvcCharge)
print "Amount entered - {0:.2f}\n".format(userInputFloat)
userInput = raw_input("\nIs the total cost going to be split? (Y/N) ")
if userInput.lower() == "y":
splitCost = True
inputLoop = False
elif userInput.lower() == "n":
splitCost = False
inputLoop = False
else:
print "\nPlease only enter either 'y' for YES, or 'n' for NO."
raw_input()
# If split, requests how much to split into. Skips this part otherwise.
if splitCost == True:
inputLoop = True
while inputLoop == True:
cls()
print "Tax calculator - Details\n"
print "GST - {0:.2%}\nService charge - {1:.2%}".format(GST,SvcCharge)
print "Amount entered - {0:.2f}\n".format(userInputFloat)
try:
userInput = int(raw_input("How many parts should the final cost be split into? "))
except ValueError:
print "Please enter numbers only!"
raw_input()
else:
splitNumber = userInput
inputLoop = False
# Starts calculations
cls()
print "Tax calculator - Calculations\n"
print "Original cost - ${0:.2f}".format(userInputFloat)
print "GST - {0:.2%}\nService charge - {1:.2%}\n".format(GST,SvcCharge)
print "GST costs ${0:.2f}".format(userInputFloat * GST)
print "Service charge costs ${0:.2f}".format(userInputFloat * SvcCharge)
print "Additional costs add up to a total of ${0:.2f}\n".format(userInputFloat * GST + userInputFloat * SvcCharge)
print "The total is ${0:.2f}".format(userInputFloat + userInputFloat * GST + userInputFloat * SvcCharge)
# Add-on if cost is to be split
if splitCost == True:
print "The cost per part is ${0:.2f}".format((userInputFloat + userInputFloat * GST + userInputFloat * SvcCharge)/splitNumber)
raw_input("End of program")
|
#Text - Pig latin (Sentence)
#Current solution was is to add 'ay' to the end of each word, shift the first letter back, then add the '-'.
#Further reading has revealed that pig latin is not as simple as it looks.
#Both consonants and consonant clusters at the start of words are shifted back.
#Vowels are not shifted back, and -ay is just appended to the end.
#This can be resolved by simply comparing the first letter to a list of consonants and vowels to see which one it matches.
#Consonant clusters can be detected by removing everything up to the first vowel.
#This is more complicated and I can't be arsed to do it because screw pig latin.
sentence = raw_input("Type something: ")
if sentence == "":
print "Nothing was typed."
else:
list_sentence = list(sentence) #Converts to list
is_looping = True
word_start_index = 0
word_end_index = 0
previous_isalnum = False
counter = 0
while is_looping == True:
if counter > len(list_sentence):
is_looping = False
print "".join(list_sentence)
elif counter == len(list_sentence) or\
list_sentence[counter].isalnum() == False and\
previous_isalnum == True: #End of a word
word_end_index = counter
list_sentence.insert(word_end_index, "y")
list_sentence.insert(word_end_index, "a")
list_sentence.insert((word_end_index-1), list_sentence.pop(word_start_index))
list_sentence.insert((word_end_index-1), "-")
previous_isalnum = False
counter += 4
elif list_sentence[counter].isalnum() == True and\
previous_isalnum == False: #Start of a word
word_start_index = counter
previous_isalnum = True
counter += 1
elif list_sentence[counter].isalnum() == True and\
previous_isalnum == True: #Cont of a word
counter += 1
|
#
# Complete the 'print_full_name' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING first
# 2. STRING last
#
from string import Template
def getStringFromTemplate(templateObj,varDict):
return templateObj.substitute(varDict)
FULLNAME_TEMPLATE = Template('Hello $first $last! You just delved into python.');
def print_full_name(first, last):
# Write your code here
print(getStringFromTemplate(FULLNAME_TEMPLATE,{'first': first, 'last': last}))
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if(root==None):
return [];
qu = [];
qu.append({
"node": root,
"level": 0
})
rv = [];
while(len(qu)>0):
curr = qu.pop(0)
if(curr["node"].right!=None):
qu.append({
"node": curr["node"].right,
"level": curr["level"]+1
})
if(curr["node"].left!=None):
qu.append({
"node": curr["node"].left,
"level": curr["level"]+1
})
if(len(rv)==curr["level"]):
rv.append(curr["node"].val);
# else:
# rv[curr["level"]] = curr["node"].val;
return rv; |
if __name__ == '__main__':
x = int(raw_input())
y = int(raw_input())
z = int(raw_input())
n = int(raw_input())
list3d = [[a,b,c] for a in range(0,x+1) for b in range(0,y+1) for c in range(0,z+1)]
def checkForSum(arr):
if (arr[0]+arr[1]+arr[2])==n:
return False
else:
return True
filteredList = filter(checkForSum,list3d)
print(filteredList) |
from zoo import Zoo
from animal import Animal
class SimulateZoo:
DAYS_IN_WEEK = 7
DAYS_IN_MONTH = 30
DAYS_IN_YEAR = 365
def __init__(self, zoo):
self.zoo = zoo
def simulate(self, command):
command[1] = int(command[1])
if command[2] == "years":
days = command[1] * SimulateZoo.DAYS_IN_YEAR
elif command[2] == "weeks":
days = command[1] * SimulateZoo.DAYS_IN_WEEK
elif command[2] == "months":
days = command[1] * SimulateZoo.DAYS_IN_MONTH
else:
days = command[1]
for day in range(days):
for animal in self.zoo.animals:
animal.eat(5)
animal.age += 1
if animal.age == animal.life_expectancy:
print("{} {} died!".format(animal.name, animal.species))
self.zoo.die(animal)
outcome = self.zoo.calculate_outcome()
if outcome > self.zoo.budget:
print("Bankrupt!")
else:
self.zoo.budget -= outcome
newborns = self.zoo.reproduce()
if len(newborns) > 0:
print(newborns)
self.zoo.calculate_income()
print(self.zoo)
def move_to_habitat(self, species, name):
for animal in self.zoo.animals:
if animal.name == name and animal.species == species:
self.zoo.animals.remove(animal)
def get_input(self):
command = input("Enter command> ")
command = command.split(" ")
return command
def interface(self):
command = self.get_input()
while command[0] != "exit":
if command[0] == "see_animals":
print(self.zoo)
command = self.get_input()
elif command[0] == "accomodate":
species = command[0]
name = command[1]
age = command[2]
weight = command[3]
gender = ""
new_animal = Animal(species, age, name, gender, weight)
gender = new_animal.determine_gender()
new_animal.gender = gender
self.zoo.accomodate(new_animal)
elif command[0] == "move_to_habitat":
self.move_to_habitat(command[1], command[2])
command = self.get_input()
elif command[0] == "simulate":
self.simulate(command)
command = self.get_input()
else:
print("Bad input!")
command = self.get_input()
else:
print("Goodbye!")
def main():
park = Zoo([], 10, 10)
park.load_zoo("test_dogs.txt")
simulation = SimulateZoo(park)
simulation.interface()
if __name__ == '__main__':
main()
|
from datetime import datetime
from functools import reduce
from util import contains, write_to_file
def generate_output(key, value_tuple):
date_str = value_tuple[1].strftime("%Y-%m-%d %H:%M:%S")
return "{}\t{}\t{}\n".format(key, date_str, str(value_tuple[0]))
def calculate_busiest_time(key_values_dict, key_value):
key, value = key_value.strip().split("\t", 1)
entries, date, time = value.strip().split('\t')
entries_num = float(entries)
entry_time = datetime.strptime(date + "T" + time, "%Y-%m-%dT%H:%M:%S")
keys = list(key_values_dict)
current_count = key_values_dict[key] if contains(keys, key) else (0.0, datetime(1970,1,1))
entry_high = current_count if current_count[0] > entries_num or (current_count[0] == entries_num and current_count[1] > entry_time) else (entries_num, entry_time)
key_values_dict[key] = entry_high
return key_values_dict
def reducer(ridership_file):
'''
Write a reducer that will compute the busiest date and time (that is, the
date and time with the most entries) for each turnstile unit. Ties should
be broken in favor of datetimes that are later on in the month of May. You
may assume that the contents of the reducer will be sorted so that all entries
corresponding to a given UNIT will be grouped together.
The reducer should print its output with the UNIT name, the datetime (which
is the DATEn followed by the TIMEn column, separated by a single space), and
the number of entries at this datetime, separated by tabs.
For example, the output of the reducer should look like this:
R001 2011-05-11 17:00:00 31213.0
R002 2011-05-12 21:00:00 4295.0
R003 2011-05-05 12:00:00 995.0
R004 2011-05-12 12:00:00 2318.0
R005 2011-05-10 12:00:00 2705.0
R006 2011-05-25 12:00:00 2784.0
R007 2011-05-10 12:00:00 1763.0
R008 2011-05-12 12:00:00 1724.0
R009 2011-05-05 12:00:00 1230.0
R010 2011-05-09 18:00:00 30916.0
...
...
Since you are printing the output of your program, printing a debug
statement will interfere with the operation of the grader. Instead,
use the logging module, which we've configured to log to a file printed
when you click "Test Run". For example:
logging.info("My debugging message")
Note that, unlike print, logging.info will take only a single argument.
So logging.info("my message") will work, but logging.info("my","message") will not.
'''
with open(ridership_file) as ridership_data:
output_filename = "./subway_busiest_hour.txt"
ridership_dict = reduce(calculate_busiest_time, [data for data in ridership_data], {})
[write_to_file(output_filename, generate_output(k, v)) for k, v in ridership_dict.items()]
if __name__ == "__main__":
reducer("./subway_ridership_by_hour_and_unit.txt")
|
#!/usr/bin/env python3
import itertools
# encrypted key1, key2 and flag (from scrambledeggs.txt)
ekey1 = 'xtfsyhhlizoiyx'
ekey2 = 'eudlqgluduggdluqmocgyukhbqkx'
eflag = 'lvvrafwgtocdrdzfdqotiwvrcqnd'
scramble_map = ['v', 'r', 't', 'p', 'w', 'g', 'n', 'c', 'o', 'b', 'a', 'f', 'm', 'i', 'l', 'u', 'h', 'z', 'd', 'q', 'j', 'y', 'x', 'e', 'k', 's']
# result of the evaluation of (sys.maxsize % 28) for 64-bit machines
randsize = 7
# to choose whether or not to swap key1 and key2
swapkeys = True
# write the resulting flag combinations to a file
outfile = 'results.txt'
# reverse enc1, but provide n
def dec1(text, n):
assert(0 <= n < 28)
return text[-n:] + text[:-n]
# reverse enc2
def dec2(text):
# map each character of text to the character of order :
# index of text[i] in scramble_map + ord('a')
return ''.join(chr(scramble_map.index(char) + ord('a')) for char in text)
# recover key2 from the encrypted key2 (the part where random chars are appended to key2)
def recover_key2(ekey2):
assert(len(ekey2) == 28)
# the random characters are the 14 first
k = ekey2[:14]
# the list of `a`s
alist = list(map(ord, ekey2[14:]))
res = ''
for i in range(14):
# we simply compute c using linear equations
c = alist[i] - ord(k[i]) + ord('a')
# since all characters are ascii lowercase
# this check helps avoiding multiple potential values
if not ord('a') <= c <= ord('z'):
c += 122 - 97
res += chr(c)
return res
# undo the big double loop
def unloop(key1, key2, flag):
key1, key2, flag = list(key1), list(key2), list(flag)
assert (len(key1) == len(key2) == 14)
for j in range(2):
# we make sure the range is from 27 to 14, not 14 to 27
for i in range(27, 13, -1):
# taking advantage of python's built-in way to swap values
# rather than using a temp variable
index = (ord(key1[i-14]) - ord('a')) % 14
key2[index], key2[i-14] = key2[i-14], key2[index]
index = (ord(key2[i-14]) - ord('a')) % 28
flag[i], flag[index] = flag[index], flag[i]
for i in range(13, -1, -1):
index = (ord(key2[i]) - ord('a')) % 14
key1[index], key1[i] = key1[i], key1[index]
index = (ord(key1[i]) - ord('a')) % 28
flag[i], flag[index] = flag[index], flag[i]
return ''.join(key1), ''.join(key2), ''.join(flag)
if __name__ == '__main__':
# generate the combinations of 3 `n`s using itertools.product
combinations = [p for p in itertools.product(range(randsize+1), repeat=3)]
key1 = ekey1
key2 = recover_key2(dec2(ekey2))
flag = dec2(eflag)
if swapkeys: key1, key2 = key2, key1
original = flag, key1, key2
results = []
for c in combinations:
flag = dec1(dec1(dec1(flag, c[0]), c[1]), c[2])
key1, key2, flag = unloop(key1, key2, flag)
if dec2(dec2(key2)) == key1:
for n in range(randsize + 1):
flag = dec1(flag, n)
results.append(flag)
flag, key1, key2 = original
with open(outfile, 'w') as f:
f.write('\n'.join(results))
f.close()
|
# -*- coding: utf-8 -*-
def steffensen(f, x0, tol):
if tol <= 0:
print("illegal value for tolerance")
return
for i in range(1, 1000):
y0 = f(x0)
x = x0 - y0 * y0 / (f(x0 + y0) - y0)
if abs(x - x0) < tol:
print("found root", x, "in", i, "iteration(s)")
return
x0 = x
print("failed to converge in 1K iterations")
def steffensen_atk(f, x0, tol):
"""This function takes as inputs: a fixed point iteration function, f,
and initial guess to the fixed point, p0, and a tolerance, tol.
This function will calculate and return the fixed point, p,
that makes the expression f(x) = p true to within the desired
tolerance, tol.
"""
if tol <= 0:
print("illegal value for tolerance")
return
# do a large, but finite, number of iterations
for i in range(1, 1000):
x1 = f(x0) # calculate the next two guesses for the fixed point
x2 = f(x1)
# use Aitken's delta squared method to find a better approximation to
# p0
x = x2 - (x2 - x1) * (x2 - x1) / (x2 - 2 * x1 + x0)
if abs(x - x0) < tol:
print("found root", x, "after", i, "iteration(s)")
return
x0 = x
print("failed to converge in 1K iterations")
|
#using machine and utime Micropython libraries
import machine
import utime
buzzer = machine.Pin(2,machine.Pin.OUT) #The buzzer is attached to pin D4 on the NodeMCU
motor = machine.PWM(machine.Pin(14), freq = 50) #The motor driver is attached to pin D5 on the NodeMCU
#time parameters defined as empty arrays
first_release_time = []
hours_until_release = []
#This function defines what happens in the event of a pill release
def pill_release():
motor.duty(200)
utime.sleep(3.75)
motor.duty(0)
buzzer.value(1)
utime.sleep(2)
buzzer.value(0)
n = 1 #n is a factor that is used in definint the release_time varible
first_release_time = 10 #defines how long to wait before releasing the first pill
hours_until_release = 10 #defines how often the medication must be taken
number_of_pills = 20 #defines the number of pills at the start
did_first_action = False #an extra condition that corrects for delays in timing
#main loop of the code. A pill is released after user-specified intervals
while True:
current_time = utime.ticks_ms()
release_time = first_release_time + hours_until_release*n
motor.duty(0)
buzzer.value(0)
if current_time/3600000 >= first_release_time and did_first_action == False:
pill_release()
did_first_action = True
utime.sleep(hours_until_release*3600 - 5.75)
if current_time/3600000 >= release_time and did_first_action == True:
pill_release()
n = n + 1
utime.sleep(hours_until_release*3600 - 5.75)
if n > (number_of_pills - 1):
buzzer.value(1)
utime.sleep(2)
buzzer.value(0)
utime.sleep(1)
buzzer.value(1)
utime.sleep(2)
buzzer.value(0)
utime.sleep(1)
buzzer.value(1)
utime.sleep(2)
buzzer.value(0)
break
|
############################ dAY 7 ########################
############################ hANGMAN pROJECT ##################
#Step 1
import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
word_list = ["pakistan","srilanka","india"]
choosen_word = random.choice(word_list)
display = []
gameOver = True
lives = 6
for i in choosen_word:
display.append("_")
while gameOver:
if "_" in display:
user_inp = input("guess a letter\n").lower()
for position in range(0,len(choosen_word)):
if user_inp == choosen_word[position]:
display[position] = user_inp
print(f"{' '.join(display)}")
if user_inp not in choosen_word:
lives -=1
print(stages[lives])
if lives == 0:
print("you loose")
break
else:
gameOver = False
print("you win")
|
# Python 3 - Polling radio buttons tkinter program
# Author: J.Smith
# Import tkinter library
from tkinter import *
import tkinter.messagebox as box
# A window
window = Tk()
window.title('Radio Button Example')
# Frame to contain widgets
frame = Frame(window)
# String variable to store a selection
book = StringVar()
# Three radio button widgets
radio_1 = Radiobutton(frame, text = "HTML5", variable = book, value = "HTML5 in Easy Steps")
radio_2 = Radiobutton(frame, text = "CSS", variable = book, value = "CSS in Easy Steps")
radio_3 = Radiobutton(frame, text = "JS", variable = book, value = "JavaScript in Easy Steps")
# Set default radio button
radio_1.select()
# Function to show selection
def dialog():
box.showinfo('Selection', 'Your choice: \n' + book.get())
# Button to run the function
btn = Button(frame, text = "Choose", command = dialog)
# Pack all the elements together
btn.pack(side = RIGHT, padx = 5)
radio_1.pack(side = LEFT)
radio_2.pack(side = LEFT)
radio_3.pack(side = LEFT)
frame.pack(padx = 30, pady= 30)
# Maintain the current window
window.mainloop() |
x= int(input("Digite el primer numero: "))
y= int(input("Digite el segundo numero: "))
def resta(x,y,):
return x-y
def multiplicacion(x,y):
return x*y
def division(x,y):
return x//y
def divisionres(x,y):
return x%y
print("La resta de tus dos numero es: ", resta (x,y))
print("La multiplicacion de tus dos numero es: ", multiplicacion(x,y))
print("La division de tus dos numero es: ", division(x,y))
print("El residuo de la divison de tus dos numero es: ", divisionres(x,y))
|
numero1= int(input("En que numero comienza la lista: "))
numero2= int(input("En que numero termina la lista: "))
lista=list(range(numero1,numero2+1))
for n in lista:
inverso_n=int(str(n)[::-1])
suma=inverso_n+n
inverso_checa=int(str(suma)[::-1])
if n==inverso_n:
print(n,"es palindromo")
elif(suma==inverso_checa):
print(n,"No es un numero Lychrel")
else:
print(n,"Es un numero Lychrel")
|
import random
contador=0
respuesta=0
n=random.randint(0,101)
while respuesta!=n:
respuesta=0
respuesta = int(input("Intente adivinar el numero: "))
if respuesta>n:
contador=contador+1
print(respuesta," es mayor, intenta con otro numero mas pequeño")
elif respuesta<n:
contador=contador+1
print(respuesta," es menor, intenta con otro numero mas grande")
else:
print("has acertado el numero, lo has intentado: ",contador," veces")
|
def adding_natural():
sum_of=0
for x in range(1,number+1):
sum_of+=x
sum_of=sum_of**(2)
return sum_of
def mult_natural():
multi=0
for x in range(1,number+1):
multi= multi + (x**(2))
return multi
try:
print("Choose your number")
number=eval(input())
print(adding_natural()-mult_natural())
except:
print("An error occured")
|
import numpy as np
class Perceptron(object):
# constructor for creating object of class perceptron
def __init__(self, no_of_inputs, epoch=20, learning_rate=0.01):
# epoch determines, how many times each training example would pass through perceptron
self.epoch = epoch
# learning rate defines that how much change is acceptable between previous and new weights
self.learning_rate = learning_rate
self.weights = np.zeros(no_of_inputs + 1)
def predict(self, inputs):
# following line is computing the equation (X1*W1) + (X2*2) + b
summation = np.dot(inputs, self.weights[1:]) + self.weights[0]
if summation >= 0:
activation = 1
else:
activation = 0
return activation
def train(self, training_inputs, labels):
for _ in range(self.epoch):
for inputs, label in zip(training_inputs, labels):
prediction = self.predict(inputs)
# Following lines are readjusting the weights and bias
# If the difference is -ve, new weight will be less than previous one
# If the difference is +ve, new weight will be greater than previous one
self.weights[1:] += self.learning_rate * (label - prediction) * inputs
self.weights[0] += self.learning_rate * (label - prediction)
print("learning rate", self.learning_rate, self.weights[1:])
training_inputs = []
training_inputs.append(np.array([1, 1]))
training_inputs.append(np.array([1, 0]))
training_inputs.append(np.array([0, 1]))
training_inputs.append(np.array([0, 0]))
labels = np.array([1, 0, 0, 0])
perceptron = Perceptron(2)
perceptron.train(training_inputs, labels)
inputs = np.array([0.5, 0.8])
print(perceptron.predict(inputs))
inputs = np.array([1.5, 0.5])
print(perceptron.predict(inputs)) |
koniec_przedzialu = int(input("Podaj koniec przedzialu: "))
lista = []
lista_new = []
def stworzliste(koniec_przedzialu):
for i in range (2,koniec_przedzialu+1):
minimum = min(i,koniec_przedzialu)
lista.append(minimum)
stworzliste(koniec_przedzialu)
print ("Podany przedzial zawiera liczby:")
print (lista)
print("Z tego przedzialu liczby pierwsze to:")
def program(argument,lista):
print(argument)
lista_new = []
for j in range (0, len(lista)):
if int(lista[j]) % argument != 0:
lista_new.append(int(lista[j]))
for k in range (0,len(lista_new)):
lista[k] = lista_new[k]
argument = int(lista[0])
wielkosclisty = int(len(lista_new))
if wielkosclisty > 0:
program(argument,lista[0:len(lista_new)])
else:
print('koniec')
program(2,lista)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Questão 1
Modele o problema do Restaurante (mencionado no capítulo 18 do livro texto)
para ser resolvido por meio de árvore de decisão e por meio de KNN (com k = 1 e com k = 5).
Este código trata só de arvores de devisão
"""
import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export
from sklearn.metrics import confusion_matrix, accuracy_score
dados = pd.read_csv("restaurante.csv")
# Fazendo um preprocessamento do dados
# Coloca na variavel entrada só as colunas referentes ao atrubutos
entradas = dados.iloc[:, 0:10].values
classe = dados.iloc[:, 10].values
# transforma as variáves categoricas em numéricas
labelencoder_entradas = LabelEncoder()
entradas[:, 0] = labelencoder_entradas.fit_transform(entradas[:, 0])
entradas[:, 1] = labelencoder_entradas.fit_transform(entradas[:, 1])
entradas[:, 2] = labelencoder_entradas.fit_transform(entradas[:, 2])
entradas[:, 3] = labelencoder_entradas.fit_transform(entradas[:, 3])
entradas[:, 4] = labelencoder_entradas.fit_transform(entradas[:, 4])
entradas[:, 5] = labelencoder_entradas.fit_transform(entradas[:, 5])
entradas[:, 6] = labelencoder_entradas.fit_transform(entradas[:, 6])
entradas[:, 7] = labelencoder_entradas.fit_transform(entradas[:, 7])
entradas[:, 8] = labelencoder_entradas.fit_transform(entradas[:, 8])
entradas[:, 9] = labelencoder_entradas.fit_transform(entradas[:, 9])
classe = labelencoder_entradas.fit_transform(classe)
# Normalizado os dados usando a média e o desvio padrão
scaler = StandardScaler()
entradas = scaler.fit_transform(entradas)
#Didvisão dos dados em tetes e treinamento.
entradas_treinamento, entradas_teste, classe_treinamento, classe_teste = train_test_split(entradas, classe, test_size=0.30, random_state=0)
# Instnacioando o classificar da arvores de devisão
# Vai gerar uma arrvores de decisão de acordo com o criterio a entropia
classificador = DecisionTreeClassifier(criterion='entropy')
classificador.fit(entradas_treinamento, classe_treinamento)
#print(classificador.feature_importances_)
# Visualização da arvore
export.export_graphviz(
classificador,
out_file = 'arvore.dot',
feature_names = ['Alternativa', 'Bar', 'Sex/Sab', 'Faminto', 'Clientes', 'Preço', 'Chovendo', 'Reserva', 'Tipo', 'Espera estimada'],
class_names = ['Sim', 'Não'],
filled = True,
leaves_parallel=True
)
# Usa a base de teste para ver o resultado
resultado_teste = classificador.predict(entradas_teste)
# Verificando a quantidade de acerto nos testes
precisao = accuracy_score(classe_teste, resultado_teste)
print(precisao)
|
# The script intends to read data from the excel file
def read():
import requests
from requests.exceptions import MissingSchema
import xlrd
#stores the name of the sites from the excel as a list
sites=[]
# Hardcode the location of the excel file here
file_location=r'C:\Users\pankaj lamba\Desktop\PBL2/csv.xlsx'
# Opens the excel file
workbook=xlrd.open_workbook(file_location)
# Opens the FIRST sheet
sheet=workbook.sheet_by_index(0)
# Counts the Number of row in the sheet
n=sheet.nrows
for i in range (1,n):
#Converts the name of the sites into an URL
# Stores the URL of the sites into the list
site='http://www.'+sheet.cell_value(i,0)
try:
request = requests.get(site)
if request.status_code == 200:
sites.append(site)
except:
pass
return(sites)
x=read()
print(x)
|
import tkinter as tk
from tkinter import *
import math
class paceCalculator:
#**def clear_search(event):
#self.entTime.delete(0, END)
#***def clear_search2(event):
#self.entDS.delete(0, END)
def __init__(self):
self.root = tk.Tk()
self.root.configure(background = "navy")
self.root.geometry('400x400')
self.labTitle = tk.Label(self.root,text = "Pace Calculator")
self.labTitle.grid(row = 2, column = 0, columnspan = 2)
self.labTime = tk.Label(self.root, text = "Enter Time in Seconds: ")
self.labTime.grid(row = 3, column = 0)
self.entTime = tk.Entry(self.root, background = "light grey")
self.entTime.grid(row = 3, column = 1)
#self.entTime.insert(0,"Enter Time in Seconds")
#self.entTime.bind("<Button-1>", clear_search)
self.labDS = tk.Label(self.root, text = "Enter Distance Swam: ")
self.labDS.grid(row = 4, column = 0, padx = 10, pady = 10)
self.entDS = tk.Entry(self.root, background = "light grey")
self.entDS.grid(row = 4, column = 1, padx = 10, pady = 10)
#**self.entDS.insert(0,"Enter Distance in Meters")
#***self.entDS.bind("<Button-1>", clear_search2)
self.DDLabel = Label(self.root, text = "Select Distance: ")
self.DDLabel.grid(row = 5 , column = 0, sticky = "E")
OPTIONS = [
"25",
"50",
"100",
"200",
]
self.var = tk.StringVar(self.root)
self.var.set(OPTIONS[0])
self.dropDownMenu = tk.OptionMenu(self.root,self.var, OPTIONS[0], OPTIONS[1], OPTIONS[2], OPTIONS[3])
self.dropDownMenu.grid(row = 5 , column = 1, sticky = "W")
d
self.btnCalc = tk.Button(self.root, text = "Calculate",command= self.calculate)
self.btnCalc.grid(row = 6 , column = 0, columnspan = 2)
self.output = tk.Text(self.root, height = 10, width=50, relief=tk.GROOVE)
self.output.config(state="disabled")
self.output.grid(row = 8, column = 0, columnspan = 2)
self.root.mainloop()
def calculate(self):
print("Calculating")
t = float(self.entTime.get())
d = float(self.entDS.get())
c = float(self.var.get())
r = math.ceil((t/d)*c)
outputValue = "When "+str(t)+" seconds is taken to swim "+str(d)+" meters, the pace per "+str(c)+"meters is:" + str(r) + " seconds per " + str(c)
self.output.config(state = "normal")
self.output.delete(1.0,tk.END)
self.output.insert(tk.INSERT,outputValue)
self.output.config(state="disabled")
print(str(r) + "Seconds per" + str(c))
paceCalculator()
|
#!/usr/bin/python
import csv
from twython import Twython
from twython import TwythonStreamer
class TwitterStream(TwythonStreamer):
'''
Implements twitter api using the TwythonStreamer subclass.
'''
def on_success(self, data):
'''
required 'TwythonStreamer' method called when twitter returns data.
'''
tweet_data = process_tweet(data)
self.save_to_csv(tweet_data)
def on_error(self, status_code, data):
'''
required 'TwythonStreamer' method called when twitter returns an error.
'''
print(status_code, data)
self.disconnect()
def save_to_csv(self, tweet):
'''
optional 'TwythonStreamer' method to store tweets into a file.
'''
with open(r'saved_tweets.csv', 'a') as file:
writer = csv.writer(file)
writer.writerow(list(tweet.values()))
|
# coding: utf-8
# # Project for Neural Networks lecture
#
# ## Deep Learning
#
# ## Project: Build a CIFAR10 Recognition Classifier
# 
# Source: Yan LeCun
#
# In this project, I will use deep neural networks and convolutional neural networks to classify CIFAR10 dataset from [http://www.cs.toronto.edu/~kriz/cifar.html](http://www.cs.toronto.edu/~kriz/cifar.html).
#
#
# ## Step 0: Load The Data - code from: https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/cifar10.py
# In[50]:
########################################################################
#
# Functions for downloading the CIFAR-10 data-set from the internet
# and loading it into memory.
#
# Implemented in Python 3.5
#
# Usage:
# 1) Set the variable data_path with the desired storage path.
# 2) Call maybe_download_and_extract() to download the data-set
# if it is not already located in the given data_path.
# 3) Call load_class_names() to get an array of the class-names.
# 4) Call load_training_data() and load_test_data() to get
# the images, class-numbers and one-hot encoded class-labels
# for the training-set and test-set.
# 5) Use the returned data in your own program.
#
# Format:
# The images for the training- and test-sets are returned as 4-dim numpy
# arrays each with the shape: [image_number, height, width, channel]
# where the individual pixels are floats between 0.0 and 1.0.
#
########################################################################
#
# This file is part of the TensorFlow Tutorials available at:
#
# https://github.com/Hvass-Labs/TensorFlow-Tutorials
#
# Published under the MIT License. See the file LICENSE for details.
#
# Copyright 2016 by Magnus Erik Hvass Pedersen
#
########################################################################
import numpy as np
import pickle
import os
import download
from dataset import one_hot_encoded
########################################################################
# Directory where you want to download and save the data-set.
# Set this before you start calling any of the functions below.
data_path = "data/CIFAR-10/"
# URL for the data-set on the internet.
data_url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
########################################################################
# Various constants for the size of the images.
# Use these constants in your own program.
# Width and height of each image.
img_size = 32
# Number of channels in each image, 3 channels: Red, Green, Blue.
num_channels = 3
# Length of an image when flattened to a 1-dim array.
img_size_flat = img_size * img_size * num_channels
# Number of classes.
num_classes = 10
########################################################################
# Various constants used to allocate arrays of the correct size.
# Number of files for the training-set.
_num_files_train = 5
# Number of images for each batch-file in the training-set.
_images_per_file = 10000
# Total number of images in the training-set.
# This is used to pre-allocate arrays for efficiency.
_num_images_train = _num_files_train * _images_per_file
########################################################################
# Private functions for downloading, unpacking and loading data-files.
def _get_file_path(filename=""):
"""
Return the full path of a data-file for the data-set.
If filename=="" then return the directory of the files.
"""
return os.path.join(data_path, "cifar-10-batches-py/", filename)
def _unpickle(filename):
"""
Unpickle the given file and return the data.
Note that the appropriate dir-name is prepended the filename.
"""
# Create full path for the file.
file_path = _get_file_path(filename)
print("Loading data: " + file_path)
with open(file_path, mode='rb') as file:
# In Python 3.X it is important to set the encoding,
# otherwise an exception is raised here.
data = pickle.load(file, encoding='bytes')
return data
def _convert_images(raw):
"""
Convert images from the CIFAR-10 format and
return a 4-dim array with shape: [image_number, height, width, channel]
where the pixels are floats between 0.0 and 1.0.
"""
# Convert the raw images from the data-files to floating-points.
# raw_float = np.array(raw, dtype=float) / 255.0
# raw_float = np.array(raw, dtype=float)
# Reshape the array to 4-dimensions.
# images = raw_float.reshape([-1, num_channels, img_size, img_size])
images = raw.reshape([-1, num_channels, img_size, img_size])
# Reorder the indices of the array.
images = images.transpose([0, 2, 3, 1])
return images
def _load_data(filename):
"""
Load a pickled data-file from the CIFAR-10 data-set
and return the converted images (see above) and the class-number
for each image.
"""
# Load the pickled data-file.
data = _unpickle(filename)
# Get the raw images.
raw_images = data[b'data']
# Get the class-numbers for each image. Convert to numpy-array.
cls = np.array(data[b'labels'])
# Convert the images.
images = _convert_images(raw_images)
return images, cls
########################################################################
# Public functions that you may call to download the data-set from
# the internet and load the data into memory.
def maybe_download_and_extract():
"""
Download and extract the CIFAR-10 data-set if it doesn't already exist
in data_path (set this variable first to the desired path).
"""
download.maybe_download_and_extract(url=data_url, download_dir=data_path)
def load_class_names():
"""
Load the names for the classes in the CIFAR-10 data-set.
Returns a list with the names. Example: names[3] is the name
associated with class-number 3.
"""
# Load the class-names from the pickled file.
raw = _unpickle(filename="batches.meta")[b'label_names']
# Convert from binary strings.
names = [x.decode('utf-8') for x in raw]
return names
def load_training_data():
"""
Load all the training-data for the CIFAR-10 data-set.
The data-set is split into 5 data-files which are merged here.
Returns the images, class-numbers and one-hot encoded class-labels.
"""
# Pre-allocate the arrays for the images and class-numbers for efficiency.
images = np.zeros(shape=[_num_images_train, img_size, img_size, num_channels], dtype=float)
cls = np.zeros(shape=[_num_images_train], dtype=int)
# Begin-index for the current batch.
begin = 0
# For each data-file.
for i in range(_num_files_train):
# Load the images and class-numbers from the data-file.
images_batch, cls_batch = _load_data(filename="data_batch_" + str(i + 1))
# Number of images in this batch.
num_images = len(images_batch)
# End-index for the current batch.
end = begin + num_images
# Store the images into the array.
images[begin:end, :] = images_batch
# Store the class-numbers into the array.
cls[begin:end] = cls_batch
# The begin-index for the next batch is the current end-index.
begin = end
return images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes)
def load_test_data():
"""
Load all the test-data for the CIFAR-10 data-set.
Returns the images, class-numbers and one-hot encoded class-labels.
"""
images, cls = _load_data(filename="test_batch")
return images, cls, one_hot_encoded(class_numbers=cls, num_classes=num_classes)
########################################################################
# In[66]:
class_names = load_class_names()
# In[51]:
maybe_download_and_extract()
# In[52]:
X, y, one_hot_y_train = load_training_data()
# In[53]:
from sklearn.model_selection import train_test_split
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2, random_state=42)
# In[55]:
X_test, y_test, one_hot_y_test = load_test_data()
# ---
#
# ## Step 1: Dataset Summary & Exploration
#
# ### Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas
# In[56]:
# Number of training examples
n_train = len(X_train)
# Number of validation examples
n_validation = len(X_valid)
# Number of testing examples.
n_valid = len(X_valid)
# Number of testing examples.
n_test = len(X_test)
# What's the shape of an traffic sign image?
image_shape = X_train[0].shape
# How many unique classes/labels there are in the dataset.
n_classes = len(set(y_train))
print("Number of training examples =", n_train)
print("Number of validation examples =", n_valid)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
# ### Include an exploratory visualization of the dataset
# Visualize the CIFAR10 Dataset using the pickled file(s): images and distribution of classes in each dataset.
# In[69]:
# Randomly choose indices to represent which datapoints we choose from the training set
import math
import numpy as np
import random
import matplotlib.pyplot as plt
def plot_images(num, x, y, path):
num_images = num
indices = np.random.choice(list(range(len(x))), size=num_images, replace=False)
# Obtain the images and labels
images = x[indices]
labels = y[indices]
for i, image in enumerate(images):
plt.rcParams["figure.figsize"] = [15, 5]
plt.subplot(2, math.ceil(num_images/2.), i+1)
plt.imshow(image)
plt.title('%s' % class_names[labels[i]])
plt.tight_layout()
plt.savefig(path)
plt.show()
# In[73]:
plot_images(10, X_train/255, y_train, 'writeup_images/examples_X_train.jpg')
# In[82]:
# Count frequency of each label
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
def plot_hist(y, path):
labels, counts = np.unique(y, return_counts=True)
# Plot the histogram
plt.rcParams["figure.figsize"] = [15, 5]
axes = plt.gca()
axes.set_xlim([-1,10])
plt.bar(labels, counts, tick_label=labels, width=0.8, align='center')
plt.title('Distribution of classes on {} data'.format(namestr(y, globals())))
plt.savefig(path)
plt.show()
# ### Plot histogram of the train dataset
# In[83]:
plot_hist(y_train, 'writeup_images/hist_y_train.jpg')
# ### Plot histogram of the validation dataset
# In[84]:
# Count frequency of each label
plot_hist(y_valid,'writeup_images/hist_y_valid.jpg')
# ### Plot histogram of the test dataset
# In[85]:
# Count frequency of each label
plot_hist(y_test,'writeup_images/hist_y_test.jpg')
# ----
#
# ## Step 2: Design and Test a Model Architecture
#
# In this part I will design and implement a deep learning model that learns to recognize categories in dataset.
#
# The implementation shown in the [LeNet-5](http://yann.lecun.com/exdb/lenet/) is a solid starting point.
# There are various aspects to consider when thinking about this problem:
#
# - Neural network architecture (is the network over or underfitting?)
# - Play around preprocessing techniques (normalization, rgb to grayscale, etc)
# - Number of examples per label (some have more than others).
# - Generate fake data.
#
# Here is an example of a [published baseline model on this problem](http://yann.lecun.com/exdb/publis/pdf/sermanet-ijcnn-11.pdf).
# ### Pre-process the Data Set (normalization, grayscale, etc.)
# Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, `(pixel - 128)/ 128` is a quick way to approximately normalize the data and can be used in this project.
#
# Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
# In[140]:
def center_normalize(data):
"""Center normalize images"""
data = data.astype('float32')
data -= 128.
data /= 128.
return data
def convert_to_grey(data):
images_grey = np.average(data, axis=3)
images_grey = np.expand_dims(images_grey, axis=3)
return images_grey
def undo_normalize(data):
return (data*128 + 128)/255
# In[87]:
X_train = center_normalize(X_train)
X_valid = center_normalize(X_valid)
X_test = center_normalize(X_test)
# In[88]:
plot_images(10, X_train, y_train, 'writeup_images/examples_X_train_normalized.jpg')
# ### Model Architecture
#
# ### Input
# The LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since traffic signs images are RGB, and converting them to greyscale (C=1) didn't improve accuracy, I set C equals 3.
#
# ### Architecture:
# **Layer 1: Convolutional.** The output shape should be 28x28x6.
#
# **Activation.** Your choice of activation function. I used ReLU activation (https://en.wikipedia.org/wiki/Rectifier_(neural_networks).
#
# **Pooling.** The output shape should be 14x14x6.
#
# ---
# **Layer 2: Convolutional.** The output shape should be 10x10x16.
#
# **Activation.** Your choice of activation function. Again, I used ReLU activation.
#
# **Pooling.** The output shape should be 5x5x16.
#
# **Flatten.** Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. The easiest way to do is by using `tf.contrib.layers.flatten`, which is already imported for you.
#
# ---
# **Layer 3: Fully Connected.** This should have 120 outputs.
#
# **Activation.** ReLU activation.
#
# **Regularization.** I used dropout regularization with probabilty of dropout equals 50%
#
# ---
# **Layer 4: Fully Connected.** This should have 84 outputs.
#
# **Activation.** ReLU activation.
#
# **Regularization.** I used dropout regularization with probabilty of dropout equals 50%
#
# ---
# **Layer 5: Fully Connected (Logits).** This should have 43 outputs.
#
# ### Output
# Return the result of the 2nd fully connected layer.
# In[89]:
import tensorflow as tf
from sklearn.utils import shuffle
EPOCHS = 40
BATCH_SIZE = 128
# In[90]:
x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, n_classes)
# In[91]:
from tensorflow.contrib.layers import flatten
# Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
mu = 0
sigma = 0.1
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma))
conv1_b = tf.Variable(tf.zeros(6))
conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
conv2_b = tf.Variable(tf.zeros(16))
fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
fc1_b = tf.Variable(tf.zeros(120))
fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
fc2_b = tf.Variable(tf.zeros(84))
fc3_W = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))
fc3_b = tf.Variable(tf.zeros(n_classes))
# In[92]:
def LeNet(x, dropout):
# SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.
conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b
# SOLUTION: Activation.
conv1 = tf.nn.relu(conv1)
# SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
# SOLUTION: Activation.
conv2 = tf.nn.relu(conv2)
# SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
# SOLUTION: Flatten. Input = 5x5x16. Output = 400.
fc0 = flatten(conv2)
# SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
fc1 = tf.matmul(fc0, fc1_W) + fc1_b
# SOLUTION: Activation.
fc1 = tf.nn.relu(fc1)
fc1 = tf.nn.dropout(fc1, dropout)
# SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
fc2 = tf.matmul(fc1, fc2_W) + fc2_b
# SOLUTION: Activation.
fc2 = tf.nn.relu(fc2)
fc2 = tf.nn.dropout(fc2, dropout)
# SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.
logits = tf.matmul(fc2, fc3_W) + fc3_b
return logits
# ### Train, Validate and Test the Model
# A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation
# sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
#
# #### I used regularization for the second time: L2 regulatization prevents model from overfitting. Values of Learning rate and L2 hyperparam was chosen experimentally.
# In[93]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set is calculated and reported as well.
rate = 0.0007
l2_param = 0.007
logits = LeNet(x, keep_prob)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy + l2_param*(tf.nn.l2_loss(conv1_W) + tf.nn.l2_loss(conv1_b) + tf.nn.l2_loss(conv2_W) + tf.nn.l2_loss(conv2_b) + tf.nn.l2_loss(fc1_W) + tf.nn.l2_loss(fc1_b) + tf.nn.l2_loss(fc2_W) +
tf.nn.l2_loss(fc2_b) +
tf.nn.l2_loss(fc3_W) +
tf.nn.l2_loss(fc3_b)))
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
# In[94]:
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_loss = 0
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
loss, accuracy = sess.run([loss_operation, accuracy_operation], feed_dict={x: batch_x, y: batch_y, keep_prob: 1.})
total_accuracy += (accuracy * len(batch_x))
total_loss += (loss * len(batch_x))
return total_loss / num_examples, total_accuracy / num_examples
# ### Main part of the implementation. Here I am training the model on batches over all epochs (which takes a lot of time). Then the model is saved.
# In[95]:
# Arrays below store data to plot loss and accuracy over epochs.
validation_loss_arr = []
training_loss_arr = []
validation_accuracy_arr = []
training_accuracy_arr = []
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
print()
for i in range(EPOCHS):
X_train, y_train = shuffle(X_train, y_train)
X_valid, y_valid = shuffle(X_valid, y_valid)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5})
validation_loss, validation_accuracy = evaluate(X_valid, y_valid)
training_loss, training_accuracy = evaluate(X_train, y_train)
validation_loss_arr.append(validation_loss)
training_loss_arr.append(training_loss)
validation_accuracy_arr.append(validation_accuracy)
training_accuracy_arr.append(training_accuracy)
print("EPOCH {} ...".format(i+1))
print("Train Accuracy = {:.3f}".format(training_accuracy))
print("Validation Accuracy = {:.3f}".format(validation_accuracy))
print("Train Loss = {:.3f}".format(training_loss))
print("Validation Loss = {:.3f}".format(validation_loss))
print()
saver.save(sess, './traffic_signs.chkp')
print("Model saved")
print("Done")
# #### Measuer the accuracy on test data.
# In[96]:
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
test_loss, test_accuracy = evaluate(X_test, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy))
print("Test Loss = {:.3f}".format(test_loss))
# #### Plot the accuracy
# In[97]:
plt.plot(training_accuracy_arr, 'b') # training accuracy
plt.plot(validation_accuracy_arr, 'r') # validation accuracy
plt.rcParams["figure.figsize"] = [10, 5]
plt.title('Train (blue) and Validation (red) Accuracies over Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.show()
# #### Plot the loss
# In[98]:
plt.plot(training_loss_arr, 'b') # training loss
plt.plot(validation_loss_arr, 'r') # validation loss
plt.rcParams["figure.figsize"] = [10, 5]
plt.title('Train (blue) and Validation (red) Loss over Epochs')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.show()
# ---
#
# ## Step 3: Run a Model on few Test Images
#
# ### Load and Output the Images
# In[150]:
indices = np.random.choice(list(range(len(X_test))), size=10, replace=False)
# Obtain the images and labels
test = X_test[indices]
labels = y_test[indices]
# ### Predict the Sign Type for Each Image
# In[151]:
predictions = tf.argmax(logits, 1)
sm = tf.nn.softmax(logits)
top_k_val, top_k_idx = tf.nn.top_k(sm, k=5)
def predict_cifar10(X_data):
sess = tf.get_default_session()
logit_results, prediction_results, top_k_vals, top_k_idxs, softmax_results = sess.run([logits, predictions, top_k_val, top_k_idx, sm], feed_dict={x: X_data, keep_prob: 1.})
return logit_results, prediction_results, top_k_vals, top_k_idxs, softmax_results
# In[152]:
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
logit_results, prediction_results, top_k_vals, top_k_idxs, softmax_results = predict_cifar10(test)
final_preds = [class_names[pred] for pred in prediction_results]
# #### Print predictions on sample images
# In[153]:
print('Predictions on traffic sign images:\n')
for i in range(traffic_signs.shape[0]):
print('{:30} :(Prediction) {}'.format(class_names[labels[i]], final_preds[i]))
# ### Output Top 5 Softmax Probabilities For Test images
# In[167]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
def pred_certainty_str(top_k_val, top_k_idx):
# Convert top k indices into strings
top_k_pred = [class_names[idx] for idx in top_k_idx]
pcs = ''
for i in range(5):
pcs += '{}: {:.2f}%\n'.format(top_k_pred[i].replace('\n', ''), top_k_val[i] * 100)
return pcs
def plot_images2(path):
for i, image in enumerate(test):
plt.rcParams["figure.figsize"] = [15, 9]
plt.subplot(2, 5, i+1)
plt.imshow(undo_normalize(image))
plt.title('%s' % class_names[labels[i]])
plt.xlabel(pred_certainty_str(top_k_vals[i], top_k_idxs[i]))
plt.tight_layout()
plt.savefig(path)
plt.show()
# In[168]:
plot_images2('writeup_images/examples_5_softmax.jpg')
# In[ ]:
|
from keras.layers import Input, Dense, Flatten
from keras.models import Model
def model(input_shape=(150,150,3)):
# Input layer
inputs = Input(shape=input_shape)
# Hidden & output layers
x = Dense(32, activation='relu')(inputs)
x = Dense(32, activation='relu')(x)
x = Flatten()(x)
predictions = Dense(2, activation='softmax')(x)
return Model(inputs=inputs, outputs=predictions)
|
unos=int(raw_input("Unesi broj izmedu 1 i 100:"))
for unos in range(1,unos+1):
if unos%15==0:
print "FizzBuzz"
elif unos%5==0:
print "Buzz"
elif unos%3==0:
print "Fizz"
else:
print unos
|
#!/usr/bin/env python3
import sys
def main(args):
print("Hello world!")
pos=(0,0)
x=0
up=(0,1)
down=(0,-1)
left=(1,0)
right=(-1,0)
dir=[up,left,down,right]
for i in argv[1]:
if (i=='L'):
x+=1
elif (i=='R'):
x-=1
if (x==4):
x=0
if (x==-1):
x=3
if (i!='O' and i!='L' and i!='R'):
pos+=dir
return 0
if __name__ == "__main__":
main(sys.argv)
|
import csv, os
# Function to grab the CSV files and prep them for the CSV Reader.
def filelist(*files):
for f in files:
global fname
fname = os.path.basename(f) # Assign the file names to the fname variable.
with open(f) as fobj:
next(fobj)
for line in fobj:
yield line
# Write the data from the collected CSV files into a new CSV file.
writer = csv.writer(open('docs/merged.csv', 'wb'))
writer.writerow(['email_hash', 'category', 'filename'])
try:
for row in csv.reader(filelist('docs/clothing.csv', 'docs/accessories.csv', 'docs/household_cleaners.csv')):
row.append(fname) # Append the new filename column.
writer.writerow(row)
print row
except csv.Error as e:
sys.exit('line %d: %s' % (reader.line_num, e)) |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 15 10:22:11 2021
@author: Jarrod Daniels
"""
import string
### takes a single integer as input and returns the sum of the integers from zero to the input parameter.
def add_it_up(int):
total = 0
num_list = list(range(1, int+1))
for num in num_list:
total += num
print(total)
return total
add_it_up(5)
"""
Creates a basic ceasar cypher that takes in a lower case string and returns the string shifted N times
"""
def c_cypher(str, n):
return_string = ''
alphabet_string = string.ascii_lowercase
alphabet_list = list(alphabet_string)
for letter in str:
if letter == ' ':
return_string += ' '
else:
index_to_ref = alphabet_list.index(letter)+4
if index_to_ref > 26:
index_to_ref -= 26
return_string += alphabet_list[index_to_ref]
print(return_string)
return(return_string)
example_string = "holland lopz"
n = 5
c_cypher(example_string, n)
# Other implementation using minimal functions
def caesar(plain_text, shift_num):
letters = string.ascii_lowercase
mask = letters[shift_num:] + letters[:shift_num]
trantab = str.maketrans(letters, mask)
print(plain_text.translate(trantab))
caesar(example_string, 4)
|
#
# Script to generate puzzles based on Raymond Smullyan's
# 'Alice in the Forest of Forgetfulness' puzzles from
# 'What is the Name of this Book?'
#
# first we define the days of the week
daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# if we say one of several days was yesterday, return the possible days for 'today'
def fromYesterdays(yesterdays):
return [daysOfWeek[(daysOfWeek.index(day) + 1) % (len(daysOfWeek))] for day in yesterdays]
# if we say one of several days will be tomorrow, return the possible days for 'today'
def fromTomorrows(tomorrows):
return [daysOfWeek[(daysOfWeek.index(day) - 1) % (len(daysOfWeek))] for day in tomorrows]
# The Lion and the Unicorn lie on certain days
lionLying =['Monday', 'Tuesday', 'Wednesday']
unicornLying = ['Thursday', 'Friday','Saturday']
# given a list of days, what are the other days of the week?
def otherDays(days):
return [day for day in daysOfWeek if day not in days]
# we can find when the Lion and Unicorn are truthful
lionTruthful = otherDays(lionLying)
unicornTruthful = otherDays(unicornLying)
# return the days of the week that are common to both lists
def intersect(a, b):
return [item for item in a if item in b]
# return the days of the week that appear in either list
def union(a, b):
return list(a) + [item for item in b if item not in a]
# create sets of statements that the creatures can make
def annotatedVariations(base):
today = {'description': base['actor'] + ' told ' + base['state'] + ' today', 'days': base['days']}
tomorrow = {'description': base['actor'] + ' will tell ' + base['state'] + ' tomorrow', 'days': fromTomorrows(base['days'])}
yesterday = {'description': base['actor'] +' told ' + base['state'] + ' yesterday', 'days': fromYesterdays(base['days'])}
return [today, tomorrow, yesterday]
def individualDays():
return [{'description': 'Today is ' + d, 'days':[d]} for d in daysOfWeek]
def weekAndWeekend():
weekend = ['Saturday', 'Sunday']
return [{'description': 'Today is a weekday', 'days': otherDays(weekend)},
{'description': 'It is the weekend', 'days': weekend}]
allAnnotated = [];
allAnnotated.extend(annotatedVariations({'actor': 'Lion', 'state': 'lies', 'days': lionLying}))
allAnnotated.extend(annotatedVariations({'actor': 'Lion', 'state': 'truths', 'days': lionTruthful}))
allAnnotated.extend(annotatedVariations({'actor': 'Unicorn', 'state': 'lies', 'days': unicornLying}))
allAnnotated.extend(annotatedVariations({'actor': 'Unicorn', 'state': 'truths', 'days': unicornTruthful}))
allAnnotated.extend(individualDays())
allAnnotated.extend(weekAndWeekend())
def validPuzzle(lionStatement, unicornStatement):
puzzle = {};
lionPositive = intersect(lionStatement['days'], lionTruthful)
lionNegative = intersect(otherDays(lionStatement['days']), lionLying)
lionDays = union(lionPositive, lionNegative)
unicornPositive = intersect(unicornStatement['days'], unicornTruthful)
unicornNegative = intersect(otherDays(unicornStatement['days']),unicornLying)
unicornDays = union(unicornPositive, unicornNegative)
validDays = intersect(lionDays, unicornDays)
if (len(validDays) != 1):
return puzzle
if ('Lion' in lionStatement['description']):
puzzle['lion'] = ("The Lion says: " + lionStatement['description'].replace("Lion", "I") + '.')
else:
puzzle['lion'] = ("The Lion says: " + lionStatement['description'] + '.')
if ('Unicorn' in unicornStatement['description']):
puzzle['unicorn'] = ("The Unicorn says: " + unicornStatement['description'].replace("Unicorn", "I") + '.')
else:
puzzle['unicorn'] = ("The Unicorn says: " + unicornStatement['description'] + '.')
puzzle['solution'] = validDays[0]
puzzle['explanation'] = explanation1("Lion",lionStatement['days'], lionLying, lionPositive, lionNegative, lionDays)
puzzle['explanation'] = puzzle['explanation'] + " "
puzzle['explanation'] = puzzle['explanation'] + explanation1("Unicorn",unicornStatement['days'], unicornLying, unicornPositive, unicornNegative, unicornDays)
puzzle['explanation'] = puzzle['explanation'] + " Based on what both are saying, the only day it could be is " + validDays[0] +"."
return puzzle
def prettyList(list, conj):
isFirst = True;
result = ""
count = 1
size = len(list)
for s in list:
if not isFirst and size > 2:
result += ", "
isFirst = False
if count == size and size > 1:
if (size == 2):
result += " "
result += conj + " "
count = count +1
result += s
return result
def explanation1(actor, statement, lieDays, daysIfTrue, daysIfFalse, unionDays):
exp1 = actor +" says today"
if len(statement) == 1:
exp1 += " is " + statement[0]
else:
exp1 += " could be " + prettyList(statement, "or")
exp1 += ". We know that " + actor + " lies on " + prettyList(lieDays, "and")
exp1 += ". So if "+ actor + " is telling the truth it can"
if (len(daysIfTrue) == 0):
exp1 += " not be any day (so they must be lying)"
elif (len(daysIfTrue) == 1):
exp1 += " only be " + daysIfTrue[0]
else:
exp1 += " be " + prettyList(daysIfTrue, "or")
exp1 += ", and if "+ actor + " is lying, it can"
if (len(daysIfFalse) == 0):
exp1 += " not be any day (so they must be telling the truth)"
elif (len(daysIfFalse) == 1):
exp1 += " only be " + daysIfFalse[0]
else:
exp1 += " be " + prettyList(daysIfFalse, "or")
exp1 += ". All told, from what " + actor + " says, it could"
if (len(unionDays) == 1):
exp1 += " only be " + unionDays[0]
else:
exp1 += " be " + prettyList(unionDays, "or")
exp1 += "."
return exp1
def jsonForPuzzle(puzzle):
json = '{"lion": "' + puzzle['lion'] +'",' + "\n"
json += '"unicorn": "' + puzzle['unicorn'] +'",' + "\n"
json += '"solution": "' + puzzle['solution'] +'",' + "\n"
json += '"explanation": "' + puzzle['explanation'] +'",' + "\n"
json += '"id": "' + str(puzzle['id']) +'"}'
return json
counter = 0
validPuzzles = []
for s1 in allAnnotated:
for s2 in allAnnotated:
puzzle = validPuzzle(s1,s2)
if(len(puzzle) > 0):
counter = counter + 1
puzzle['id'] = counter
validPuzzles.append(jsonForPuzzle(puzzle))
result = "["
first = True
for p in validPuzzles:
if not first:
result += ", \n"
else:
first = False
result += p
result += "]"
f = open("../data/forest.json","w")
f.write( result )
f.close()
|
# Problem Set 4A
# Name: <your name here>
# Collaborators:
# Time Spent: x:xx
def get_permutations_count(n):
if n==1:
return 1
else:
return n*get_permutations_count(n-1)
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only
# one permuatation is possible
if len(lst) == 1:
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range(len(lst)):
m = lst[i]
print('M=',m)
# Extract lst[i] or m from the list. remLst is
# remaining list
remLst = lst[:i] + lst[i+1:]
print('Remainin list=',remLst)
# Generating all permutations where m is first
# element
for p in permutation(remLst):
print('P is=',p)
l.append([m] + p)
print('Final list=',l)
return l
# Driver program to test above function
if __name__ == '__main__':
# #EXAMPLE
# example_input = 'abc'
# print('Input:', example_input)
# print('Expected Output:', ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])
# print('Actual Output:', get_permutations(example_input))
# # Put three example test cases here (for your sanity, limit your inputs
# to be three characters or fewer as you will have n! permutations for a
# sequence of length n)
pass #delete this line and replace with your code here
permutation_string='abcd'
print('Current permutation string is: ',permutation_string)
letters=list(permutation_string)
print('Converting string to a list for permutations: ',letters)
n=len(permutation_string)
print('Number of permutations will be: ',get_permutations_count(n))
for p in permutation(letters):
print(p ) |
# def build_shift_dict(self, shift):
# shift_dict={}
# alphabeth=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# if 26<shift<1:
# print('Your shift is out of legal range. Try again with shift from 1 to 25 inclusive')
# else:
# for i in range(len(alphabeth)):
# print(i)
# s={}
# s.update({'A':'C'})
# s.update({'B':'C'})
# print(s)
# self_text='Victor Semenov!'
# shift=25
# shift_dict={}
# alphabeth_capitals=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# alphabeth_small=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# if shift>26 or shift<1:
# print('Your shift is out of legal range. Try again with shift from 1 to 25 inclusive')
# else:
# for i,j in enumerate(alphabeth_capitals):
# shift_dict.update({alphabeth_capitals[i]:alphabeth_capitals[i+shift]})
# if i==25:
# break
# for i,j in enumerate(alphabeth_small):
# shift_dict.update({alphabeth_small[i]:alphabeth_small[i+shift]})
# if i==25:
# break
# x=shift_dict
# print(x)
# #return shift_dict
# def apply_shift(self_text, shift):
# '''
# Applies the Caesar Cipher to self.message_text with the input shift.
# Creates a new string that is self.message_text shifted down the
# alphabet by some number of characters determined by the input shift
# shift (integer): the shift with which to encrypt the message.
# 0 <= shift < 26
# Returns: the message text (string) in which every character is shifted
# down the alphabet by the input shift
# '''
# encrypted=''
# temp=[]
# for char in self_text:
# if char in shift_dict:
# # print(shift_dict[char])
# temp.append(shift_dict[char])
# # print(temp)
# else:
# # print(char)
# temp.append(char)
# # print(temp)
# encrypted=''.join(temp)
# print(encrypted)
# apply_shift(self_text, shift)
# def load_words(file_name):
# '''
# file_name (string): the name of the file containing
# the list of words to load
# Returns: a list of valid words. Words are strings of lowercase letters.
# 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_name, 'r')
# # wordlist: list of strings
# wordlist = []
# for line in inFile:
# wordlist.extend([word.lower() for word in line.split(' ')])
# print(" ", len(wordlist), "words loaded.")
# return wordlist
# def is_word(word_list, word):
# '''
# Determines if word is a valid word, ignoring
# capitalization and punctuation
# word_list (list): list of words in the dictionary.
# word (string): a possible word.
# Returns: True if word is in word_list, False otherwise
# Example:
# >>> is_word(word_list, 'bat') returns
# True
# >>> is_word(word_list, 'asdf') returns
# False
# '''
# word = word.lower()
# word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
# return word in word_list
# word_list=load_words('words.txt')
# self_text='Uhbsnq Rdldmnu!'
# def decrypt_message(self_text):
# final=[]
# list_of_string=[]
# decrypted=''
# temp=[]
# shift_dict={}
# alphabeth_capitals=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# alphabeth_small=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# shift=0
# while shift<=25:
# for i,j in enumerate(alphabeth_capitals):
# shift_dict.update({alphabeth_capitals[i]:alphabeth_capitals[i+shift]})
# if i==25:
# break
# for i,j in enumerate(alphabeth_small):
# shift_dict.update({alphabeth_small[i]:alphabeth_small[i+shift]})
# if i==25:
# break
# for char in self_text:
# if char in shift_dict:
# temp.append(shift_dict[char])
# else:
# temp.append(char)
# decrypted=''.join(temp)
# final.append(temp)
# shift+=1
# temp=[]
# list_of_string.append(decrypted)
# wordfin=[]
# for i,j in enumerate(list_of_string):
# word=list_of_string[i].split()
# for key,value in enumerate(word):
# if is_word(word_list, word[key])==True:
# wordfin.append(word[key])
# decrypted=''.join(wordfin)
# wordfin=[]
# print(decrypted)
# decrypt_message(self_text)
class Message(object):
def __init__(self, text):
self.message_text=text
def get_message_text(self):
# return self.message_text
print(self.message_text)
class PlaintextMessage(Message):
def __init__(self, text, shift):
Message.__init__(self, text)
self.shift=shift
def get_shift(self):
# return self.shift
print(self.shift)
def test_self(self):
print('test')
text=str(input('enter text :'))
shift=int(input('enter shift: '))
c=PlaintextMessage(text, shift)
c.get_shift()
c.get_message_text()
|
import pandas as pd
import csv
#MINIMUM_YEAR = 5
MINIMUM_YEAR = 6
#MINIMUM_YEAR = 7
def load_wine_dataset_sheet(wine_data_set_file):
"""
Returns the wine dataset workbook file.
Parameter:
wine_data_set_file: The excel file containing the wine dataset.
Returns:
workbook_file: The workbook of the excel wine dataset.
"""
# Load the Excel document
workbook_file = pd.read_excel(wine_data_set_file, "Sheet1")
return workbook_file
def check_if_wine_is_drinkable_or_not(wine_data_sheet):
"""
Checks if a wine is drinkable or Held.
Parameter:
wine_data_set_file: The excel file containing the wine dataset.
Returns:
None
"""
hold_wine_list = list()
drink_wine_list = list()
no_wine_data_list = list()
wine_dict = dict()
for wine in wine_data_sheet.itertuples(index=False, name="Wine"):
wine_dict = wine._asdict()
drinkable_from = wine_dict["From"]
manufacutred_year = wine_dict["Year"]
if isinstance(drinkable_from, int):
years_to_decide_to_drink_or_not = drinkable_from - manufacutred_year
if years_to_decide_to_drink_or_not >= MINIMUM_YEAR:
wine_data = {
"Years To Decide To Drink or Not": years_to_decide_to_drink_or_not
}
wine_dict.update(wine_data)
hold_wine_list.append(wine_dict)
elif years_to_decide_to_drink_or_not < MINIMUM_YEAR:
wine_data = {
"Years To Decide To Drink or Not": years_to_decide_to_drink_or_not
}
wine_dict.update(wine_data)
drink_wine_list.append(wine_dict)
else:
pass
else:
wine_data = {
"Year": manufacutred_year,
}
wine_dict.update(wine_data)
no_wine_data_list.append(wine_dict)
# Calls write to excel and csv function to write the data to excel and csv.
write_to_excel_and_csv(hold_wine_list,drink_wine_list, no_wine_data_list)
def write_to_excel_and_csv(hold_list, drink_list, no_data_list):
"""
Writes list of hold, drink and no_wine data to a new excel file.
Parameter:
hold_list: List containing a dictionary of wines that can be held.
drink_list: List containing a dictionary of wines that should be drunk.
no_wine_data: List containing a dictionary of wines that should be drink now.
Returns:
None
"""
hold_data = pd.DataFrame.from_dict(hold_list)
drink_data = pd.DataFrame.from_dict(drink_list)
no_data = pd.DataFrame.from_dict(no_data_list)
hold_data.columns = [column.strip().replace('_', ' ') for column in hold_data.columns]
drink_data.columns = [column.strip().replace('_', ' ') for column in drink_data.columns]
no_data.columns = [column.strip().replace('_', ' ') for column in no_data.columns]
hold_data.to_excel('hold_data.xlsx', index=False)
hold_data.to_csv("hold.csv", index=False)
drink_data.to_excel("drink.xlsx", index=False)
drink_data.to_csv("drink.csv", index=False)
no_data.to_excel("no_data.xlsx", index=False)
no_data.to_csv("no_data.csv", index=False)
def main():
"""
Defines the main entry point of the script.
"""
# Declare a constant to store the excel file name.
CLEANED_WINE_DATASET_FILE = "cleaned_drink_duration_dataset_binary_attributes.xlsx"
# Loads and read file from excel
cleaned_data_sheet = load_wine_dataset_sheet(CLEANED_WINE_DATASET_FILE)
# Determines which wines are drinkable
check_if_wine_is_drinkable_or_not(cleaned_data_sheet)
# Check if the file name is main, if the name is main run the script else do not run the script.
if __name__ == "__main__":
main() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 13:28:49 2018
@author: paul
"""
import copy
class Solution:
def __init__(self, places, graph):
"""
places: a list containing the indices of attractions to visit
p1 = places[0]
pm = places[-1]
"""
self.g = 0 # current cost
self.graph = graph
self.visited = [places[0]] # list of already visited attractions
self.not_visited = copy.deepcopy(places[1:]) # list of attractions not yet visited
def __str__(self):
return "v = " + str(self.visited) + " " + "g = " + str(self.g)
def add(self, idx):
"""
Adds the point in position idx of not_visited list to the solution
"""
self.g += self.graph[self.visited[-1], self.not_visited[idx]]
self.visited.append(self.not_visited[idx])
del self.not_visited[idx]
def swap(self, i, j): # permute la position de deux noeuds dans la solution
# i et j ne doivent pas etre egaux a 0 ou a len(s.visited)
# on met a jour le cout total
if i>j:
i, j = j, i
p_im1 = self.visited[i-1]
p_ip1 = self.visited[i+1]
p_i = self.visited[i]
p_jm1 = self.visited[j-1]
try:
p_jp1 = self.visited[j+1]
except:
print("exception")
print(j)
print(len(self.visited))
p_j = self.visited[j]
# on doit differencier le cas ou i+1 = j
# on retire les couts initiaux
self.g -= self.graph[p_im1,p_i] + self.graph[p_i,p_ip1]
self.g -= self.graph[p_jm1,p_j] + self.graph[p_j,p_jp1]
if i+1 == j:
self.g += self.graph[p_i,p_ip1]
# on permute les elements
self.visited[i], self.visited[j] = self.visited[j], self.visited[i]
# on somme les couts des nouveaux chemins
p_im1 = self.visited[i-1]
p_ip1 = self.visited[i+1]
p_i = self.visited[i]
p_jm1 = self.visited[j-1]
p_jp1 = self.visited[j+1]
p_j = self.visited[j]
self.g += self.graph[p_im1,p_i] + self.graph[p_i,p_ip1] + self.graph[p_jm1,p_j] + self.graph[p_j,p_jp1]
if i+1 == j:
self.g -= self.graph[p_i,p_ip1]
|
import re
rex = '[0-9]+'
pattern = re.compile(rex)
s = 'John was born in 1970, he joined SEAL force at the age of 30. John was killed in action in 2016.'
print(pattern.findall(s)) |
"""
作者:徐飞
时间:2019
版本:04
功能:汇率转换
"""
def main():
"""
主函数
"""
ratio = eval(input('请输入汇率值:'))
money = input("请输入带单位的货币金额:")
money_unite = money[-3:]
money_value = eval(money[:-3])
if money_unite == 'CNY':
exchange_rate = 1 / ratio
elif money_unite == 'USD':
exchange_rate = ratio
else:
exchange_rate = -1
if exchange_rate != -1:
# 调用函数
out_currency = lambda x, y: x * y
out_money = out_currency(money_value, exchange_rate)
print(out_money)
else:
print('暂不支持该货币!')
if __name__ == '__main__':
main()
|
"""
作者:徐飞
时间:2019
版本:02
功能:汇率转换
"""
money = input("请输入带单位的货币金额:")
money_unite = money[-3:]
money_value = eval(money[:-3])
ratio = eval(input("请输入汇率:"))
if money_unite == 'CNY':
usd = money_value / ratio
print("所得美元金额:", usd)
elif money_unite == 'USD':
rmb = money_value * ratio
print("所得人民币金额:", rmb)
else:
print('暂不支持该种货币!') |
from tkinter import *
import ReadThread
import Paddle
import Ball
import math
import random
class PongGame():
def __init__(self):
#Start the reader thread
self.readerThread = ReadThread.MyThread(10)
self.readerThread.setName("Reader")
self.readerThread.start()
#Frame parameters
self.width = 1200;
self.height = 600;
self.borderWidth = 10;
#Paddle parameters
self.paddlesDistance = self.width / 120;
self.paddleThickness = self.width / 40;
self.paddleLength = 5 * self.height / 24;
self.paddleMinPos = self.borderWidth + self.paddleLength / 2
self.paddleMaxPos = self.height - self.borderWidth - self.paddleLength / 2
#Ball parameters
self.ballRadius = self.width / 100
self.ballPosX = self.width / 2
self.ballPosY = self.height / 2
self.ballSpeed = 10
#Start the tkinter context
self.root = Tk()
self.root.title("Pong")
self.canvas = Canvas(self.root, width = self.width, height = self.height, bg='#101010')
self.debugText = self.canvas.create_text(50, 50, text="", fill="#EEEEEE") #Debug text, to print current values of the sensors
self.canvas.focus_set()
self.root.protocol("WM_DELETE_WINDOW", self.close) #Set a custom close function to be able to stop the reader thread on closing the frame
#The 2 paddles
self.paddleLeft = Paddle.Paddle(self.canvas, self.paddlesDistance, self.paddleThickness, self.paddleLength, self.height / 2, self.paddleMinPos, self.paddleMaxPos)
self.paddleRight = Paddle.Paddle(self.canvas, self.width - self.paddlesDistance - self.paddleThickness, self.paddleThickness, self.paddleLength, self.height / 2, self.paddleMinPos, self.paddleMaxPos)
#The ball
self.ball = Ball.Ball(self.canvas, self.ballPosX, self.ballPosY, self.ballRadius, -math.pi/3, self.ballSpeed)
#The values of the sensors
self.sensor1 = 0
self.sensor2 = 0
self.update()
self.root.mainloop()
#Update the game
def update(self):
#Update the debug text to the current sensor values
if self.readerThread.isRead1 == False:
self.sensor1 = self.readerThread.getSensors(1)
print(self.sensor1)
self.canvas.itemconfigure(self.debugText, text="Sensor 1 : " + str(self.sensor1) + "\nSensor 2 : " + str(self.sensor2))
self.paddleLeft.update(self.sensor1)
if self.readerThread.isRead2 == False:
self.sensor2 = self.readerThread.getSensors(2)
self.paddleRight.update(self.sensor2)
self.ball.update(self.width, self.height, self.paddleLeft, self.paddleRight)
self.canvas.pack()
self.root.after(10, self.update)
#Custom close method : stop the reader thread and stop the TKinter frame
def close(self):
self.readerThread.stop()
self.root.destroy()
###########################
game = PongGame() #Start the pong game
# def pascal(n):
# line = [1]
# for k in range(n):
# line.append(line[k] * (n-k) / (k+1))
# return line
# print pascal(8)
|
"""
6. Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
"""
from math import pi
raio_circulo = float(input("Digite o raio do círculo: "))
area_circulo = pi * (raio_circulo ** 2)
print(f"A área do círculo é: {area_circulo:.2f} m2") |
"""
Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
Calcule e mostre o total do seu salário no referido mês.
"""
valor_hora = float(input("Quanto você recebe por hora? R$ "))
numero_horas_mes = float(input("Quantas horas você trabalha por mês? "))
salario = valor_hora * numero_horas_mes
print(f"O salário a receber é igual a R${salario:.2f}") |
def exchange(money):
return money* 9.912
if __name__ == "__main__":
money = float(input('请输入要转化的人民币,退出输入0:'))
while money:
print('{0}元人民币={1}俄罗斯卢布'.format(money,exchange(money)))
money = float(input('请输入要转化的人民币,退出输入0:')) |
edad = int(input("cuantos años tienes?\n"))
eleccion = input("a que quieres cambiar tu edad?\ndias horas segundos\n")
if eleccion == "dias":
dias = edad * 365
print("tienes" , dias , "dias de edad")
elif eleccion == "horas":
horas = (edad * 365) * 24
print("tienes" , horas , "horas de edad")
elif eleccion == "segundos":
segundos = ((edad * 365) * 24) * 3600
print ("tienes" , segundos , "segundos de edad")
|
#Program that does left factoring on production rules
#Function to accept rules
def accept_rules():
rules = {}
non_terminals = []
y = 'y'
while (y == 'y'):
string = input("Enter production rule : ")
for i in range(len(string)):
if string[i] == '=':
antecedent = string[0:i]
non_terminals.append(antecedent)
get_cons = string[i+1:]
consequent = get_cons.split('|')
#Creating key value pair
rules[antecedent] = consequent
y = input("Continue?y/n : ")
return rules, non_terminals
#Function for getting the terminals in production rules.
def get_terminals(rules):
normalised_text = '(terminal)'
normalised_list = []
terminals = []
rules_copy = rules.copy()
for i in rules.keys():
get_list = rules[i]
for element in get_list:
copy = element
for index in range(len(element)):
#Normalizing the non_terminal by replacing it with the string normalized_text.
#Makes it easier for comparison purposes
if element[index].islower():
copy = element[0:index] + normalised_text + element[(index+1):]
normalised_list.append(copy)
terminals.append(element[index])
rules_copy[i] = normalised_list
normalised_list = []
#Returns the list of terminals present in the production rules and the dictionary of rules with normalized terminals.
return terminals, rules_copy
def get_term_nonterm_from_rule(rules, antecedent, terminals, non_terminals):
get_consequent = rules[antecedent]
term_store = ''
non_term_store = ''
for i in get_consequent:
for j in i:
if j in terminals:
term_store = term_store + j + '|'
elif j.isupper() and (j not in non_term_store):
non_term_store = non_term_store + j
return non_term_store, term_store[:len(term_store)-1] #slicing to remove the last | present in the string.
#Function that does left factoring
def left_factoring(rules, rules_norm, terminals, non_terminals):
copy_rules = rules.copy()
for antecedent in rules_norm.keys():
get_consequent = rules_norm[antecedent]
flag = True
if len(get_consequent) > 1 :
store = get_consequent[0]
#Loop to check if the consequents are similar. Normalizing the terminals helps in this comparison.
for element in range(1, len(get_consequent)):
temp = get_consequent[element]
if temp != store:
flag = False
break
if flag == True:
non_term, term = get_term_nonterm_from_rule(rules, antecedent, terminals, non_terminals)
copy_rules[antecedent+'\''] = term.split('|')
copy_rules[antecedent] = antecedent + '\'' + non_term
return copy_rules
#Control function
def main():
rules, non_terminals = accept_rules()
terminals, rules_norm = get_terminals(rules)
#print (rules, non_terminals, terminals, rules_norm)
new_rules = left_factoring(rules, rules_norm, terminals, non_terminals)
print ("After left factoring : ")
print (new_rules)
main()
|
game_board = []
n = 3
end_game = False
player1 = True
def create_game_board():
for i in range(n):
tmp = []
for j in range(n):
tmp.append(" ")
game_board.append(tmp[:])
def print_game_board():
for i in range(0, 3):
print(" {0} | {1} | {2}".format(game_board[i][0], game_board[i][1], game_board[i][2]))
if i != 2:
print(' ---------')
def input_player():
global player1
move = input("Player {0}: Please, make your move (x, y): ".format(1 if player1 else 2))
xy = move.split(",")
x = int(xy[0])
y = int(xy[1])
if x > 2 or y > 2:
print("Invalid position!")
elif game_board[x][y] == " ":
game_board[x][y] = "X" if player1 else "O"
player1 = not player1
else:
print("This position has already been fill")
def player_win():
for i in range(0,3):
if game_board[i][0] == game_board[i][1] and game_board[i][1] == game_board[i][2]:
return game_board[i][0] == "X" or game_board[i][0] == "O";
for i in range(0,3):
if game_board[0][i] == game_board[1][i] and game_board[1][i] == game_board[2][i]:
return game_board[0][i] == "X" or game_board[0][i] == "O";
return False
def main():
global end_game
create_game_board()
while not end_game:
print()
print_game_board()
print()
input_player()
if player_win():
end_game = True
print_game_board()
print("Player {0} win!".format("1" if not player1 else "2"))
main()
|
name = raw_input("Enter Name:")
for i in range(1,11):
print i
print "Hello, "+ name |
# Given two arrays write a function to find out if two arrays have the
# same frequency of digits
# Examples
one = [[1,2,3,4], [1,2,3,4]]
# [1,2,3,4], [1,4,5,6] = two
# [1,2,3,4], [1,4,4,2] = three
# [1,2,3,4], [1,4,3,2] = four
# [1,2,3,4,5], [1,2,3,4] = five
# Create frequency dictionary for first array
# loop through numbers in the array
def create_frequency(array):
frequency_dict = {}
# loop through numbers in the array
for num in array:
# if num exists in array already, add one to its value, else create key value pair with value set to 1
if num in frequency_dict:
frequency_dict[num] += 1
else:
frequency_dict[num] = 1
# return the frequency dictionary for that array
return frequency_dict
def compare_frequencies(combined_array):
if len(combined_array[0]) != len(combined_array[1]):
return False
# create frequency dict for first array
first_frequency = create_frequency(combined_array[0])
# create frequency dict for second array
second_frequency = create_frequency(combined_array[1])
# loop through keys in the first frequency dict
for key in first_frequency:
# if that key doesn't exist in second frequency dict, return False
try:
if second_frequency[key]:
pass
except:
return False
# if key does exist in second frequency, check that the values match
if first_frequency[key] != second_frequency[key]:
return False
# if all of the above do not evaluate to false, return True
return True
print((compare_frequencies(one)))
|
#!/usr/bin/env python
#coding:utf8
################################################################
# function: this script provides functions for other programs
# history : 2019.07.25 V1.0
# author : gaoyuanyong
###############################################################
import numpy as np
import csv
import math
from math import sin,radians,cos,asin,sqrt
import parameter
# function
class function:
def __int__(self):
pass
def SphereDistance(lon1, lat1, lon2, lat2):
# This function compute the great-circle distance
# between (lat1, lon1) and (lat2, lon2) on
# a sphere with given radius.
radius = 6371.0 # radius of Earth, unit:KM
# degree to radians
lon1, lat1,lon2, lat2 = map(radians,[lon1, lat1,lon2, lat2])
dlon = lon2 -lon1
dlat = lat2 -lat1
arg = sin(dlat*0.5)**2 + \
cos(lat1)*cos(lat2)*sin(dlon*0.5)**2
dist = 2.0 * radius * asin(sqrt(arg))
return dist
def getAzimuth(lon1, lat1, lon2, lat2):
# This function compute the azimuth from A(lat1, lon1) to
# B(lat2, lon2) on lats and lons on degree
lon1, lat1, lon2, lat2 = map(radians,[lon1,lat1,lon2,lat2])
cosC = cos(90-lat2)*cos(90-lat1) + \
sin(90-lat2)*sin(90-lat1)*cos(lon2-lon1)
sinC = sqrt(1-cosC*cosC)
if abs(sinC) < 1e-10:
print(lon1, lat1, lon2, lat2)
sinC = 0.0001
arg1 = (sin(90-lat2)*sin(lon2-lon1))/sinC
A = asin(arg1)
A = A*180/math.pi
if lat2 >= lat1:
if lon2 >= lon1:
Azimuth = A
# print("1")
else:
Azimuth = 360 + A
# print("2")
else:
Azimuth = 180 - A
#print("3/4")
return Azimuth
if __name__ == '__main__':
print("funcion name :","SphereDistance")
print("funcion name :","getAzimuth")
|
password = "mulualem03"
trials = 0
while password != "password":
# if the values of the two operands are not equal
if trials == 5:
print("Terminate")
break;
else:
password = input("Enter password: ")
trials += 1
if password == "password":
print("Welcome In")
|
class Times:
def __init__(self, nome, estado):
self.nome = nome
self.estado = estado
class Pilha(object):
def __init__(self):
self.dados = []
def empilha(self, elemento):
self.dados.append(elemento)
def desempilha(self):
if not self.vazia():
return self.dados.pop(-1)
def vazia(self):
return len(self.dados) == 0
def imprimir(self):
if len(self.dados) == 0:
print('Pilha vazia.')
else:
print(self.dados)
############################
t1 = Times('Grêmio','RS')
t2 = Times('Internacional','RS')
t3 = Times('Santos','SP')
t4 = Times('Vasco','RJ')
pilha = Pilha()
pilha.empilha(t1.nome)
pilha.imprimir()
input()
pilha.empilha(t2.nome)
pilha.imprimir()
input()
pilha.empilha(t3.nome)
pilha.imprimir()
input()
pilha.desempilha()
pilha.imprimir()
input()
pilha.empilha(t4.nome)
pilha.imprimir()
input()
pilha.desempilha()
pilha.imprimir()
input()
|
'''
Created on Feb 16, 2016
@author: sumkuma2
'''
"""
Python Identity Operators:
Identity operators compare the memory locations of two objects. There are two Identity operators explained below:
Operator | Description
------------------------------------------------------
1) Is | Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
Example : x is y, here is results
in 1 if id(x) equals id(y).
2) is not | Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.
Example:
x is not y, here is not results in 1 if id(x)
is not equal to id(y).
"""
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"
if ( a is not b ):
print "Line 4 - a and b do not have same identity"
else:
print "Line 4 - a and b have same identity" |
list1= ['phusics','mathemetics',2341,9876]
list2= [1,2,3,4,5,6,7]
print "\n Before modification",list1
print "Value at index position 2 before insertion: ",list1[2]
list1[2]='chemestry'
print "Value at index position 2 after insertion: ",list1[2]
print "\n After modification",list1
print "lenght of list2",len(list2)
list3 = list1 + list2
print "Element of list3 after concatenation of list1 and list2 :",list3
'''Negative count of list from right'''
print "8th value of list3 from right :",list3[-8]
print "Compares elements of both lists : list1 and list2:: ",cmp(list1,list3)
print "Max value in the list3 :",max(list2)
#print list2[4]
|
#import exceptions #its a module under which All Exceptions class are defined
#print dir(exceptions)
#print help(exceptions)
# User defined Exceptions class
class ShortInput(Exception):
'''Short input exception class '''
def __init__(self,length,atleast):
'''Initializing ShortInput Calss'''
self.length=length #object variable
self.atleast=atleast
print "Short Input Exception:, Input Should be minimum 6byte"
#obj = ShortInput(3,9)
try:
s=raw_input("Enter some data:")
if len(s) <6:
raise ShortInput(len(s),6)
except ShortInput,sie:
print "You entered %s bytes expected %s bytes"%(sie.length,sie.atleast)
else:
print "Your data is %s"%s
|
import re
#use of (r) raw string and boudary character
s=''' Mobile 9844816548 email [email protected] 8861733377
[email protected],[email protected]'''
print re.findall('\\b\d{10}\\b',s) #
print re.findall(r'\b\d{10}\b',s) # r is to escape all special symbol in the string
s=''' Mobile 9844816548 \n\t email [email protected] 8861733377
[email protected]\n\t,[email protected]'''
print s
#used r(raw string) to escape special symbol from string
s=r''' Mobile 9844816548 \n\t email [email protected] 8861733377
[email protected]\n\t,[email protected]'''
print s
#extract email address from given string
s=''' Mobile 9844816548 \n\t email [email protected] 8861733377
[email protected]\n\t,[email protected]'''
print re.findall(r'\b[\w.]+@\w+.\w{2,3}\b',s)
print re.findall(r'\b[\w.]+@\w+.\w{2,3}\b',s).__len__()
|
'''
Created on Feb 16, 2016
@author: sumkuma2
'''
# Sample for loop using a List
## define a list
shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
## Read shuttles list and store the value of each element into var shuttle and display on screen
for shuttle in shuttles:
print shuttle
print "------------------------------------------------------------------------------------"
'''
To print index and its value, try enumerate(). It simplify a commonly used looping methods. It provides all iterable collections with the
same advantage that iteritems() affords to dictionaries -- a compact, readable, reliable index notation:
'''
# A list of shuttles , to print index and value using enumerate function
#shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
## Read shuttles list and enumerate into index and value
for index, value in enumerate(shuttles):
print index, value
|
'''
Created on Feb 14, 2016
@author: sumkuma2
'''
'''
Accessing Command Line Arguments:
The Python sys module provides access to any command-line arguments via the sys.argv. This serves two
purpose:
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
'''
import sys;
print "\n Number of command line arguments passed",len(sys.argv);
print "\n Argument List :",str(sys.argv)
for arg_position in range (len(sys.argv)):
print "\n arg:",sys.argv[arg_position] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.