text
stringlengths 37
1.41M
|
---|
def gcd(a,b):
a = abs(int(a))
b = abs(int(b))
if b > a:
a, b = b, a
# @@@@@@ very good to know! a,b = b,a !!
while b != 0:
new_a = b
new_b = a % b
a = new_a
b = new_b
return new_a
def main():
a = (input("Enter your first value: "))
while a != "":
b = (input("Enter your second value: "))
print("The GCD of " + str(a) + " and " + str(b) + " is " + str(gcd(a,b)))
a = (input("Enter your first value: "))
if __name__ == "__main__":
main()
|
def gcd(a,b):
if a < b:
a,b = abs(b),abs(a)
if b == 0:
return a
return gcd(b,a%b)
def main():
int1 = int(input("Enter first integer value: "))
int2 = int(input("Enter second integer value: "))
print("Your integers are {0} and {1}, and their GCD is {2}.".format(int1,int2,gcd(int1,int2)))
if __name__ == "__main__":
main()
|
def mine_convert(s,numRows):
if numRows == 1:
return s
else:
keynum = 2 * numRows - 2
mystrings = [""] * numRows
myanswer = ""
rows = 1
while rows <= numRows:
for each_index, each_value in enumerate(s):
if each_index % keynum == rows - 1 or each_index % keynum == keynum - rows + 1:
mystrings[rows-1] += each_value
rows += 1
for eachrow in mystrings:
myanswer += eachrow
return myanswer
"""
My answer above stil returns correct answer.
However, I am still disqualified because of "Time Limit Exceeded"
Below is the solution to that.
Things to note:
1. I could've used comprehensive list (line 7)
2. Without having double loops (while loop and for loop), I could've define the row more effectively. Refer the codes Below.
3. Both answers approached this quesiton using "%", but different algorithm.
- I set two conditions, but the ideal_answer has important algorithm for numbers between the main columns.
- refer to line 46.
4. str.join method -- refer to list methods.
"""
def answer_convert(s, numRows):
if numRows <= 1:
return s
rows = ['' for i in range(0, numRows)]
for i, c in enumerate(s):
new_row = i % (2 * numRows - 2)
# print(new_row,numRows-1)
if new_row > numRows - 1:
new_row = 2 * numRows - new_row - 2
rows[new_row] += c
return ''.join(rows)
print(bool(mine_convert("LeetCode_problem_number6",3) == answer_convert("LeetCode_problem_number6",3)))
|
"""
This is not my answer,
I tried, but I failed to pass this question.
I brought the best answer as future reference to learn.
The main explanation is provided as follow:
"""
"""
The main idea is to iterate every number in nums.
We use the number as a target to find two other numbers which make total zero.
For those two other numbers, we move pointers, l and r, to try them.
l start from left to right
r start from right to left
First, we sort the array, so we can easily move i around and know how to adjust l and r.
If the number is the same as the number before, we have used it as target already, continue. [1]
We always start the left pointer from i+1 because the combination of 0~i has already been tried. [2]
Now we calculate the total:
If the total is less than zero, we need it to be larger, so we move the left pointer. [3]
If the total is greater than zero, we need it to be smaller, so we move the right pointer. [4]
If the total is zero, bingo! [5]
We need to move the left and right pointers to the next different numbers, so we do not get repeating result. [6]
We do not need to consider i after nums[i]>0, since sum of 3 positive will be always greater than zero. [7]
We do not need to try the last two, since there are no rooms for l and r pointers.
You can think of it as The last two have been tried by all others. [8]
For time complexity
Sorting takes O(NlogN)
Now, we need to think as if the 'nums' is really really big
We iterate through the 'nums' once, and each time we iterate the whole array again by a while loop
So it is O(NlogN+N^2)~=O(N^2)
For space complexity
We didn't use extra space except the 'res'
Since we may store the whole 'nums' in it
So it is O(N)
N is the length of 'nums'
"""
def threeSum(nums):
res = []
nums.sort()
length = len(nums)
for i in range(length-2): #[8]
if nums[i]>0: break #[7]
if i>0 and nums[i]==nums[i-1]: continue #[1]
l, r = i+1, length-1 #[2]
while l<r:
total = nums[i]+nums[l]+nums[r]
if total<0: #[3]
l+=1
elif total>0: #[4]
r-=1
else: #[5]
res.append([nums[i], nums[l], nums[r]])
while l<r and nums[l]==nums[l+1]: #[6]
l+=1
while l<r and nums[r]==nums[r-1]: #[6]
r-=1
l+=1
r-=1
return res
print(threeSum([-1, 0, 1, 2, -1, -4]))
|
from FINAL.funciones_final import *
#main
print("\n ----------------------"
"\n -Welcome to the Game--"
"\n ----------------------")
#colocacion automatica de los barcos
user_tab.colocacion_automatica()
machine_tab.colocacion_automatica()
print("This is your board with your boats generated automatically"
"\nYou will see on it where the machine will hit your board"
"\nIt will show XX if it hits a boat, _ if it hits water"
"\nYou will see also your shoots with the same symbols on your Shoot Zone"
"\n")
user_tab.print_main()
print("\nReady ? Let's play!"
"\n-------------------"
"\nUser starts !!! ")
game("User",20,20)
#the game function starts once the player who starts is defined and the number of lives each player has
#Here we count 20 lives as per as the boats, but you can imagine having less lives for example.
|
import unittest
# f(0) = [0]
# f(1) = [0,1]
# f(n+1) = duplicate(f(n))
class Solution:
# @param A, a list of integer
# @return an integer
def hasCycle(self, head):
node = head
node2 = head
while node != None:
node = node.next
if node2 == None:
return False
else:
node2 = node2.next
if node2 == None:
return False
else:
node2 = node2.next
if node2 == node:
return True
return False
return head
class ListNode(object):
"""docstring for ListNode"""
def __init__(self, x):
super(ListNode, self).__init__()
self.val = x
self.next = None
def printVal(self):
print self.val
node = self.next
while node != None:
print node.val
node = node.next
class SList(object):
"""docstring for SList"""
def __init__(self):
super(SList, self).__init__()
self.head = None
def append(self, inode):
if self.head == None:
self.head = inode
prev = self.head
node = self.head.next
while node != None:
prev = node
node = node.next
prev.next = inode
# inode.next = None
def printVal(self):
node = self.head
while node != None:
print node.val
node = node.next
class SolutionUnitTest(unittest.TestCase):
"""docstring for SolutionUnitTest"""
def setup(self):
pass
def tearDown(self):
pass
def testsingleNumber(self):
# data = [0,1,3,2]
s = Solution()
head = SList()
head.append(ListNode(1))
head.append(ListNode(1))
head.append(ListNode(2))
n = ListNode(3)
n.next = head
head.append(n)
node = s.hasCycle(head.head)
print node
# print str(len(r_data))
# print r_data
# self.assertEqual(r_data ,data, "test failed")
if __name__ == '__main__':
unittest.main()
|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def sumNumbers(self, root):
self.sum = 0
if root == None:
return 0
if (root.left == None) and (root.right == None):
return root.val
if root.left != None:
self.visitLeaf(root.left, root.val)
if root.right != None:
self.visitLeaf(root.right, root.val)
return self.sum
def visitLeaf(self, root, fatherNum):
num = fatherNum * 10 + root.val
if (root.left==None) and (root.right==None):
self.sum += num
return
if root.left != None:
self.visitLeaf(root.left, num)
if root.right != None:
self.visitLeaf(root.right, num)
return
|
import unittest
class Solution:
# @param n, an integer
# @return an integer
def climbStairs(self, n):
first = 0
second = 1
for i in range(n):
first, second = second, second + first
return second
class SolutionTest(unittest.TestCase):
"""docstring for SolutionTest"""
def setup(self):
pass
def tearDown(self):
pass
def testCase1(self):
s = Solution()
self.assertEquals(s.climbStairs(1), 1)
self.assertEquals(s.climbStairs(2), 2)
self.assertEquals(s.climbStairs(3), 3)
print s.climbStairs(5)
print s.climbStairs(10)
if __name__ == '__main__':
unittest.main()
|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import unittest
class Solution:
# @param root, a tree node
# @return a list of integers
def levelOrder(self, root):
self.valMap ={}
if root == None:
return []
deep = self.treeDeepVisitor(root,0)
result = []
i = 0
while i <= deep:
# print "deep :" + str(deep)
values = self.valMap[i]
result.append(values)
i += 1
return result
def treeDeepVisitor(self, root, deepLevel):
if root == None:
return deepLevel-1
if self.valMap.has_key(deepLevel):
values = self.valMap[deepLevel]
values.append(root.val)
self.valMap[deepLevel] = values
else:
self.valMap[deepLevel] = [root.val]
deepLeft = self.treeDeepVisitor(root.left, deepLevel+1)
deepRight = self.treeDeepVisitor(root.right, deepLevel+1)
if deepLeft > deepRight:
return deepLeft
return deepRight
class TreeNode(object):
"""docstring for TreeNode"""
def __init__(self, arg):
super(TreeNode, self).__init__()
self.val = arg
self.left = None
self.right = None
class SolutionUnitTest(unittest.TestCase):
"""docstring for SolutionUnitTest"""
def setup(self):
pass
def tearDown(self):
pass
def testsingleNumber(self):
s = Solution()
print s.levelOrderBottom(None)
def testCase1(self):
s = Solution()
tree = TreeNode(1)
print s.levelOrderBottom(tree)
def testCase2(self):
s = Solution()
tree = TreeNode(1)
tree.left = TreeNode(2)
# tree.right = TreeNode(3)
print s.levelOrderBottom(tree)
if __name__ == '__main__':
unittest.main()
|
class Solution1(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
self.coins= sorted(coins, reverse=True)
maxCnt = amount/coins[-1] + 1
self.length = maxCnt
if amount == 0:
return 0
self.calcCoin(0, amount)
if self.length == maxCnt:
return -1
return self.length
def calcCoin(self,cnt, amount):
if amount < 0 :
return
cnt += 1
if cnt > self.length:
return
if amount in self.coins:
if cnt < self.length:
self.length = cnt
return
for coin in self.coins:
self.calcCoin(cnt, amount-coin)
class Solution2(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
maxNums = ((amount/coins[-1]) + 1) * (coins[-1] + 1)
amounts = [maxNums]*(amount+1)
amounts[0] = 0
for i in xrange(1, amount+1):
minNums = maxNums
for coin in coins:
if i- coin >= 0:
if minNums > amounts[i-coin] +1 :
minNums = amounts[i-coin] + 1
amounts[i]= minNums
if amounts[-1] == maxNums:
return -1
return amounts[-1]
|
#Line 18: RuntimeError: maximum recursion depth exceeded in cmp
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if nums == []:
return True
self.travel = ['u'] * len(nums)
self.nums = nums
self.length = len(nums)
return self.startTravel(0)
def startTravel(self, start):
flag = False
if start >= self.length-1:
return True
if self.travel[start] == 'u':
for x in xrange(self.nums[start]):
if self.startTravel(start+x+1) == True:
flag = True
self.travel[start] = flag
return self.travel[start]
#Time Limit Exceeded
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if nums == []:
return True
self.travel = [False] * len(nums)
self.travel[0] = True
length = len(nums)
for x in xrange(length):
if self.travel[x] == True:
for i in xrange(nums[x]):
if x+i+1 < length:
self.travel[x+i+1] = True
return self.travel[-1]
|
import random
def main():
dicerolls = int(input('How many dice would you like to roll? '))
dice_size = int(input('How many sides are the dice? '))
sum = 0
for i in range (0, dicerolls):
roll = random.randint(1, dice_size)
sum += roll
if roll == 1:
print(f'You rolled a {roll}! Critical Fail')
elif roll == dice_size:
print(f'You rolled a {roll}! Critical Success')
else:
print(f'You rolled a {roll}')
print(f'You have rolled a total of {sum}')
if __name__ == "__main__":
main()
|
person = {"name": "Eli", "email": "[email protected]", "number": 1234567}
all_contacts =[]
all_contacts.append(person)
print(all_contacts)
name = str(input("Enter name:"))
while len(str(name)) > 20 or len(str(name)) < 3 or len(str(name)) == 3:
name = str(input("Invalid name. Re-enter name(more than 2 letters): "))
email = input("Enter email:")
while "@" not in(email) and "." is not (email):
email = input("Enter valid email:")
number = int(input("Enter number:"))
while len(str(number)) > 10 or len(str(number)) < 10:
number = int(input("Invalid number. Re-enter phonenumber(10 digits):"))
new_person = {"name": name, "email": email, "number": number}
all_contacts.append(new_person)
print(all_contacts)
# for x in all_contacts:
# print(x)
# any(char.isdigit() for char in "tool1")
# x = "t56l1"
# for char in x:
# print(char.isdigit())
|
"""
Script to evaluate the predictions
(based on the code submission Text Mining Domains
Van der Ende, Buckens and Den Uijl 2020-2021 VU Amsterdam)
"""
import argparse
import sys
import os
import pandas as pd
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
def read_data(path):
"""
Function that reads in the data and returns a dataframe.
:param path: path to data file
:type path: string
:return: pandas dataframe
"""
with open(path, encoding = 'utf-8') as infile:
df = pd.read_csv(infile, delimiter=',')
predictions = df['prediction']
goldlabels = df['discrimination_label']
return predictions, goldlabels
def print_confusion_matrix(predictions, goldlabels):
'''
Function that prints out a confusion matrix
:param predictions: predicted labels
:param goldlabels: gold standard labels
:type predictions, goldlabels: list of strings
:returns: confusion matrix
'''
# based on example from https://datatofish.com/confusion-matrix-python/
data = {'Gold': goldlabels, 'Predicted': predictions}
df = pd.DataFrame(data, columns=['Gold', 'Predicted'])
confusion_matrix = pd.crosstab(df['Gold'], df['Predicted'], rownames=['Gold'], colnames=['Predicted'])
print('----> CONFUSION MATRIX <----')
print(confusion_matrix)
return confusion_matrix
def print_precision_recall_fscore(predictions, goldlabels):
'''
Function that prints out precision, recall and f-score in a complete report
:param predictions: predicted output by classifier
:param goldlabels: original gold labels
:type predictions: list
:type goldlabels: list
'''
report = classification_report(goldlabels,predictions,digits = 3)
print('----> CLASSIFICATION REPORT <----')
print(report)
def main():
predictions, goldlabels = read_data('data/predictions_baseline.csv')
print_confusion_matrix(predictions, goldlabels)
print_precision_recall_fscore(predictions, goldlabels)
if __name__ == '__main__':
main()
|
import random
#Selection sort is when you take the smallest element in an unsorted array and bring it over to the sorted side, then go back to the unsorted side and bring the next smallest element in the unsorted array and then keep repeating the process until the last index is reached in the unsorted array.
def selection_sort( arr ):
#1. In the initial unsorted array, iterate over it until the smallest element is reached
for i in range(0, len(arr) - 1):
#print(arr)
#2. Store smallest element in a sorted variable
cur_index = i
smallest_index = cur_index
#3. Loop over the rest of the unsorted array
for j in range(cur_index, len(arr)):
#4.if the any element is smaller than the current, smaller element, move to the sorted variable
if arr[j] < arr[smallest_index]:
smallest_index = j
arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index]
return arr
test_list = random.sample(range(0, 40), 10)
selection_sort(test_list)
# TO-DO: implement the Bubble Sort function below
#Bubble Sort
#Bubble sort works by comparing each element to it's neigbor
#If the second index is smaller than the first index, swap the two indices
#If you reach the end of the array, start again
def bubble_sort(arr):
#Loop through the initial unsorted array
for i in range(0, len(arr) - 1):
for j in range(0, len(arr) -1):
if arr[j] > arr[j+1]:
#If the second index is smaller than the first index, swap the two indices
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
bubble_sort(test_list)
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
|
def hhmmss2sec( hours, minutes, seconds ):
"""Given a hour value in th eformat hh:mm:ss convert it to the amount of seconds"""
if checkHourRange( hours ) == False:
return -1
elif checkMinutesSecondsRange( minutes ) == False:
return -1
elif checkMinutesSecondsRange( seconds ) == False:
return -1
else:
result = ( hours * 3600) + ( minutes * 60) + seconds
return result
def checkHourRange( hours ):
"""Check if hours value is between 00 and 23"""
if hours >= 0 and hours <=23:
return True
return False
def checkMinutesSecondsRange( value ):
"""Check if minutes/seconds value is between 00 and 59"""
if value >= 0 and value <=59:
return True
return False
|
"""Graphs in python."""
# Author: Daniel Dahlmeier <[email protected]>
from abc import ABCMeta, abstractmethod
import numpy as np
import random
from itertools import chain
from operator import itemgetter
import heapq
def unique(iter):
"""Helper class to return list of unique items in iter"""
return list(set(iter))
class Graph(object):
"""Abstract base class for graphs"""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_edge(self, frm, to):
pass
@abstractmethod
def adjacent(self, frm):
pass
@abstractmethod
def set_edge(self, frm, to):
pass
@abstractmethod
def nodes(self):
pass
class GraphMatrix(Graph):
""" Graph stored as a two dimensional adjacency matrix, nodes are
stored as integer ids"""
def __init__(self, n_nodes=10):
self.adjacency = np.inf * np.ones((n_nodes, n_nodes))
def get_edge(self, frm, to):
return self.adjacency[frm, to]
def adjacent(self, frm):
return [to for to in self.adjacency[frm] if to != np.inf]
def set_edge(self, frm, to, weight):
self.adjacency[frm, to] = weight
def nodes(self):
return range(self.adjacency.shape[0])
class GraphDict(Graph):
""" Graph stored as a adjacency list with dicts"""
def __init__(self):
self.adjacency = {}
def get_edge(self, frm, to):
g = self.adjacency.get(frm)
if g:
return g.get(to, np.inf)
else:
return np.inf
def adjacent(self, frm):
node = self.adjacency.get(frm, None)
return node.keys() if node else []
def set_edge(self, frm, to, weight):
if frm not in self.adjacency:
self.adjacency[frm] = {}
self.adjacency[frm][to] = weight
def nodes(self):
return unique(chain(self.adjacency.keys(),
*(d.keys() for d in self.adjacency.values())))
def depth_first_search(graph, start, end):
"""traverse graph in depth first search from start to end
return true if value is found otherwise false
"""
stack = [start]
visited = {n: False for n in graph.nodes()}
print "depth first search", start, "->", end
while stack:
node = stack.pop()
print "visit", node
visited[node] = True
if node is end:
return True
for to in (neighbour for neighbour in graph.adjacent(node)
if not visited[neighbour]):
stack.append(to)
return False
def breath_first_search(graph, start, end):
"""traverse graph in breath first search from start to end
return true if value is found otherwise false
"""
queue = [start]
visited = {n: False for n in graph.nodes()}
print "breath first search", start, "->", end
while queue:
node = queue.pop(0)
print "visit", node
visited[node] = True
if node is end:
return True
for to in (neighbour for neighbour in graph.adjacent(node)
if not visited[neighbour]):
queue.append(to)
return False
def trace_back(graph, backpointers, node):
""" return path from node through backpointers"""
path = []
while node:
path.append(node)
node = backpointers.get(node)
return list(reversed(path))
def dijkstra(graph, start, end):
"""Dijkstra shortest-path search"""
queue = [(0, start)] # priority queue for nodes
distance = {n: np.inf for n in graph.nodes()} # shortest distance to nodes
distance[start] = 0
visited = {n: False for n in graph.nodes()}
backpointers = {} # store back pointers for tracing back path
print "dijkstra search", start, "->", end
while queue:
dist, node = queue.pop(0)
# ignore visited nodes, can double visit due to queue duplicates
if visited[node]:
continue
print "visit", node, " with distance", dist
visited[node] = True
if node is end:
return (dist, trace_back(graph, backpointers, node))
for to in (neighbour for neighbour in graph.adjacent(node)
if not visited[neighbour]):
print "check", node, " ->", to
# update distance if we have found a new shortest path
if distance[node] + graph.get_edge(node, to) < distance[to]:
print "update shortest path"
distance[to] = distance[node] + graph.get_edge(node, to)
backpointers[to] = node
# add neighbour to queue
heapq.heappush(queue, (distance[to], to))
return (np.inf, [])
def random_graph(Graph, n_nodes, n_edges):
if Graph is GraphMatrix:
g = GraphMatrix(n_nodes)
elif Graph is GraphDict:
g = GraphDict()
else:
raise Exception("Unknown graph type %s" % Graph)
for _ in xrange(n_edges):
g.set_edge(random.randint(0, n_nodes-1), random.randint(0, n_nodes-1),
random.randint(1, 10))
return g
|
# split the string into two and count the total values. If they're equal return true else false
class Solution:
def halvesAreAlike(self, s: str) -> bool:
n = len(s)
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
l_count = 0
for i in range(0, int(n / 2)):
if s[i] in vowels:
l_count += 1
r_count = 0
for i in range(n // 2, n):
if s[i] in vowels:
r_count += 1
print(l_count)
print(r_count)
return l_count == r_count
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 13:20:25 2021
@author: eshasharma
"""#
# import csv and random libraries
import csv
import random
# for random example
from datetime import datetime
# Introductin to csv library and dict reader
with open('BanditsData.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
print(row['Sample A'])
with open('homes.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
# Introduction to random library and seed
from random import seed
from random import random
from random import sample
# seed random number generator - this will be used to generate the random
# numbers
seed(1)
# generate some random numbers
print(random(), random(), random())
# reset the seed
seed(2)
# generate some random numbers
print(random(), random(), random())
# generate some random numbers based on current date
seed(datetime.now())
# Generate 10 random numbers
print(random(), random(), random())
s = sample(range(1000), k=10)
print(s)
|
#https://www.codewars.com/kata/511f11d355fe575d2c000001/train/python
def two_oldest_ages(ages):
'''
oldest = []
oldest.append(max(ages))
ages.pop(ages.index(max(ages)))
if oldest[0] in ages:
oldest.append(max(ages))
else:
for a in ages:
if max(ages) not in oldest:
oldest.insert(0, max(ages))
return oldest
'''
return sorted(ages)[-2:]
print(two_oldest_ages([1, 5, 87, 45, 8, 8]))
print(two_oldest_ages([6, 5, 83, 5, 3, 18]))
print(two_oldest_ages([10, 1]))
|
import random
from .deck import Card
# Base Player
class Player:
# Who is sitting next to the player
left_player = None
right_player = None
# Card Chosen for the Round
card_chosen = None
# Is the player eliminated
eliminated = False
# Has the player won
is_winner = False
def __init__(self, win_threshold, player_num):
# Set Score to 0 and other player traits
self.score = 0
self.win_threshold = win_threshold
self.player_num = player_num
# Add to score, and check if player meets victory threshold
def tallyScore(self, value):
self.score = self.score + value
if self.score == self.win_threshold:
self.is_winner = True
elif self.score > self.win_threshold:
raise Exception("Unexpected Error, player score over win threshold")
# Basic Player Info
def __repr__(self):
return "Player " + str(self.player_num) + " Score: " + str(self.score)
# A player that always randomly selects a card
class AlwaysRandomPlayer(Player):
# Initialize Player and starting suspicion level
def __init__(self, win_threshold, player_num, base_suspicion_level):
self.base_suspicion_level = base_suspicion_level
self.suspicion_level = self.base_suspicion_level
super().__init__(win_threshold, player_num)
# Picks a random card from the deck by checking how many doubles left (note this is somewhat redundant if deck is shuffled)
def pickCard(self, deck):
if random.random() > deck.countOfTypeRemaining("double")/deck.cards_remaining:
self.card_chosen = deck.selectCardTypeIfPossible("single")
else:
self.card_chosen = deck.selectCardTypeIfPossible("double")
self.tallyScore(1)
self.card_chosen.is_chosen = True
if self.card_chosen == None:
raise Exception("Unexpected Error, player did not choose a card")
def suspicionUpdate(self):
pass
def __repr__(self):
return "AlwaysRandom" + str(super().__repr__())
class NeighborSuspicionAlwaysRandomPlayer(AlwaysRandomPlayer):
def __init__(self, win_threshold, player_num, suspicion_level, higher_rate, lower_rate):
self.higher_rate = higher_rate
self.lower_rate = lower_rate
super().__init__(win_threshold, player_num, suspicion_level)
def suspicionUpdate(self):
if self.score > max(self.right_player.score, self.left_player.score):
self.suspicion_level = self.base_suspicion_level*self.higher_rate
elif self.score < min(self.right_player.score, self.left_player.score):
self.suspicion_level = self.base_suspicion_level*self.lower_rate
else:
self.suspicion_level = self.base_suspicion_level
return self
def __repr__(self):
return "NeighborSuspicion" + str(super().__repr__())
# Update after each round
def playerUpdateRelations(players):
neighbor_players = create_neighbors_from_array_spot(players)
shifted_players = shift_right(neighbor_players)
suspicion_updated_players = updateSuspicions(shifted_players)
return suspicion_updated_players
# Adds left and right neighbors to each person
def create_neighbors_from_array_spot(players):
amount_players = len(players)
for x in range(amount_players):
players[x].right_player = players[(x+1)%amount_players]
players[x].left_player = players[(x+(amount_players-1))%amount_players]
return players
def updateSuspicions(players):
for player in players:
player.suspicionUpdate()
return players
# Changes who draws first (while keeping order)
def shift_right(lst):
return [lst[-1]] + lst[:-1]
def shift_left(lst):
return lst[1:] + [lst[0]]
|
N = int(input())
print('{:.3f}'.format(sum([i/(i*2-1) if i%2==1 else -i/(i*2-1) for i in range(1,N+1)])))
|
from random import randint
t = ["r","s","p"]
computer = t[randint(0,2)]
player = "y"
name = input("enter your name: ")
print("type reset if you want to reset the score: ")
you = 0
pc = 0
def win():
global you
you+=1
print(message)
print("computer:",pc,"\n",name,":",you)
def lose():
global pc
pc+=1
print(message)
print("computer",pc,"\n",name,":",you)
def tie():
print(message)
while player == "y" or player == "Y":
player = input("rock,paper or scissor?(r,p,s): ")
if player==computer:
print("tie")
elif player == "r":
if computer == "p":
message = "you lose!"
lose()
elif player == computer:
message= "tie"
tie()
else:
message = "you win"
win()
elif player == "s":
if computer == "r":
message="you lose!"
lose()
elif player == computer:
message= "tie"
tie()
else:
message ="you win"
win()
elif player == "p":
if computer == "s":
message = "you lose!"
lose()
elif player == computer:
message= "tie"
tie()
else:
message = "you win"
win()
elif player=="reset":
you = 0
pc = 0
print("score has been reset")
player = input("if you want to continue press y or Y: ")
computer = t[randint(0,2)]
|
import sqlite3
sqlite_file = 'sql_test.db'
table_name1 = 'my_table_1'
table_name2 = 'my_table_2'
new_field = 'my_first_column'
field_type = 'INTEGER'
conn = sqlite3.connect(sqlite_file)
c = conn.cursor()
c.execute('CREATE TABLE {tn} ({nf} {ft})'\
.format(tn=table_name1, nf=new_field, ft=field_type))
c.execute('CREATE TABLE {tn} ({nf} {ft} PRIMARY KEY)'\
.format(tn=table_name2, nf=new_field, ft=field_type))
conn.commit()
conn.close()
|
names = ['Demi', 'Victoria', 'Carmen', 'Myat', 'Nico']
boys = ['Shaun', 'Brian', 'Krishna', 'Patrick']
print(names+boys)
print(names.extend(boys)) #old list changes
print(names.append(boys))
def capitalize_all(t):
result = []
for word in t:
result.append(word.capitalize())
return result
names = ['nico', 'myat', 'carmen']
print(capitalize_all(names))
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res
animals = ['dog', 'cat', 'BIRDS', 'Sheep']
print(only_upper(animals))
print(names)
names.pop(2) #Delete carmen
def cumsum(t):
|
class Sweetgreens:
"""
represents a sweetgreens list
attributes: vegetable, grain, protein, standard topping, premium topping, bread
"""
def __init__(self, vegetable = [], grain='wild rice', protein='chicken', standard='tomatoes', premium='corn', dressing='vinegar', bread='wheat'):
self.vegetable = vegetable
self.grain = grain
self.protein = protein
self.standard = standard
self.premium = premium
self.dressing = dressing
self.bread = bread
def __str__(self):
"""
returns a salad order in human readable format
"""
return f"Your sweetgreen order is {' , '.join(self.vegetable)}, {self.grain}, {self.protein}, {self.standard}, {self.premium} with {self.dressing} dressing and a piece of {self.bread} bread."
def vegetables(self,number_of_vegetables):
"""
will add extra amount of payment
"""
price = 0.00
if number_of_vegetables==3:
price += 2.75
return f"You will need to pay an extra of {price} for an extra serving of vegetable"
if number_of_vegetables==4:
price += 5.50
return f"You will need to pay an extra of {price} for 2 extra serving of vegetables"
if number_of_vegetables>4:
return f"Please, only 4 vegetables in total. You are not a cow - moo moo. \U0001F923"
else:
return f"Please just pay $10"
def beverage(self, drink):
"""
add a drink onto your order
"""
return f"Your order has {drink} included"
def __contains__(self,parameter1):
"""
will return true if bread is part of order
will return false if bread is not part of order
"""
if parameter1 in self.bread:
return True
else:
return False
Myat_Order = Sweetgreens(['Kale','Arugula','Spinach','Romaine','Mesclun'],'Quinoa', 'Blackened Chicken Thighs', 'Corn', 'Avocado','Sesame Miso Ginger','White')
print(Myat_Order)
print(Myat_Order.vegetables(5))
print(Myat_Order.beverage('Tangerine Fresca'))
Vicky_Order2 = Sweetgreens('Kale', 'Qunoa', 'Steelhead','Corn','Avocado','Olive Oil')
print('White' in Vicky_Order2)
|
import turtle
import math
#SHAPE 1
shape1 = turtle.Turtle()
print (shape1)
def polygon(t, length, n):
for i in range(n):
t.fd(length)
t.lt(360/n)
def circle(t, r):
circumference = 2 * math.pi * r
n = 100
length = circumference / n
polygon(t,length, n)
circle (shape1, 100)
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = angle / n
for i in range(n):
t.fd(step_length)
t.lt(step_angle)
def move (t, x, y):
t.pu()
t.setpos(x,y)
t.pd()
shape1.left (60)
arc (shape1, 100, 120)
shape1.left (120)
arc (shape1, 100, 120)
shape1.left (120)
arc (shape1, 100, 120)
move (shape1,0,200)
shape1.right(60)
arc (shape1, 100, 120)
shape1.left (120)
arc (shape1, 100, 120)
shape1.left (120)
arc (shape1, 100, 120)
turtle.mainloop()
|
# list of DNA combinaisons.
def mkstr(prefix):
if len(prefix) == 4:
return [prefix]
combs = []
combs.extend(mkstr(prefix + "A"))
combs.extend(mkstr(prefix + "T"))
combs.extend(mkstr(prefix + "G"))
combs.extend(mkstr(prefix + "C"))
return combs
letters = ""
ATGC_comb = mkstr(letters)
# DJINA's function, used to find some specfics sequences into the genome where we incorporated
# the message.
def find_all(msg, site):
start = 0
while site in msg:
start = msg.find(site, start)
if start == -1: return
yield start
start += len(site)
# decryption function. It call other functions in order to decrypt the differents types of encryption.
def decrypt(key, genome_encrypted):
# first we have a genome and we need to find where is our message.
# At the end of the message we can find the restriction site that we will search to know where start and finish
# our message.
list_genome_encrypted = list(genome_encrypted)
list_genome_encrypted2 = []
message_encrypted = []
restrict_site = []
for i in range(8):
a = -(i+1)
restrict_site.append(a)
if restrict_site != 'AAAAAAAA':
position = find_all(restrict_site, genome_encrypted)
position = list(position)
if position != []:
first_site = position[0]
second_site = position[1]
# We found the two sites around our sequence, so we will keep the sequence between.
for i in range(second_site):
list_genome_encrypted2.append(i)
for i in range(first_site):
list_genome_encrypted2.pop(i)
message_encrypted = list_genome_encrypted2
# if it is a sequence encrypted without genome:
else:
for i in range(8):
message_encrypted = list_genome_encrypted.pop(-1)
encrypt_seq = []
DNA_letters = []
for chrct in message_encrypted:
DNA_letters.append(chrct)
if len(DNA_letters) ==4:
DNA_letters = "".join(DNA_letters)
encrypt_seq.append(DNA_letters)
DNA_letters = []
if DNA_letters == ATGC_comb[ord('1')]:
import caesar_decrypt as cd
return cd.caesar_decrypt(key, encrypted_seq)
elif encrypt_seq[-1] == ATGC_comb[ord('2')]:
import vigenere_decrypt as vd
return vd.vigenere_decrypt(key, encrypted_seq)
elif encrypt_seq[-1] == ATGC_comb[ord('3')]:
import hill_decrypt as hd
return hd.hill_decrypt(key, encrypted_seq)
elif encrypt_seq[-1] == ATGC_comb[ord('4')]:
import AES_decrypt as ad
return ad.AES_decrypt(key, encrypted_seq)
|
my_name = 'Joe Shuttlewood'
my_age = 26
my_height = 6*12+2 #Hopefully this will put my height in to inches for me. Yep, it works!
my_weight = 200
my_eyes = 'blue'
my_hair = 'blonde'
is_heavy = my_weight > 3000 #when I use this variable further on this will return 'False'. Flattering.
my_height_in_cm = my_height * 2.5
my_weight_in_kg = my_weight // 2.2 #I had 'my_height / 2.2' here originally but it returned a float with 13 decimal places, looking at the documentation you can do 'integer division' with '//' which will always round down.
test_weight_in_kg = my_weight / 2.2 #I am going to try calling the result of this function as an integer, which hopefully will return 90 or 91. A second method of the above.
print(f"Let's talk about {my_name}.")
print(f"He is {my_height} inches tall, which is {my_height_in_cm} centimeters.") #this works correctly as above.
print(f"He's {my_weight} pounds heavy, which is {my_weight_in_kg} kilograms.")
print(f"It is {is_heavy} that he is overweight.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
print (int(test_weight_in_kg)) #this should hopefully return 90.
|
annual_salary = float(input("Enter your annual salary: "))
monthly_salary = annual_salary / 12
total_cost = 1000000
portion_deposit = total_cost * 0.25
current_savings = 0
semi_annual_raise = 0.07
r = 0.04
epsilon = 100
months = 0
low = 0
high = 10000
limit = 36
savings_percent = (low + high) / 2.0
iterations = 0
for months in range(0,35):
while current_savings <= portion_deposit:
months += 1
current_savings += monthly_salary * (savings_percent / 10000)
current_savings += current_savings * r / 12
if months % 6 == 0:
monthly_salary += monthly_salary * semi_annual_raise
print(months, current_savings, monthly_salary)
if current_savings - portion_deposit >= epsilon:
low = savings_percent
else:
high = savings_percent
print(f"Best savings rate: {savings_percent}")
print(f"Steps in bisection search: {iterations}")
break
if months > 35:
print("It is not possible to pay the down payment in three years")
break
|
# Similar code for logistic regression
import torch
import torch.nn.functional as F
x_data = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
y_data = torch.tensor([[0.0], [0.0], [1.0], [1.0]])
# Step 1. define network parameters and forward, it's still linear layer, but for regular NN logistic reguression, there is activation function,
# can be sigmoid, Relu, tanh..., they are just the function in forward, rather the layer structure. Previous linear regression, there is no
# activation, only direct calculation.
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(1,1)
def forward(self, x):
y_pred = F.sigmoid(self.linear(x))
return y_pred
model = Model()
# Step 2. define loss and optimizer.
criterion = torch.nn.BCELoss(size_average = True) # sigmoid activation is usually combined with Entropy loss
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
# Step 3. Training
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.data[0])
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Test
t = torch.tensor([[1.0]])
print("predic 1", 1.0, model(t).data[0][0].item()>0.5)
t = torch.tensor([[7.0]])
print("predic 7", 7.0, model(t).data[0][0].item()>0.5)
|
dic = {'b':3, 'a':1, 'c':2}
sorted(dic.items())
# [('a', 1), ('b', 3), ('c', 2)]
sorted(dic.items(), key=lambda x:x[1])
# [('a', 1), ('c', 2), ('b', 3)]
sorted(dic.items(), reverse=True)
# [('c', 2), ('b', 3), ('a', 1)]
sorted(dic.items(), key=lambda x:x[1], reverse=True)
# [('b', 3), ('c', 2), ('a', 1)]
|
x = int(input("Enter an Integer: "))
if (x%2) != 0:
print ("Odd")
elif (x%2) == 0:
print("Even")
|
import math
h = float(input("Enter in Height(cm)"))
M = float(input("Enter in Mass(kg)"))
m = M
h = h / 100.0
V = M / 1000
r = math.sqrt(float(V/(h*math.pi)))
waist_line = 2*math.pi*r
waist_line_inch = 100 * waist_line * 0.39
print (waist_line_inch)
|
"""
Program: investmentGUI.py
Alexa Caridi 4/28/2020
GUI-based investment program
1.Inputs:
starting investment amount
number of years
interest rate (an integer %)
2.The report is displayed in tabular format
3.Compute interst for each year and add it to the investment
4.Display the ending investment and interest earned as final output
"""
from breezypythongui import EasyFrame
class InvestmentGUI(EasyFrame):
#an investment calculator that demonstrates the use of multi-line text area
def __init__(self):
EasyFrame.__init__(self, title="Investment Calculator")
#labels for the window
self.addLabel(text="Initial amount", row=0, column=0)
self.addLabel(text="Number of years", row=1, column=0)
self.addLabel(text="Interest rate in %", row=2, column=0)
#entry fields for inputs
self.amount = self.addFloatField(value=0.0, row=0, column=1)
self.period = self.addIntegerField(value=0, row=1, column=1)
self.rate = self.addIntegerField(value=0, row=2, column=1)
#button widget
self.compute = self.addButton(text="Compute", row=3, column=0, columnspan=2, command=self.compute)
#text-area widget
self.outputArea = self.addTextArea("", row=4, column=0, columnspan=2, width=50, height=15)
#event handling method- trigger for button being clicked on
def compute(self):
#computes the investment schedule based on the inputs & outputs the schedule
#obtain and validate the inputs
startBalance = self.amount.getNumber()
rate = self.rate.getNumber() / 100
years = self.period.getNumber()
if startBalance == 0 or rate == 0 or years == 0:
return
#set the header for the table
result = "%4s%18s%10s%16s\n" % ("Year", "Starting blance", "Interest", "Ending balnce")
#compute and append the results for each year
totalInterest = 0.0
for year in range(1, years+1):
interest = startBalance * rate
endBalance = startBalance + interest
result += "%4d%18.2f%10.2f%16.2f\n" % (year, startBalance, interest, endBalance)
startBalance = endBalance
totalInterest += interest
#append the totals for the period
result += "Ending balance: $%0.2f\n" % endBalance
result += "Total interest earned: $%0.2f\n" % totalInterest
#output the result while preserving read-only status
self.outputArea["state"] = "normal"
self.outputArea.setText(result)
self.outputArea["state"] = "disabled"
def main():
InvestmentGUI().mainloop()
main()
|
#!/usr/bin/python
numbers=range(1,101)
def factorial (n):
fact = 1;
numbers = range(1,n+1)
for i in numbers:
fact = fact * i
if n == 1:
return 1
else:
return fact
N=factorial(100)
sum=0
while N>1:
dig=N % 10
sum = sum + dig
N = (N-dig)/10
print "ANSWER=",sum
|
human = 'choyeaeun'
age = 24
print('hello world', 'my name is', human, 'my age is', age)
human = 'ohhyunji'
age = 25
print('hello world', 'my age is', age, 'my name is', human)
#주석 처리는 이렇게
"""
긴 주석은 이렇게 처리
"""
|
# 튜플은 소괄호로 선언하며, 값의 변경과 삭제가 불가능
# 튜플 선언
tuple1 = (1, 2, 3)
tuple2 = 1, 2, 3, 4
print(tuple1)
print(tuple2)
# 리스트를 튜플에 넣을 수도 있음
list1 = [4, 5, 6, 7]
tuple3 = tuple(list1)
print(tuple3)
# packing, unpacking : 여러 개의 값을 한 번에 변수에 넣을 수 있다
c = (3, 4)
a, b = c
print(a) # 3
print(b) # 4
# temp없이 바로 두 개의 값 바꾸기 가능
amy = 10
bella = 13
amy, bella = bella, amy
print(amy) # 13
print(bella) # 10
|
#function to left rotate array of size s by n
def rotateArray(array, s, n):
for i in range(s):
rotateByOne(array, n)
#function to left rotate array of size s by 1
def rotateByOne(array, n):
tempArray = array[0]
for i in range(n - 1):
array[i] = array[i + 1]
array[n - 1] = tempArray
array = [1, 2, 3, 4, 5]
rotateArray(array, 5, 3)
print(*array)
|
#python math
# arithmetic operators
# + plus addition
# - minus subtraction
# * times multiplication
# / divided by division
# ** power exponentiation
print 12, -3, 3.14159, -1.8 #prints 12 -3 3.14159 -1.8
print type(1), type(3.14159), type(2.0) # prints <type 'int'> <type 'float'> <type 'float'>
print int(3.14159), int(-5.5) # prints 3 -5
print float(7), float(-5) # prints 7.0 -5.0
print 3.1415926535897932384626433832795028841971 #python prints out 12 characters
print 1.0 / 3, 7.0 / 2.0, -8 / 3.0 # prints 0.3333333333 3.5 -2.333333333333
print 1 + 2, 3 - 4, 5 * 6, 7 ** 8 ## prints 3 -1 30 5764801
print 1 * 2 + 3 * 4 #prints 14
print 1 * (2 + 3) * 4 # prints 20
|
users = {
"omer": {
"level": 7
},
"yusuf": {
"level": 4
},
"esra": {
"level": 1
}
}
name = "omer"
for i, j in users.items():
if i == name:
print(j["level"])
|
from .. import util
class Point:
def __init__(self, x, y, dx, dy):
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def step(self):
self.x += self.dx
self.y += self.dy
def step_backwards(self):
self.x -= self.dx
self.y -= self.dy
def __repr__(self):
return 'Point(%s, %s, %s, %s)' % (self.x, self.y, self.dx, self.dy)
def width_and_height(points):
xs = [point.x for point in points]
ys = [point.y for point in points]
width = max(xs) - min(xs) + 1
height = max(ys) - min(ys) + 1
return width, height
def translate_to_0(points):
xs = [point.x for point in points]
ys = [point.y for point in points]
min_x = min(xs)
min_y = min(ys)
for point in points:
point.x -= min_x
point.y -= min_y
def print_array(points):
array = []
width, height = width_and_height(points)
for y in range(height):
array.append(['.'] * width)
for point in points:
array[point.y][point.x] = 'X'
for line in array:
for char in line:
print(char, end='')
print()
def print_at_smallest_height_and_width(points):
width_plus_height = 100000000000
time = 0
while True:
time += 1
for point in points:
point.step()
new_width_plus_height = sum(width_and_height(points))
if new_width_plus_height > width_plus_height:
for point in points:
point.step_backwards()
translate_to_0(points)
print_array(points)
print(time - 1)
break
width_plus_height = new_width_plus_height
# load points from list
# points = [Point(2, 0, -1, 0), Point(-3, 1, 1, 0)]
points = []
for line in util.input_lines(10):
x = int(line.split('<')[1].split(',')[0])
y = int(line.split(',')[1].split('>')[0])
dx = int(line.split('<')[2].split(',')[0])
dy = int(line.split(',')[2].split('>')[0])
points.append(Point(x, y, dx, dy))
print_at_smallest_height_and_width(points)
|
from tree import TreeNode
def search_name(root_node, goal_value, path=()):
path = path + (root_node,)
if root_node.value == goal_value:
return path
for child in root_node.children:
path_found = search_name(child, goal_value, path)
if not path_found == None:
return path_found
return None
|
class Node(object):
def __init__(self,value = None):
self.value = value
self.left = None
self.right = None
def set_value(self,value):
self.value = value
def get_value(self):
return self.value
def set_left_child(self,left):
self.left = left
def set_right_child(self, right):
self.right = right
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left != None
def has_right_child(self):
return self.right != None
# define __repr_ to decide what a print statement displays for a Node object
def __repr__(self):
return f"Node({self.get_value()})"
def __str__(self):
return f"Node({self.get_value()})"
class Tree():
def __init__(self, value=None):
self.root = Node(value)
def get_root(self):
return self.root
# Use recursion and perform pre-order traversal
# def pre_order(tree):
# cur_node = tree.get_root()
# visit_order = []
# visit_order.append(cur_node.value)
# def traverse(node):
# if node is None:
# return
# if node.has_left_child():
# cur = node.get_left_child()
# visit_order.append(cur.value)
# traverse(cur)
# if node.has_right_child():
# cur = node.get_right_child()
# visit_order.append(cur.value)
# traverse(cur)
# traverse(cur_node)
# return visit_order
def pre_order(tree):
root = tree.get_root()
visit_order = []
def traverse(node):
if node:
# visit node
visit_order.append(node.value)
# traverse left
traverse(node.get_left_child())
# traverse right
traverse(node.get_right_child())
traverse(root)
return visit_order
# define in-order traversal
def in_order(tree):
visit_order = []
root = tree.get_root()
def traverse(node):
if node:
# visit left node
traverse(node.get_left_child())
# visit node
visit_order.append(node.value)
# visit right node
traverse(node.get_right_child())
traverse(root)
return visit_order
# define post_order traversal
def post_order(tree):
visit_order = []
root = tree.get_root()
def traverse(node):
if node:
traverse(node.get_left_child())
traverse(node.get_right_child())
visit_order.append(node.value)
traverse(root)
return visit_order
tree = Tree("apple")
tree.get_root().set_left_child(Node("banana"))
tree.get_root().set_right_child(Node("cherry"))
tree.get_root().get_left_child().set_left_child(Node("dates"))
pre_order(tree)
in_order(tree)
post_order(tree)
|
"""
The flag of the Netherlands consists of three colors: red, white and blue.
Given balls of these three colors arranged randomly in a line (the actual number of balls does not matter),
the task is to arrange them such that all balls of the same color are together
and their collective color groups are in the correct order
"""
def arrange(lst):
"""Sort an array of 0, 1 and 2's but you must do this in place, in linear time and without any extra space.
For example:
>>> arrange([2,0,0,1,2,1])
[0, 0, 1, 1, 2, 2]
>>> arrange([0,1,0,2,0,1,2])
[0, 0, 0, 1, 1, 2, 2]
"""
lo = 0
mid = 0
hi = len(lst) - 1
while mid <= hi:
if lst[mid] == 0:
lst[lo], lst[mid] = lst[mid], lst[lo]
mid += 1
lo += 1
elif lst[mid] == 2:
lst[hi], lst[mid] = lst[mid], lst[hi]
hi -= 1
# mid += 1
else:
mid += 1
return lst
############################################################################
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YOU DID AN EXCELLENT JOB!\n")
|
def arraysIntersection(arr1, arr2, arr3):
"""Given three sorted arrays strictly increasing order, return a sorted array of only the integers
that appeared in all three arrays.
For example:
>>> arraysIntersection([1,2,3,4,5], [1,2,5,7,9], [1,3,4,5,8])
[1, 5]
"""
# i = 0
# j = 0
# k = 0
# intersection = []
# while i < len(arr1) and j < len(arr2) and k < len(arr3):
# if arr1[i] == arr2[j] and arr1[i] == arr3[k]:
# intersection.append(arr1[i])
# i += 1
# j += 1
# k += 1
# continue
# if arr1[i] < arr2[j] or arr1[i] < arr3[k]:
# i += 1
# if arr1[i] > arr2[j] or arr3[k] > arr2[j]:
# j += 1
# if arr1[i] > arr3[k] or arr2[j] > arr3[k]:
# k += 1
# return intersection
# Solution: Get the intersection of first two arrays and then use the result to get the intersection with the third array.
def get_common(a1, a2):
i = j = 0
intersection = []
while i < len(a1) and j < len(a2):
if a1[i] == a2[j]:
intersection.append(a1[i])
i += 1
j += 1
elif a1[i] < a2[j]:
i += 1
else:
j += 1
return intersection
common_a1_a2 = get_common(arr1, arr2)
return get_common(common_a1_a2, arr3)
############################################################################
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YOU DID AN EXCELLENT JOB!\n")
|
"""
Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like
(i.e., buy one and sell one share of the stock multiple times).
"""
def maxProfit(prices):
"""Input an array prices and find the max profit.
For example:
>>> maxProfit([7,1,5,3,6,4])
7
>>> maxProfit([1,2,3,4,5])
4
>>> maxProfit([2,1,4,5,2,9,7])
11
"""
# max profit = the sum of a pair of numbers' difference
# the 1st num should be greater than the 2nd num
# Use linked list
# if next num is greater than current num,
# current_difference = next_num - current_num
# keep checking the rest of the numbers when next number is increasing
# if next_difference is greater than current_difference
# replace current_diff
# stop checking when next number decreases
# add current_diff (which is max so far) to profit
# move to next num and restart the process
# to add more profit until the array ends
profit = 0
total_profit = 0
if len(prices) < 2:
raise ValueError('To have transactions, you need at least to have two prices.')
for i in range(len(prices)-1):
# print(i)
if prices[i+1] >= prices[i]:
current_diff = prices[i+1] - prices[i]
# print(current_diff)
if current_diff > 0:
profit = current_diff
total_profit += profit
# print(total_profit)
else:
profit = 0
return total_profit
#######################################################
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print("\n*** ALL TESTS PASSED. YOU CAUGHT ALL THE STRAY PARENS!\n")
|
import random
lista = ['piosenka1', 'piosenka2', 'piosenka3']
losowy_element = random.choice(lista)
print(losowy_element)
for i in range(2):
losowy_element = random.choice(lista)
print(losowy_element)
losowa_lista = random.sample(lista, 2)
print(losowa_lista)
|
def main():
from sys import stdin, stdout
t = int(input())
for i in range(0, t):
s = input()
mid = (len(s) + 1) // 2
first = ''.join(sorted(s[:mid - (len(s)%2)]))
second = ''.join(sorted(s[mid:]))
if first == second:
print('YES')
else:
print('NO')
if __name__ == "__main__":
main()
|
# 比较不同类别精灵属性值分布 查看双变量数据分布 查看变量间的关系
# seaborn 盒形图 双变量图 相关系数
# 如果有多个画图 运行程序时 每个图的show()不能少 不然容易最后都画到一张图上面
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data_path = 'C:\\Users\\shine小小昱\\Desktop\\data_pd\\pokemon.csv'
save_path = 'C:\\Users\\shine小小昱\\Desktop\\'
def collect_data():
"""
载入csv数据至pandas
:return: 所有数据df
"""
f = open(data_path, encoding='utf-8') # 中文文件名或中文路径必须这么打开
cols = ['Name', 'Type_1', 'Total', 'HP', 'Attack', 'Defense', 'Speed', 'Height_m', 'Weight_kg', 'Catch_Rate']
data_df = pd.read_csv(f, usecols=cols, header=0) # 可只读取需要的列
return data_df
def inspect_data(data_df):
"""
审查数据
:param data_df: 所有数据df
:return:
"""
print('数据预览:')
print(data_df.head(10))
print('数据基本信息:')
print(data_df.info())
print('数据内容统计:')
print(data_df.describe())
def process_data(data_df):
"""
处理数据,去除空值
:param data_df: 所有数据df
:return: 去除空值后的数据
"""
cln_data_df = data_df.dropna()
print('原始数据有{}行记录,处理后的数据有{}行记录'.format(data_df.shape[0], cln_data_df.shape[0]))
return cln_data_df
def analyze_by_box(df, attr):
"""
绘制盒型图,比较不同类别精灵属性值分布
:param df: 数据
:param attr: 需分析的属性
:return:
"""
# 自动按x分组后进行数据统计
sns.boxplot(data=df, x='Type_1', y=attr)
plt.title('Attribution Analysis')
plt.xticks(rotation=90)
plt.savefig(save_path + '精灵属性盒型图.png')
plt.show()
def analyze_dual_variables(df, var1, var2):
"""
双变量数据分布查看
:param df: 数据
:param var1: 作为变量的属性1
:param var2: 作为变量的属性2
:return:
"""
# 这种画图不能加标题 不然会混乱乱
sns.jointplot(data=df, x=var1, y=var2)
plt.savefig(save_path + '精灵双变量属性分析.png')
plt.show()
def analyze_variables_relationships(df):
"""
可视化变量间相关关系(基于皮尔逊相关系数:-1 到 0 到 1 ,体现正负相关强度)
:param df: 数据
:return:
"""
# 直接生成两两变量直接的相关关系形成二维数组
corr_df = df.corr()
# 调用注释 方格内显示数据
sns.heatmap(corr_df, annot=True) # 利用seaborn生成相关关系热图
plt.title('Attribution Relationships')
plt.savefig(save_path + '精灵属性相关关系图.png')
plt.show()
if __name__ == '__main__':
all_data_df = collect_data()
inspect_data(all_data_df)
proc_data_df = process_data(all_data_df)
analyze_by_box(proc_data_df, 'Attack')
analyze_dual_variables(proc_data_df, 'Attack', 'Defense')
analyze_variables_relationships(proc_data_df)
|
# 进程由进程创建 被创建的进程是子进程 每个进程执行自己的任务 互不干扰 进程有属于自己的进程编号 标示着从属关系
# 进程间的内存空间各自独立 比较稳定 消耗内存
from multiprocessing import Process, cpu_count, Queue
import os
import time
# 死循环任务1
def print_A(word, que):
i = 1
while True:
time.sleep(4)
print(word)
print(f'正在执行的子进程号:{os.getpid()}')
print(f'此进程放入Queue一个:{i}')
que.put(i)
i += 1
print(f'此进程放入Queue一个:{i}')
que.put(i)
i += 1
print('---------------------')
# 死循环任务2
def print_B(word, que):
while True:
time.sleep(4)
print(word)
print(f'正在执行的子进程号:{os.getpid()}')
print('q队列的size:')
print(que.qsize())
i1 = que.get()
i2 = que.get()
print(f'此进程取出一个:{i1}')
print(f'此进程取出一个:{i2}')
print('---------------------')
# 必须要在声明主函数当中启动进程
if __name__ == '__main__':
# 父进程创建各进程公用的队列存储对象 并作为参数传入
q = Queue()
# 获取cpu内核数目 启动cpu内核数目相等的进程 充分利用计算机资源
count = cpu_count()
print(f'当前计算机cpu内核数量为:{count}')
print(f'主函数进程号:{os.getpid()}')
print('------------------------------------------------------')
# 开启两个进程 进程执行的函数 传入参数
A = Process(target=print_A, args=('A', q))
B = Process(target=print_B, args=('B', q))
# 分别启动进程
# 用A.terminate()结束进程
A.start()
# 代表当A进程执行完毕后再继续 timeout参数代表A执行在几秒后还未完成的话 代码继续往下走
A.join(timeout=2)
B.start()
|
# 统计不同专业背景的员工的平均薪资,并用柱状图显示结果
import pandas as pd
import matplotlib.pyplot as plt
data_info_path = 'C:\\Users\\shine小小昱\\Desktop\\data_employee\\employee_info.csv'
data_edu_path = 'C:\\Users\\shine小小昱\\Desktop\\data_employee\\employee_edu.csv'
save_path = 'C:\\Users\\shine小小昱\\Desktop\\'
def collect_data():
"""
载入csv数据至pandas
:return: 设备数据df, 使用数据df
"""
f1 = open(data_info_path, encoding='utf-8') # 中文文件名或中文路径必须这么打开
cols = ['EmployeeNumber', 'MonthlyIncome']
info_df = pd.read_csv(f1, header=0, usecols=cols) # 可只读取需要的列
f2 = open(data_edu_path, encoding='utf-8') # 中文文件名或中文路径必须这么打开
edu_df = pd.read_csv(f2, header=0) # 可只读取需要的列
return info_df, edu_df
def inspect_data(info_df, edu_df):
"""
审查数据
:param info_df: 员工信息df
:param edu_df: 员工专业df
:return:
"""
print('数据预览:')
print(info_df.head(10))
print(edu_df.head(10))
print('数据基本信息:')
print(info_df.info())
print(edu_df.info())
print('数据内容统计:')
print(info_df.describe())
print(edu_df.describe())
def process_data(info_df, edu_df):
"""
数据处理
:param info_df: 员工信息df
:param edu_df: 员工专业df
:return: 处理后的数据
"""
# 预防处理空值
info_df.dropna(inplace=True)
edu_df.dropna(inplace=True)
# 联合数据
merged_df = pd.merge(info_df, edu_df, on='EmployeeNumber', how='inner')
return merged_df
def analyze_data(proc_df):
"""
分析数据
:param proc_df: 处理后的数据
:return: 已分组求月薪均值后排序的df
"""
# 分组 求月薪均值 排序
edu_ic_df = proc_df.groupby('EducationField')['MonthlyIncome'].mean().sort_values(ascending=False)
return edu_ic_df
def save_and_show(edu_ic_df):
"""
保存csv,绘制保存图像
:param edu_ic_df: 已分组求月薪均值后排序的df
:return:
"""
# edu_ic_df.to_csv(save_path + '专业与收入对比.csv', header=['mean_income'])
edu_ic_df.plot(kind='bar', rot=0) # 设置为零激活横排
plt.title('Education & Income')
plt.ylabel('mean income')
plt.tight_layout()
plt.savefig(save_path + '专业与收入对比.png')
plt.show()
if __name__ == '__main__':
data_info_df, data_edu_df = collect_data()
inspect_data(data_info_df, data_edu_df)
proc_data_df = process_data(data_info_df, data_edu_df)
edu_income_df = analyze_data(proc_data_df)
save_and_show(edu_income_df)
|
# Problem 21
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
# If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called
# amicable numbers.
# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore
# d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
# Evaluate the sum of all the amicable numbers under 10000.
import helpers
amicable = []
cache = {}
def d(n):
if n not in cache:
cache[n] = sum(helpers.ProperDivisors(n))
return cache[n]
for p in range(1, 10001):
if p in amicable:
break
a1 = d(p)
a2 = d(a1)
print p, a1, a2
if a2 == p:
amicable.append(p)
amicable.append(a1)
print sum(amicable)
|
def showOdds(last):
n = int(last) + 1
print("All odd numbers are given below:")
sumOfOdds = 0
for i in range(1, n, 2):
print(i, end = " ")
sumOfOdds += i
print()
return sumOfOdds
value = input("Enter a number: ")
result = showOdds(value)
print("Sum of the following numbers: " + str(result))
|
import random
def burbuja(A):
n = len(A)
for i in range(1, n):
for j in range(0, n - i):
if A[j] > A[j + 1]:
swap(A, j, j + 1)
def swap(A, i, j):
tmp = A[i]
A[i] = A[j]
A[j] = tmp
'''
def burbuja_optimizado2(A):#La optimizacion del algoritmo burbuja es que simplemente se le anade un contador "c" el cual se suma si ya esta ordenado y se resta si no esta ordenado
n = len(A) #Cada vez que este ordenado se verifica si "c" no es mayor a "n/2", si es asi, el programa considera ordenada la lista y hace break
c = 0
for i in range(n - 1):
for j in range(0, n - i - 1):
if A[j] > A[j + 1]:
swap(A, j, j + 1)
c-=1
else:
if c >= n/2:
break
else:
c+=1
'''
def burbuja_optimizado(A): #El anterior algoritmo se sometio a una lista la cual no mostro un resultado acertado, la lista en cuestion fue: A=[21,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,22,23,24,25,26,27,28,29,30,1,0]
M = True #Por lo tanto se ideo un algoritmo de banderas, en este caso "M" el cual significa movimiento, e indica si se hizo un swap o no y abarca toda la lista
n = len(A)
for i in range(1, n):
if M == True:
M = False
for j in range(0, n - i):
if A[j] > A[j + 1]:
swap(A, j, j + 1)
M = True
else:
break
##raise NotImplementedError()
|
"""
후위표기볍 연산하는 알고리즘 미리 생각해보기
인자 = '3+4*2-4/2'를 str으로 넣고 for문 돌려서 i가 연산자, 괄호가 아니면 int로 casting해서 answer.append(i)하기.
연산자 만났는데, 우선순위 비교하고 opStack.pop() 하는 곳에
if oper == '*':
K = answer.pop(-2) * answer.pop(-1)
answer.append(K)
elif oper == '/':
K = answer.pop(-2) / answer.pop(-1)
answer.append(K)
elif oper == '+':
K = answer.pop(-2) + answer.pop(-1)
answer.append(K)
else:
K = answer.pop(-2) - answer.pop(-1)
answer.append(K)
위 연산자 부르는 코드를 삽입한다.
"""
class ArrayStack:
def __init__(self):
self.data = []
def size(self):
return len(self.data)
def isEmpty(self):
return self.size() == 0
def push(self, item):
self.data.append(item)
def pop(self):
return self.data.pop()
def peek(self):
return self.data[-1]
prec = {
'*': 3, '/': 3,
'+': 2, '-': 2,
'(': 1
}
#S = '3+4*2-4/2'
#S2 = '(3+(4-2))*2'
def solution(S):
opStack = ArrayStack()
answer = []
for i in S:
if i not in '+-*/':
if i not in '()':
answer.append(int(i))
elif i == '(':
opStack.push(i)
else:
while opStack.peek() !='(':
oper = opStack.pop()
if oper == '*':
K = answer.pop(-2) * answer.pop(-1)
answer.append(K)
elif oper == '/':
K = answer.pop(-2) / answer.pop(-1)
answer.append(K)
elif oper == '+':
K = answer.pop(-2) + answer.pop(-1)
answer.append(K)
else:
K = answer.pop(-2) - answer.pop(-1)
answer.append(K)
continue
opStack.pop()
continue
else:
if not opStack.isEmpty():
while prec[opStack.peek()] >= prec[i]:
oper = opStack.pop()
if oper == '*':
K = answer.pop(-2) * answer.pop(-1)
answer.append(K)
elif oper == '/':
K = answer.pop(-2) / answer.pop(-1)
answer.append(K)
elif oper == '+':
K = answer.pop(-2) + answer.pop(-1)
answer.append(K)
else:
K = answer.pop(-2) - answer.pop(-1)
answer.append(K)
if opStack.isEmpty():
#opStack.push(i) 여기서 break하면 while를 나가서 opStack.push(i) 코드가 작동한다.
break
else:
continue
opStack.push(i)
continue
else:
opStack.push(i)
continue
while not opStack.isEmpty():
oper = opStack.pop()
if oper == '*':
K = answer.pop(-2) * answer.pop(-1)
answer.append(K)
elif oper == '/':
K = answer.pop(-2) / answer.pop(-1)
answer.append(K)
elif oper == '+':
K = answer.pop(-2) + answer.pop(-1)
answer.append(K)
else:
K = answer.pop(-2) - answer.pop(-1)
answer.append(K)
return answer[0]
S ='(3+(4-2))*2'
# answer = 10.0
print(solution(S))
|
import time
def rec(n):
if n <=1:
return n
else:
return rec(n-1) + rec(n-2)
def iter(n):
a = 0
b = 1
count = 0
if n<=1:
return n
else:
while count < n-1:
count +=1
c = b + a
a = b
b = c
return b #return이 while문 안에 들어가있으면 한번 while문 실행하고 return 보이니까 바로 출력한다.
while True:
number = int(input("input number..."))
ts = time.time()
rec(number)
rec_elapsedTime = time.time() - ts
print("{0:.3f}".format(rec_elapsedTime))
ts = time.time()
iter(number)
rec_elapsedTime = time.time() - ts
print("{0:.3f}".format(rec_elapsedTime))
|
# 作业背景:在数据处理的步骤中,可以使用 SQL 语句或者 pandas 加 Python 库、函数等方式进行数据的清洗和处理工作。
# 因此需要你能够掌握基本的 SQL 语句和 pandas 等价的语句,利用 Python 的函数高效地做聚合等操作。
# 请将以下的 SQL 语句翻译成 pandas 语句:
import pandas as pd
import os
pwd = os.path.dirname(os.path.realpath(__file__))
data_file = os.path.join(pwd,'data.csv')
df = pd.read_csv(data_file)
# 1. SELECT * FROM data;
print(f'输出全部内容:')
print('='*30)
print(df)
print('='*30)
# 2. SELECT * FROM data LIMIT 10;
print(f'输出前10行数据:')
print('='*30)
print(df.head(10))
print('='*30)
# 3. SELECT id FROM data; //id 是 data 表的特定一列
print(f'输出id列:')
print('='*30)
print(df['id'])
print('='*30)
# 4. SELECT COUNT(id) FROM data;
print(f'输出id个数:')
print('='*30)
print(df['id'].count())
print('='*30)
# 5. SELECT * FROM data WHERE id<1000 AND age>30;
print(f'输出id<1000且age>30的数据:')
print('='*30)
print(df[df['id']<1000][df['age']>30])
print('='*30)
table1_file = os.path.join(pwd,'table1.csv')
table2_file = os.path.join(pwd,'table2.csv')
table1 = pd.read_csv(table1_file)
table2 = pd.read_csv(table2_file)
# 6. SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id;
print(f'输出table1的id和order_id的数量:')
print('='*30)
print(table1.groupby('id').order_id.nunique())
print('='*30)
# 7. SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id;
print(f'输出table1和table2 inner join的结果:')
print('='*30)
print(pd.merge(table1, table2, on='id', how='inner'))
print('='*30)
# 8. SELECT * FROM table1 UNION SELECT * FROM table2;
print(f'输出table1和table2拼接的结果:')
print('='*30)
print(pd.concat([table1, table2]))
print('='*30)
# 9. DELETE FROM table1 WHERE id=10;
print(f'删除table1中id=10的数据:')
print('='*30)
print(table1[table1['id'] != 10])
print('='*30)
# 10. ALTER TABLE table1 DROP COLUMN column_name;
print(f'删除table1中的order_id列:')
print('='*30)
print(table1.drop('order_id', axis = 1))
print('='*30)
|
# 区分以下类型哪些是容器序列哪些是扁平序列,哪些是可变序列哪些是不可变序列:
# list - 容器序列, 可变序列
list_a = [1, 'a']
list_b = list_a
print(list_b is list_a) # True
list_a[1] = 'b'
print(list_b is list_a) # True
# tuple - 容器序列, 不可变序列
tuple_a = tuple([1, 'a'])
try:
tuple_a[1] = 'b' # TypeError
except TypeError:
print('tuple object does not support item assignment')
# str - 扁平序列, 不可变序列
str_a = 'abcdef'
try:
str_a[0] = 1 # TypeError
except TypeError:
print('str object does not support item assignment')
# dict - 容器, 可变
dict_a = { 'a': 10, 'b': 'str'}
dict_b = dict_a
print(dict_b is dict_a) # True
dict_a['b'] = 12
print(dict_b is dict_a) # True
# collections.deque - 容器序列, 可变序列
from collections import deque
deque_a = deque([1, 'a'])
deque_b = deque_a
print(deque_b is deque_a) # True
deque_a[1] = 'b'
print(deque_b is deque_a) # True
|
def raisetest():
try:
integer = int(input('2의 배수를 입력하세요 : '))
if (integer % 2) != 0:
raise Exception('2의 배수가 아닙니다.')
print(integer)
except Exception as e:
print('raisetest 함수에서 예외가 발생했습니다.', e)
raise
try:
raisetest()
except Exception as e:
print('스크립트 파일에서 예외가 발생했습니다.', e)
|
import time,multiprocessing
print('Multithreads thread')
start = time.perf_counter()
def dosomething():
print("funtion sleeping zzzzzZZZZ")
time.sleep(1)
print("woke up")
p1 = multiprocessing.Process(target= dosomething)
p2 = multiprocessing.Process(target= dosomething)
p1.start()
p2.start()
## Join method will prevent execution till p1,p2 will
p1.join()
p2.join()
finish = time.perf_counter()
print('Total time taken {} secs'.format(round(finish-start,2)))
|
import re
string = "My name is John, Hi I'm John"
pattern =r"John"
newstring = re.sub(pattern,"Rob",string)
print(newstring)
|
# Create a dictionary
# Access the items in dictionary
# Changing the value of specific item in a dictionary
# Print all the key names in the dictionary
# print all the values in a dictionary, one by one
# Using the values() function return all the values of the dictionary
# Loop through both keys an value, by using the items() functions
# Check if a key exists
# Get the lenght of dictionary
# Add an item to a dictionary
# Remove an item from a dictionary
# Empty a dictionary
# Using the dict() constructor to create a dictionary
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def display_board(val):
print(val[1]+ '|' + val[2]+ '|' + val[3])
print("------")
print(val[4]+ '|' + val[5]+ '|' + val[6])
print("------")
print(val[7]+ '|' +val[8]+ '|' +val[9])
# In[2]:
test_board = ['#','X','O','X','O','X','O','X','O','X']
display_board(test_board)
# In[3]:
def player_input():
choice = 'wrong'
while choice not in ['X','O']:
choice = input("Player1 please select X OR O: ")
if choice not in ['X','O']:
print("Sorry invalid choice!")
return choice
# In[4]:
player_input()
# In[5]:
def position_choice():
position = 'wrong'
while position not in [1,2,3,4,5,6,7,8,9]:
position = int(input("Enter a position you want to pick(1-9): "))
if position not in [1,2,3,4,5,6,7,8,9]:
print ("Please enter a valid position!")
return position
##board[position] = player_input()
# In[6]:
position_choice()
# In[7]:
def place_marker(board, choice, position):
board[position]= choice
# In[8]:
place_marker(test_board, 'O', 5)
display_board(test_board)
# In[9]:
def win_check(board, mark):
return ((board[1] == mark) and (board[2] == mark) and (board[3] == mark) or
(board[4] == mark) and (board[5] == mark) and (board[6] == mark) or
(board[7] == mark) and (board[8] == mark) and (board[9] == mark) or
(board[1] == mark) and (board[4] == mark) and (board[7] == mark) or
(board[2] == mark) and (board[5] == mark) and (board[8] == mark) or
(board[3] == mark) and (board[6] == mark) and (board[9] == mark) or
(board[1] == mark) and (board[5] == mark) and (board[9] == mark) or
(board[3] == mark) and (board[5] == mark) and (board[7] == mark))
# In[10]:
win_check(test_board, "X")
# In[11]:
import random
def choose_first():
if random.randint(0, 1) == 0:
return 'Player 2'
else:
return 'Player 1'
# In[12]:
def space_check(board, position):
if board[position] == ' ':
return True
else:
return False
# In[13]:
def full_board_check(board):
for x in range(1,9):
if space_check(board, x):
return False
return True
# In[14]:
full_board_check(test_board)
# In[15]:
test_board
# In[16]:
full_board_check(test_board)
# In[17]:
def replay():
return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')
# In[19]:
print('Welcome to Tic Tac Toe!')
while replay() == True:
game_board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
display_board(game_board)
mark_player1 = player_input()
if mark_player1 == 'X':
mark_player2 == 'O'
else:
mark_player2 == 'X'
turn = choose_first()
print(turn + ' will go first.')
play_game = input('Are you ready to play? Enter Yes or No.')
if play_game.lower()[0] == 'y':
game_on = True
else:
game_on = False
while game_on:
if turn == 'Player 1':
display_board(game_board)
position = position_choice()
place_marker(game_board, mark_player1, position)
if win_check(game_board, mark_player1):
display_board(game_board)
print('Congratulations! Player 1 won the game!')
game_on = False
else:
if full_board_check(game_board):
display_board(game_board)
print('The game is a draw!')
break
else:
turn = 'Player 2'
else:
display_board(game_board)
position = position_choice()
place_marker(game_board,mark_player2, position)
if win_check(game_board, mark_player2):
display_board(game_board)
print('Player 2 has won!')
game_on = False
else:
if full_board_check(game_board):
display_board(game_board)
print('The game is a draw!')
break
else:
turn = 'Player 1'
if not replay():
break
# In[20]:
print('Welcome to Tic Tac Toe !!')
while True:
game_board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
display_board(game_board)
mark_player1 = player_input()
mark_player2 = "q"
if mark_player1 == 'X':
mark_player2 == 'O'
else:
mark_player2 == 'X'
turn = choose_first()
print(turn + ' will go first.')
play_game = input('Are you ready to play? Enter Yes or No.')
if play_game.lower()[0] == 'y':
game_on = True
else:
game_on = False
while game_on:
if turn == 'Player 1':
display_board(game_board)
position = position_choice()
place_marker(game_board, mark_player1, position)
if win_check(game_board, mark_player1):
display_board(game_board)
print('Congratulations! Player 1 won the game!')
game_on = False
else:
if full_board_check(game_board):
display_board(game_board)
print('The game is a draw!')
break
else:
turn = 'Player 2'
else:
display_board(game_board)
position = position_choice()
place_marker(game_board,mark_player2, position)
if win_check(game_board, mark_player2):
display_board(game_board)
print('Player 2 has won!')
game_on = False
else:
if full_board_check(game_board):
display_board(game_board)
print('The game is a draw!')
break
else:
turn = 'Player 1'
if not replay():
break
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
|
# Ingreso de datos de triangulo 1
print("Ingrese datos del triangulo 1:\n")
lado1 = float (input ("Ingrese lado 1 del triangulo:"))
lado2 = float (input ("Ingrese lado 2 del triangulo:"))
lado3 = float (input ("Ingrese lado 3 del triangulo:"))
ang1 = float (input ("Ingrese angulo 1 del triangulo:"))
ang2 = float (input ("Ingrese angulo 2 del triangulo:"))
ang3 = float (input ("Ingrese angulo 3 del triangulo:"))
# Ingreso de datos de triangulo 2
print("Ingrese Datos del triangulo 2:\n")
lado11 = float (input ("Ingrese lado 1 del triangulo:"))
lado22 = float (input ("Ingrese lado 2 del triangulo:"))
lado33 = float (input ("Ingrese lado 3 del triangulo:"))
ang11 = float (input ("Ingrese angulo 1 del triangulo:"))
ang22 = float (input ("Ingrese angulo 2 del triangulo:"))
ang33 = float (input ("Ingrese angulo 3 del triangulo:"))
# Presentacion de resultados
if lado1 == lado11 and lado2 == lado22 and lado3 == lado33 and ang1 == ang11 and ang2 == ang22 and ang3 == ang33:
print("Los triangulos SON CONGRUENTES")
else:
print("Los triangulos NO SON CONGRUENTES")
|
from coin import Coin
import matplotlib.pyplot as plt
import os.path
import pathlib
class Game:
def __init__(self):
self.coin = Coin(0.4)
self.goal = 100
self.discount_rate = 1
self.epsilon = 0.000001
self.value_archive = []
self.action_archive = []
@staticmethod
def get_path(file_name):
abs_path = pathlib.Path(__file__).parent.absolute()
complete_name = os.path.join(abs_path,'records',file_name+'.png')
return complete_name
def init_states(self): #needs to be outside of __init__ or else recursion error for subclass initialization
self.states = [State(i) for i in range(self.goal+1)]
def change_odds(self,p_succ):
self.coin = Coin(p_succ)
def change_goal(self,new_goal):
self.goal = new_goal
def display(self): #for debugging only
for state in game.states:
print(state,state.actions)
def display_values(self): #for debugging only
for state in game.states:
print(f'{state}={state.value:.3f}', end='\t')
print('\n')
def new_state(self,state,num): #calculate the new state an action will lead to
return self.states[state.money+num]
def update_state_values(self): #where the magic happens
for state in self.states:
_value, _best_action = state.value, state.best_action
if state.money == 12:
a=3
if state.actions:
for action in state.actions:
win_state = self.new_state(state,action)
lose_state = self.new_state(state,-action)
v_s = self.coin.p_succ*(state.reward + self.discount_rate * win_state.value) + self.coin.p_fail*(state.reward + self.discount_rate * lose_state.value)
if v_s > _value + self.epsilon:
_value, _best_action = v_s, action
else:
_value, _best_action = state.reward, 0
state.value, state.best_action = _value, _best_action
def archive_values(self):
self.value_archive.append(([state.money for state in self.states],[state.value for state in self.states]))
def archive_actions(self):
self.action_archive.append(([state.money for state in self.states],[state.best_action for state in self.states]))
def plot_values(self):
for itr in range(len(self.value_archive)):
money_data,value_data = self.value_archive[itr]
plt.plot(money_data,value_data,label = f'Iter: {itr}')
plt.legend()
plt.savefig(self.get_path(f'act_iter_{itr}'))
# plt.show()
def plot_actions(self):
for itr in range(len(self.action_archive)):
plt.clf()
money_data,action_data = self.action_archive[itr]
plt.bar(money_data,action_data,label = f'Iter: {itr}')
plt.legend()
plt.savefig(self.get_path(f'iter_{itr}'))
# plt.show()
def run(self,itr=1):
for _ in range(itr):
self.update_state_values()
self.archive_values()
self.archive_actions()
class State(Game):
def __init__(self,money,init_value=0):
super().__init__()
self.money = money
self.actions = [s for s in range(1,min(self.money,(self.goal-self.money))+1)]
self.reward = self.set_reward()
self.value = init_value
self.best_action = 0
def display(self):
print(f'State {self.money}: Value={self.value:.3f}\tAction={self.best_action}')
def set_reward(self):
if self.money == self.goal:
return 1
elif self.money == 0:
return 0
else:
return 0
def __repr__(self):
return f'State {self.money}'
if __name__ == "__main__":
game = Game()
game.init_states()
game.run(itr=15)
game.plot_values()
game.plot_actions()
|
class SimActLocation:
"""
Structure-like class used to bundle the instruction address and statement index of a given SimAction in order to
uniquely identify a given SimAction
"""
def __init__(self, bbl_addr: int, ins_addr: int, stmt_idx: int):
self.bbl_addr = bbl_addr
self.ins_addr = ins_addr
self.stmt_idx = stmt_idx
def __repr__(self):
return f"SimActLocation<{hex(self.bbl_addr)}.{hex(self.ins_addr)}.{hex(self.stmt_idx)}>"
def __hash__(self):
return hash((self.bbl_addr, self.ins_addr, self.stmt_idx))
def __eq__(self, other):
if not isinstance(other, SimActLocation):
return False
return self.bbl_addr == other.bbl_addr and self.ins_addr == other.ins_addr and self.stmt_idx == other.stmt_idx
# def __add__(self, other):
# if not isinstance(other, int):
# return
#
# self._stmt_idx += other
DEFAULT_LOCATION = SimActLocation(0, 0, 0) # To be used when a location isn't necessary (eg, ConstantDepNode)
class ParsedInstruction:
"""
Used by parser to facilitate linking with recent ancestors in an efficient manner
"""
def __init__(
self,
ins_addr: int, # Instruction that was parsed
min_stmt_idx: int, # Index of first statement in instruction
max_stmt_idx: int,
): # Index of last statement in instruction
self.ins_addr = ins_addr
self.min_stmt_idx = min_stmt_idx
self.max_stmt_idx = max_stmt_idx
|
from typing import Set
from collections import defaultdict
import ailment
class Goto:
"""
Describe the existence of a goto (jump) statement. May have multiple gotos with the same address (targets
will differ).
"""
def __init__(self, block_addr=None, ins_addr=None, target_addr=None):
"""
:param block_addr: The block address this goto is contained in
:param ins_addr: The instruction address this goto is at
:param target_addr: The target this goto will jump to
"""
self.block_addr = block_addr
self.ins_addr = ins_addr
self.target_addr = target_addr
def __hash__(self):
return hash(f"{self.block_addr}{self.ins_addr}{self.target_addr}")
def __str__(self):
if not self.addr or not self.target_addr:
return f"<Goto {self.__hash__()}>"
return f"<Goto: [{hex(self.addr)}] -> {hex(self.target_addr)}>"
def __repr__(self):
return self.__str__()
@property
def addr(self):
return self.block_addr or self.ins_addr
class GotoManager:
"""
Container class for all Gotos found in a function after decompilation structuring.
This should be populated using GotoSimplifier.
"""
def __init__(self, func, gotos=None):
self.func = func
self.gotos: Set[Goto] = gotos or set()
self._gotos_by_addr = None
def __str__(self):
return f"<GotoManager: func[{hex(self.func.addr)}] {len(self.gotos)} gotos>"
def __repr__(self):
return self.__str__()
def gotos_by_addr(self, force_refresh=False):
"""
Returns a dictionary of gotos by addresses. This set can CONTAIN DUPLICATES, so don't trust
this for a valid number of gotos. If you need the real number of gotos, just get the size of
self.gotos. This set should mostly be used when checking if a block contains a goto, since recording
can be recorded on null-addr blocks.
:param force_refresh: Don't use the cached self._gotos_by_addr
:return:
"""
if not force_refresh and self._gotos_by_addr:
return self._gotos_by_addr
self._gotos_by_addr = defaultdict(set)
for goto in self.gotos:
if goto.block_addr is not None:
self._gotos_by_addr[goto.block_addr].add(goto)
if goto.ins_addr is not None:
self._gotos_by_addr[goto.ins_addr].add(goto)
return self._gotos_by_addr
def gotos_in_block(self, block: ailment.Block) -> Set[Goto]:
gotos_by_addr = self.gotos_by_addr()
gotos = set()
if block.addr in gotos_by_addr:
gotos.update(gotos_by_addr[block.addr])
for stmt in block.statements:
if stmt.ins_addr in gotos_by_addr:
gotos.update(gotos_by_addr[stmt.ins_addr])
return gotos
|
'''Example script to generate text from Nietzsche's writings.
At least 20 epochs are required before the generated text
starts sounding coherent.
It is recommended to run this script on GPU, as recurrent
networks are quite computationally intensive.
If you try this script on new data, make sure your corpus
has at least ~100k characters. ~1M is better.
'''
from __future__ import print_function
import collections
import os
import tensorflow as tf
from keras.models import Sequential, load_model
from keras.layers import Dense, Activation, Embedding, Flatten, Dropout
from keras.layers import LSTM
from keras.optimizers import RMSprop, Adam
from keras.preprocessing.text import one_hot
from keras.utils.data_utils import get_file
import numpy as np
import random
import sys
import argparse
"""To run this code, you'll need to first download and extract the text dataset
from here: http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz. Change the
data_path variable below to your local exraction path"""
data_path = "C:\\Users\Andy\Documents\simple-examples\data"
parser = argparse.ArgumentParser()
# parser.add_argument('run_opt', type=int, default=1, help='An integer: 1 to train, 2 to test')
parser.add_argument('data_path', type=str, default=data_path, help='The full path of the training data')
args = parser.parse_args()
if args.data_path:
data_path = args.data_path
def read_words(filename):
with tf.gfile.GFile(filename, "r") as f:
return f.read().decode("utf-8").replace("\n", "<eos>").split()
def build_vocab(filename):
data = read_words(filename)
counter = collections.Counter(data)
count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
words, _ = list(zip(*count_pairs))
word_to_id = dict(zip(words, range(len(words))))
return word_to_id
def file_to_word_ids(filename, word_to_id):
data = read_words(filename)
return [word_to_id[word] for word in data if word in word_to_id]
def load_data():
# get the data paths
train_path = os.path.join(data_path, "ptb.train.txt")
valid_path = os.path.join(data_path, "ptb.valid.txt")
test_path = os.path.join(data_path, "ptb.test.txt")
# build the complete vocabulary, then convert text data to list of integers
word_to_id = build_vocab(train_path)
train_data = file_to_word_ids(train_path, word_to_id)
valid_data = file_to_word_ids(valid_path, word_to_id)
test_data = file_to_word_ids(test_path, word_to_id)
vocabulary = len(word_to_id)
reversed_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))
print(train_data[:5])
print(word_to_id)
print(vocabulary)
print(" ".join([reversed_dictionary[x] for x in train_data[:10]]))
return train_data, valid_data, test_data, vocabulary, reversed_dictionary
train_data, valid_data, test_data, vocabulary, reversed_dictionary = load_data()
class KerasBatchGenerator(object):
def __init__(self, data, num_steps, target_size, batch_size, skip_step=5):
self.data = data
self.num_steps = num_steps
self.target_size = target_size
self.batch_size = batch_size
# this will track the progress of the batches sequentially through the
# data set - once the data reaches the end of the data set it will reset
# back to zero
self.current_idx = 0
# skip_step is the number of words which will be skipped before the next
# batch is skimmed from the data set
self.skip_step = skip_step
def generate(self):
x = np.zeros((batch_size, self.num_steps))
y = np.zeros((batch_size, self.target_size))
while True:
for i in range(self.batch_size):
if self.current_idx + self.num_steps + self.target_size >= len(self.data):
# reset the index back to the start of the data set
self.current_idx = 0
x[i, :] = self.data[self.current_idx:self.current_idx + self.num_steps]
y[i, :] = self.data[self.current_idx + self.num_steps:self.current_idx + self.num_steps + self.target_size]
self.current_idx += self.skip_step
yield x, y
num_steps = 25
target_size = 10
batch_size = 100
train_data_generator = KerasBatchGenerator(train_data, num_steps, target_size, batch_size)
valid_data_generator = KerasBatchGenerator(valid_data, num_steps, target_size, batch_size)
hidden_layers = 300
model = Sequential()
model.add(Embedding(vocabulary, hidden_layers, input_length=num_steps))
model.add(LSTM(hidden_layers, return_sequences=True))
model.add(LSTM(hidden_layers))
model.add(Dropout(0.2))
model.add(Dense(target_size))
model.add(Activation('softmax'))
# optimizer = RMSprop(lr=0.01)
optimizer = Adam()
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
print(model.summary())
num_epochs = 20
model.fit_generator(train_data_generator.generate(), len(train_data)//batch_size, num_epochs,
validation_data=valid_data_generator.generate(),
validation_steps=len(valid_data)//batch_size)
model.save(data_path + "model.h5")
|
# purpose is to find the 'stationary number'
# stationary number = number that will be the same regardless how many times it goes through loop
# div_13 sequence: [1, 10, 9, 12, 3, 4]
# eventually recursive calls should yield n = total = stationary number
def thirt(n):
total = 0
a = [int(x) for x in str(n)]
a.reverse()
for i in range(len(a)):
div_13 = (10**i) % 13
total += a[i]*div_13
if total != n:
return thirt(total)
else:
return total
|
# works for most cases, except case where there is inner solution
# example ([5,3,7,5], 10) returns [5,5] when [3,7] is solution
def sum_pairs(ints, s):
for i in range(0,len(ints)):
for j in range(i+1,len(ints)):
if ints[i] + ints[j] == s:
return [ints[i],ints[j]]
return None
|
nombre = int(input())
nombre += 1
print(nombre)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("../..")
import game
def saisieCoup(jeu):
""" jeu -> coup
Retourne un coup a jouer
"""
print("Les coups valides sont:")
print(str(game.getCoupsValides(jeu)))
i= int(input("Entrer la colonne du coup à jouer: "))
return [jeu[1] - 1, i]
|
def WriteArrayToFile (array, filename = 'result.txt'):
''' This procedure takes a name of a file and writes to it an array of data'''
f = open(filename, 'w')
'''for revstep in array:
strarray = []
for pos in revstep:
sign = ''
if pos > 0:
sign = '+'
strarray.append(sign + str(pos))
s = ' '.join(strarray)
f.write('(' + s + ')')
f.write('\n')'''
for pair in array:
p1 = str(pair[0])
p2 = str(pair[1])
f.write('(' + p1 + ', ' + p2 + ')')
f.write('\n')
f.close()
return
|
def ChromosomeToCycle(Chromosome):
'''Chromosome is a sequence of synteny blocks in format [-3, +1, +2]
Return its representation of nodes [6, 5, 1, 2, 3, 4]'''
nodes = []
for el in Chromosome:
if el > 0:
nodes.append(el*2-1)
nodes.append(el*2)
else:
nodes.append(-el*2)
nodes.append(-el*2-1)
return nodes
def CycleToChromosome(Nodes):
'''An opposite procedure to the above one'''
Chromosome = []
for i in range(len(Nodes)/2):
if Nodes[2*i] < Nodes[2*i+1]:
Chromosome.append(Nodes[2*i+1]/2)
else:
Chromosome.append(-Nodes[2*i]/2)
return Chromosome
def PairToBlock(Nodes):
'''By pair of nodes return block number'''
if Nodes[0] < Nodes[1]:
block = Nodes[1]/2
else:
block = -Nodes[0]/2
return block
def ColoredEdges(G):
'''Given a genome G in format [+1, -2, -3], [+4, +5, -6], output
a collection of colored edges in its graph in format [2, 4], [3, 6],...'''
edges = []
for chromosome in G:
nodes = ChromosomeToCycle(chromosome)
for i in range(len(chromosome)-1):
edges.append([nodes[2*i+1], nodes[2*i+2]])
i = len(nodes)-1
edges.append([nodes[i], nodes[0]])
return edges
def ColoredEdgesGraph(G):
'''Given a genome G in format [+1, -2, -3], [+4, +5, -6], output
a collection of colored edges in its graph in format
{2: 4, 4: 2, 3:6],... Each non-directed edge is represented
as 2 oppositly directed adges'''
edges = {}
for chromosome in G:
nodes = ChromosomeToCycle(chromosome)
for i in range(len(chromosome)-1):
edges[nodes[2*i+1]] = nodes[2*i+2]
edges[nodes[2*i+2]] = nodes[2*i+1]
i = len(nodes)-1
edges[nodes[i]] = nodes[0]
edges[nodes[0]] = nodes[i]
return edges
def GraphToGenome(Graph):
'''From a graph, which is an array of edges, find its original genome
as a sequence of synteny blocks'''
G = []
chromosome = []
while len(Graph) > 0:
if chromosome == []:
curr_edge = Graph[0]
new_edge = []
Graph.remove(curr_edge)
tail = curr_edge[0]
if tail % 2 == 0:
head = tail -1
else:
head = tail + 1
block = CycleToChromosome([head, tail])
chromosome += block
head = curr_edge[1]
if head % 2 == 0:
tail = head - 1
else:
tail = head + 1
for edge in Graph:
if edge[0] == tail:
chromosome += CycleToChromosome([head, tail])
new_edge = edge
Graph.remove(edge)
break
if edge[1] == tail:
chromosome += CycleToChromosome([head, tail])
new_edge = [edge[1], edge[0]]
Graph.remove(edge)
break
if new_edge == []: #cycle is done
G.append(chromosome)
chromosome = []
else: #we found new edge in chain, add the synteny block
curr_edge = new_edge * 1
new_edge = []
G.append(chromosome)
return G
def GraphToGenomeGraph(Graph):
'''From a graph, which is a dictionary of oppositely directed edges,
find its original genome as a sequence of synteny blocks'''
G = []
chromosome = []
while len(Graph) > 0:
if chromosome == []:
index = Graph.keys()[0]
curr_edge = [index, Graph[index]]
Graph.pop(curr_edge[0])
Graph.pop(curr_edge[1])
tail = curr_edge[0]
if tail % 2 == 0:
head = tail -1
else:
head = tail + 1
block = PairToBlock([head, tail])
chromosome.append(block)
head = curr_edge[1]
if head % 2 == 0:
tail = head - 1
else:
tail = head + 1
if tail in Graph:
chromosome.append(PairToBlock([head, tail]))
curr_edge = [tail, Graph[tail]]
Graph.pop(curr_edge [0])
Graph.pop(curr_edge [1])
else:
G.append(chromosome)
chromosome = []
if chromosome <> []:
G.append(chromosome)
return G
def BreakGraph(Graph, i1, i2, j1, j2):
'''In Graph destroy edges i1-i2, j1-j2, and create i1-j1, i2-j2'''
if [i1, i2] in Graph:
Graph.remove([i1, i2])
elif [i2, i1] in Graph:
Graph.remove([i2, i1])
if [j1, j2] in Graph:
Graph.remove([j1, j2])
elif [j2, j1] in Graph:
Graph.remove([j2, j1])
Graph.append([i1, j1])
Graph.append([i2, j2])
return Graph
def BreakGenome(G, i1, i2, j1, j2):
'''Given a genome (one chromosome) as a sequence of synteny blocks,
return its broken version'''
graph = ColoredEdges(G)
new_graph = BreakGraph(graph, i1, i2, j1, j2)
new_genome = GraphToGenome(new_graph)
return new_genome
def NonTrivialCycle(G1, G2):
'''Return any non-trivial cycle from Graph'''
cycle = []
redturn = True
while (len(G1) > 0) or (len(G2) > 0):
if cycle == []:
if redturn:
curr_edge = G1[0]
G1.remove(curr_edge)
else:
curr_edge = G2[0]
G2.remove(curr_edge)
redturn = not redturn
new_edge = []
curr_node = curr_edge[1]
cycle.append(curr_edge)
if redturn:
for edge in G1:
if curr_node in edge:
cycle.append(edge)
new_edge = edge
G1.remove(edge)
break
else:
for edge in G2:
if curr_node in edge:
cycle.append(edge)
new_edge = edge
G2.remove(edge)
break
if new_edge == []: #cycle is done
if len(cycle) == 2:
cycle = []
else:
return cycle
else: #we found new edge in chain
redturn = not redturn
curr_edge = new_edge * 1
new_edge = []
if curr_node == curr_edge[0]:
curr_node = curr_edge[1]
else:
curr_node = curr_edge[0]
if len(cycle) > 4:
return cycle
if len(cycle) == 2:
cycle = []
return cycle
def NonTrivialCycleGraph(G1, G2):
'''Return any non-trivial cycle from Graph formed by
dictionaries G1 and G2'''
cycle = []
redturn = True
while (len(G1) > 0) or (len(G2) > 0):
if cycle == []:
if redturn:
index = G1.keys()[0]
curr_edge = [index, G1[index]]
G1.pop(curr_edge[0])
G1.pop(curr_edge[1])
else:
index = G2.keys()[0]
curr_edge = [index, G2[index]]
G2.pop(curr_edge[0])
G2.pop(curr_edge[1])
redturn = not redturn
curr_node = curr_edge[1]
cycle.append(curr_edge)
if redturn:
if curr_node in G1:
curr_edge = [curr_node, G1[curr_node]]
curr_node = curr_edge[1]
cycle.append(curr_edge)
G1.pop(curr_edge[0])
G1.pop(curr_edge[1])
redturn = not redturn
else:
if len(cycle) == 2:
cycle = []
else:
return cycle
else:
if curr_node in G2:
curr_edge = [curr_node, G2[curr_node]]
curr_node = curr_edge[1]
cycle.append(curr_edge)
G2.pop(curr_edge[0])
G2.pop(curr_edge[1])
redturn = not redturn
else:
if len(cycle) == 2:
cycle = []
else:
return cycle
if len(cycle) > 3:
return cycle
if len(cycle) == 2:
cycle = []
return cycle
def CycleCount(G1, G2):
'''Return count of cycles in graph united by G1 and G2'''
cycle = []
count = 0
redturn = True
while (len(G1) > 0) or (len(G2) > 0):
if cycle == []:
if redturn:
curr_edge = G1[0]
G1.remove(curr_edge)
else:
curr_edge = G2[0]
G2.remove(curr_edge)
redturn = not redturn
new_edge = []
curr_node = curr_edge[1]
cycle.append(curr_edge)
if redturn:
for edge in G1:
if curr_node in edge:
cycle.append(edge)
new_edge = edge
G1.remove(edge)
break
else:
for edge in G2:
if curr_node in edge:
cycle.append(edge)
new_edge = edge
G2.remove(edge)
break
if new_edge == []: #cycle is done
cycle = []
count += 1
else: #we found new edge in chain
redturn = not redturn
curr_edge = new_edge * 1
new_edge = []
if curr_node == curr_edge[0]:
curr_node = curr_edge[1]
else:
curr_node = curr_edge[0]
if cycle <> []:
count += 1
return count
def ShortestRearrangementGraph(P, Q):
'''Rearrange genome P with 2-breaks, in shortest way, to Q
Both represented as set of synteny blocks'''
reversals = [P]
RedEdges = ColoredEdgesGraph(P)
BlueEdges = ColoredEdgesGraph(Q)
for i in range(10000):
RedCopy = RedEdges.copy()
BlueCopy = BlueEdges.copy()
cycle = NonTrivialCycleGraph(RedCopy, BlueCopy)
while cycle <> []:
if (cycle[1][0] in BlueEdges) and (cycle[1][1] == BlueEdges[cycle[1][0]]):
j1, i2 = cycle[1]
else:
return '2nd node is not blue!'
i1 = cycle[0][0]
RedEdges.pop(i1)
RedEdges.pop(j1)
j2 = cycle[2][1]
RedEdges.pop(i2)
RedEdges.pop(j2)
RedEdges[j1] = i2
RedEdges[i2] = j1
RedEdges[j2] = i1
RedEdges[i1] = j2
RedCopy = RedEdges.copy()
P = GraphToGenomeGraph(RedCopy)
reversals.append(P)
#print len(P)
#print len(Q)
RedCopy = RedEdges.copy()
BlueCopy = BlueEdges.copy()
cycle = NonTrivialCycleGraph(RedCopy, BlueCopy)
return reversals
def ShortestRearrangement(P, Q):
'''Rearrange P with 2-breaks, in shortest way, to Q'''
#reversals = [P]
reversals = 0
RedEdges = ColoredEdges(P)
BlueEdges = ColoredEdges(Q)
Graph = RedEdges + BlueEdges
cycle = NonTrivialCycle(Graph)
while cycle <> []:
for i in range(1, len(cycle)):
if cycle[i] in BlueEdges:
break
j1, i2 = cycle[i]
'''if cycle[i-1][1] == j1:
i1 = cycle[i-1][0]
if cycle[i-1][0] == j1:
i1 = cycle[i-1][1]
RedEdges.remove(cycle[i-1])
if cycle[i+1][1] == i2:
j2 = cycle[i+1][0]
if cycle[i+1][0] == i2:
j2 = cycle[i+1][1]
RedEdges.remove(cycle[i+1])'''
for edge in (cycle[i-1], cycle[i+1]):
if edge[1] == j1:
i1 = edge[0]
RedEdges.remove(edge)
break
if edge[0] == j1:
i1 = edge[1]
RedEdges.remove(edge)
break
for edge in (cycle[i-1], cycle[i+1]):
if edge[1] == i2:
j2 = edge[0]
RedEdges.remove(edge)
break
if edge[0] == i2:
j2 = edge[1]
RedEdges.remove(edge)
break
#RedEdges = BreakGraph(RedEdges, i1, j1, j2, i2)
RedEdges.append([j1, i2])
RedEdges.append([j2, i1])
#P = GraphToGenome(RedEdges)
#reversals.append(P)
reversals += 1
Graph = RedEdges + BlueEdges
cycle = NonTrivialCycle(Graph)
return reversals
|
import HammingDistance as HD
def ApproximatePatternCount(Text, Pattern, dist):
'''Finds in Text all Patterns and similar patterns of distance <-dist'''
count = 0
k = len(Pattern)
for i in range(len(Text) - k + 1):
if HD.HammingDistance(Text[i: i + k], Pattern) <= dist:
count +=1
return count
|
#!/usr/bin/python
#coding:utf8
from algorithms.common.sortbase import Key, IntNode, SortBase
class SelectionSort(SortBase):
@staticmethod
def sort(a):
length = len(a)
for i in range(length):
#将首号元素标记位最小
min_index = i
#从下一个元素开始遍历记录最小的索引
for j in range(i + 1, length):
if SortBase.less(a[j], a[min_index]):
min_index = j
#交换当前元素和最小元素
SortBase.exch(a, i, min_index)
def main():
pass
if __name__ == '__main__':
main()
|
# Title: Computing Pi Using Archimedes' Method
# Author: Lisa Carpenter
'''Abstract: This program computes the value of pi to within 3 decimal places. The method used will be to calculate the perimeters of two polygons, one polygon circumscribed about the circle and the other inscribed in the circle. The number of sides on the two polygons is increased until the difference between the two values is less than 1.0E-4, giving a lower and upper bound for pi. A list of values will be generated as well, using the % function to ensure consistency and equal column widths.'''
import math
# define the maximum error in approximating pi
# start with a 3-sided polygon
eps = 0.0001
n = 3
# the upper and lower bounds of pi, respectively
piUpper = 1
piLower = 0
# initialize columns for output table
listSides=[]
listPiLower=[]
listPiUpper=[]
while abs(piUpper - piLower) >= eps:
theta = 360.0/n
piLower = n * math.sin(math.radians(theta/2.0))
piUpper = n * math.tan(math.radians(theta/2.0))
listSides.append(n)
listPiLower.append(piLower)
listPiUpper.append(piUpper)
n += 1
#print the headers on the list
print('%8s\t%16s\t%16s\t' % ('# Sides','Lower Bound','Upper Bound'))
numValues = len(listSides)
# print every 10th element on the list by using mod 10 and formatting for
# column width, precision, and tabs.
for i in range(numValues):
if i % (math.ceil(listSides[-1]/10)) == 0:
print('%8d\t%16.5f\t%16.5f\t' % (listSides[i],listPiLower[i],listPiUpper[i]))
|
# Chaotic Behavior of Pendula
# Author: Lisa Carpenter
'''Abstract: A driven and damped pendulum will exhibit chaotic behavior if
initial conditions are set appropriately. The chaotic behavior is investigated
by modeling the behavior of two pendula with slightly different initial
conditions. The value for theta as a function of time for a driven/damped pendulum
is determined by using the Euler-Cromer method. When log(delta_theta) is plotted
against t, chaotic behavior will be evident for small time scales, and delta_theta
increases linearly with time. This is indicative of a chaotic system. Because the
semi-log y plot shows a linear trend, delta_theta = exp[lambda*t), where lambda is
the slope of the semi-log graph, and lambda is a parameter called the Lyapunov Exponent.
This parameter is characteristic of chaotic behavior. The Lyapunov Exponent for this
behavior is determined visually to be around 0.0039, with a y-intercept of 1E-05.
When the Lyapunov Exponent changes sign, the chaotic regime has been met, which is
confirmed by this model.'''
from pylab import *
# initialize gravity, pendulum length, damping q, end time, dt, and driving force Fd
g = 9.81
l = 9.81
q = 0.5
t_end = 120.0
dt = 0.01
Fd = 1.2
numSteps = int(t_end / dt)
t = arange(0.0, t_end, dt)
theta1 = zeros([numSteps])
theta2 = zeros([numSteps])
# initialize thetas for pendula to differ by 0.001
theta1[0] = 0.2
theta2[0] = 0.201
# angular frequency, omega, is used to calculate subsequent values of theta1 and theta2
omega1 = zeros([numSteps])
omega2 = zeros([numSteps])
omega1[0] = 0
omega2[0] = 0
# apply Euler-Cromer method to model omegas and thetas
for n in range(1, numSteps):
omega1[n] = omega1[n - 1]-((g / l * sin(theta1[n - 1]) + q * omega1[n - 1] + Fd * sin((2.0 / 3.0) * t[n - 1]))) * dt
theta1[n] = theta1[n - 1] + omega1[n] * dt
for m in range(1, numSteps):
omega2[m] = omega2[m - 1] - ((g / l * sin(theta2[m - 1])+q * omega2[m - 1] + Fd * sin((2.0 / 3.0) * t[m - 1]))) * dt
theta2[m] = theta2[m - 1] + omega2[m] * dt
y = exp(0.049*t)*exp(-10**-5)
semilogy(t,(theta1 - theta2))
plot(t,y)
xlabel('Time [seconds]')
ylabel('Theta 1 - Theta 2 [radians]')
suptitle('Chaotic Behavior of Two Pendula - Delta Theta Versus Time')
show()
|
"""
Rules of Life
- Death
If there is no surrounding unit alive then die
"""
import random
import time
import sys
from colorama import Fore, Style
size = None
spawn = None
def usage():
print("Usage: game.py size spawn")
def main():
global size
global spawn
if len(sys.argv) < 3:
usage()
return
else:
try:
size = int(sys.argv[1])
spawn = int(sys.argv[2])
except:
usage()
return
print("My Game of Life")
world = [[0] * size for _ in range(size)]
for x in range(spawn):
seed(world, 0, size, 0, size)
pworld(world)
time.sleep(2)
rounds = 0
while(True):
if not loop(world):
break
rounds = rounds + 1
pworld(world)
time.sleep(1)
print()
print("Survived:", rounds)
def seed(world, minX, maxX, minY, maxY):
x = random.randint(minX, maxX - 1)
y = random.randint(minY, maxY - 1)
world[x][y] = 1
def loop(world):
living = False
action = False
for y in range(len(world)):
for x in range(len(world[y])):
if world[y][x]:
# Alive
living = True
if act(world[y][x], world, x, y):
action = True
if living and action:
return True
else:
return False
def act(unit, world, x, y):
"""
Makes a decision for the unit based on surrounding units
"""
resource = surrounding(unit, world, x, y)
if unit:
# Currently alive
if resource < 2:
die(unit, world, x, y)
return True
elif resource > 3:
die(unit, world, x, y)
return True
else:
if resource > 3:
live(unit, world, x, y)
return True
# Currently Dead
return False
def live(unit, world, x, y):
# print("Born: ", x, y)
world[y][x] = 1
def die(unit, world, x, y):
# print("Killed: ", x, y)
world[y][x] = 0
def isAlive(x, y, world):
if x < 0 or x >= size or y < 0 or y >= size:
return 0
if world[y][x]:
return 1
else:
return 0
def surrounding(unit, world, x, y):
score = 0
# Above
score = score + isAlive(x, y - 1, world)
# Below
score = score + isAlive(x, y + 1, world)
# Left
score = score + isAlive(x - 1, y, world)
# Right
score = score + isAlive(x + 1, y, world)
# Top right
score = score + isAlive(x + 1, y - 1, world)
# Top left
score = score + isAlive(x - 1, y - 1, world)
# Bottom right
score = score + isAlive(x + 1, y + 1, world)
# Bottom left
score = score + isAlive(x - 1, y + 1, world)
return score
def pworld(world):
for row in world:
for element in row:
if element:
print(Fore.GREEN + "o", end=" ")
else:
print(Fore.RED + "x", end=" ")
print(Style.RESET_ALL)
print()
main()
|
import time
num=input("Ramdeni Procentit Ginda Rom Ikos Kle( Es Sxvas Ar Anaxo Ubralod Utiteb ): ")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
print("↓")
name = input("Klis Procentis Damtvleli. Chaweret Saxeli: ")
print("Vitvli Klis Procents...")
time.sleep(2)
for i in range(int(num)):
print(name,i,"% It Klea")
input("\n\nGavatave, Daachire ENTER Gasasvlelad.")
|
#Enter a 4-digit number and print its reverse.
n=int(input("Enter a no.(4-digit):"))
a=3
temp=0
ans=0
while a>=0:
temp=n%10
n=n//10
ans=ans+(10**a)*temp
#print("temp=",temp)
#print("n=",n)
#print("ans=",ans)
a=a-1
print("The reverse no.=",ans)
|
import sys
class stack:
def __init__(self):
self.stack =[None]*100
self.top=-1
def isFull(self):
if self.top==100:
return True
else:
return False
def isEmpty(self):
if self.top==-1:
return True
return False
def push(self,ele):
if self.isFull():
print("stack overflow")
return
self.top+=1
self.stack[self.top]= ele
def pop(self):
if self.isEmpty():
print("Stack Uderflow")
return
d = self.stack[self.top]
self.top-=1
return d
def peek(self):
if self.isEmpty():
print("Stack Underflow")
sys.exit(0)
d= self.stack[self.top]
return d
def display(self):
if self.isEmpty():
print("Stack is empty")
sys.exit(0)
temp=self.top
while temp>=0:
print(self.stack[temp])
temp-=1
if __name__=='__main__':
s= stack()
while(1):
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display all stack elements")
print("5. Exit")
print("Enter your choice")
choice = int(input())
if choice==1:
value=int(input("Enter value to push"))
s.push(value)
elif choice==2:
d=s.pop()
print("popped element ",d)
elif choice==3:
print("Top of the stack is ", s.peek)
elif choice==4:
s.display()
else:
sys.exit(0)
|
def majorityElement(nums):
count = 0
count1 = 0
for i in range(len(nums)):
if(count ==0):
m = nums[i]
count += 1
else:
if m == nums[i]:
count += 1
else:
count -= 1
for i in range(len(nums)):
if nums[i] == m:
count1 += 1
else:
continue
l = len(nums)/2
if count1>l:
return m
else:
return False
nums = [2, 8, 7, 2, 2, 2, 2,1, 1]
print(majorityElement(nums))
|
# COMPULSORY TASK - JHB Metro Police Demerit
your_speed = int(input("What was your average speed in km/h: "))
average_speed = int(input("What was the allowed speed on the road: "))
diff = your_speed - average_speed
if your_speed <= average_speed:
print("Ok!")
else:
point = diff/5
point = int(point)
print(point)
if point > 12:
print("Time to go to jail!")
|
class SymbolEntry:
def __init__(self, line, is_int, is_pointer = None, value = None):
self.is_int = is_int
self.is_pointer = is_pointer
self.values = []
self.values += [(line, value)]
# Returns corresponding type
def get_type(self):
return (self.is_int, self.is_pointer)
# Returns corresponding value
def get_value(self):
return self.is_int, self.is_pointer, self.values[-1][1]
# Returns corresponding history
def get_history(self):
return self.is_int, self.is_pointer, self.values
# Updates corresponding value
def update_value(self, line, value):
self.values.append((line, value))
class SymbolTable:
def __init__(self):
self.symbols = {}
# Adds a new symbol
def add(self, name, entry):
if name in self.symbols:
return False
self.symbols[name] = entry
return True
# Searches symbol for name
def search(self, name):
try:
return self.symbols[name]
except KeyError:
return None
|
#!/usr/bin/python3
def max_integer(my_list=[]):
if len(my_list) == 0:
return None
max_value = my_list[0]
for i in my_list:
if i > max_value:
max_value = i
return max_value
|
#!/usr/bin/python3
"""
function that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
def text_indentation(text):
"""
function that prints a text with 2 new lines
after each of these characters: ., ? and :
"""
if type(text) != str:
raise TypeError('text must be a string')
for i in range(len(text)):
if i == 0 or i == (len(text) - 1):
if text[i] != ' ':
print('{}'.format(text[i]), end='')
elif text[i - 1] in ('.', '?', ':'):
if text[i] == ' ':
print('\n')
else:
print('\n{}'.format(text[i]))
else:
print('{}'.format(text[i]), end='')
|
#!/usr/bin/python3
def uniq_add(my_list=[]):
suma = 0
new_list = sorted(my_list[:])
for i in range(len(new_list)):
if i == 0:
suma += new_list[i]
elif new_list[i] != new_list[i - 1]:
suma += new_list[i]
return suma
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Tianyanfei
# @Mail : [email protected]
# @Data : 2016-11-24 16:17:48
# @Version : python 2.7
import os
# 判断一个unicode是否是汉字
def is_chinese(uchar):
if u'\u4e00' <= uchar<=u'\u9fff':
return True
else:
return False
# 判断一个unicode是否是数字
def is_number(uchar):
if u'\u0030' <= uchar and uchar<=u'\u0039':
return True
else:
return False
# 判断一个unicode是否是英文字母
def is_alphabet(uchar):
if (u'\u0041' <= uchar<=u'\u005a') or (u'\u0061' <= uchar<=u'\u007a'):
return True
else:
return False
# 判断是否非汉字,数字和英文字符 adapt to multi-characters
def is_other(uchar):
if len(uchar) > 1: return True
if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):
return False
else:
return True
if __name__=="__main__":
ustring=u'中国 a d111*'
# 判断是否有其他字符;
print is_other(u'*')
for item in ustring:
print item
if is_chinese(item):
print 'chinese'
elif is_alphabet(item):
print 'alphabet'
elif is_number(item):
print 'digital'
elif is_other(item):
print 'other'
|
"""
Tasks
-------
Search and transform jsonable structures, specifically to make it 'easy' to make tabular/csv output for other consumers.
Example
~~~~~~~~~~~~~
*give me a list of all the fields called 'id' in this stupid, gnarly
thing*
>>> Q('id',gnarly_data)
['id1','id2','id3']
Observations:
---------------------
1) 'simple data structures' exist and are common. They are tedious
to search.
2) The DOM is another nested / treeish structure, and jQuery selector is
a good tool for that.
3a) R, Numpy, Excel and other analysis tools want 'tabular' data. These
analyses are valuable and worth doing.
3b) Dot/Graphviz, NetworkX, and some other analyses *like* treeish/dicty
things, and those analyses are also worth doing!
3c) Some analyses are best done using 'one-off' and custom code in C, Python,
or another 'real' programming language.
4) Arbitrary transforms are tedious and error prone. SQL is one solution,
XSLT is another,
5) the XPATH/XML/XSLT family is.... not universally loved :) They are
very complete, and the completeness can make simple cases... gross.
6) For really complicated data structures, we can write one-off code. Getting
80% of the way is mostly okay. There will always have to be programmers
in the loop.
7) Re-inventing SQL is probably a failure mode. So is reinventing XPATH, XSLT
and the like. Be wary of mission creep! Re-use when possible (e.g., can
we put the thing into a DOM using
8) If the interface is good, people can improve performance later.
Simplifying
---------------
1) Assuming 'jsonable' structures
2) keys are strings or stringlike. Python allows any hashable to be a key.
for now, we pretend that doesn't happen.
3) assumes most dicts are 'well behaved'. DAG, no cycles!
4) assume that if people want really specialized transforms, they can do it
themselves.
"""
from collections import Counter, namedtuple
import csv
import itertools
from itertools import product
from operator import attrgetter as aget, itemgetter as iget
import operator
import sys
## note 'url' appears multiple places and not all extensions have same struct
ex1 = {
'name': 'Gregg',
'extensions': [
{'id':'hello',
'url':'url1'},
{'id':'gbye',
'url':'url2',
'more': dict(url='url3')},
]
}
## much longer example
ex2 = {u'metadata': {u'accessibilities': [{u'name': u'accessibility.tabfocus',
u'value': 7},
{u'name': u'accessibility.mouse_focuses_formcontrol', u'value': False},
{u'name': u'accessibility.browsewithcaret', u'value': False},
{u'name': u'accessibility.win32.force_disabled', u'value': False},
{u'name': u'accessibility.typeaheadfind.startlinksonly', u'value': False},
{u'name': u'accessibility.usebrailledisplay', u'value': u''},
{u'name': u'accessibility.typeaheadfind.timeout', u'value': 5000},
{u'name': u'accessibility.typeaheadfind.enabletimeout', u'value': True},
{u'name': u'accessibility.tabfocus_applies_to_xul', u'value': False},
{u'name': u'accessibility.typeaheadfind.flashBar', u'value': 1},
{u'name': u'accessibility.typeaheadfind.autostart', u'value': True},
{u'name': u'accessibility.blockautorefresh', u'value': False},
{u'name': u'accessibility.browsewithcaret_shortcut.enabled',
u'value': True},
{u'name': u'accessibility.typeaheadfind.enablesound', u'value': True},
{u'name': u'accessibility.typeaheadfind.prefillwithselection',
u'value': True},
{u'name': u'accessibility.typeaheadfind.soundURL', u'value': u'beep'},
{u'name': u'accessibility.typeaheadfind', u'value': False},
{u'name': u'accessibility.typeaheadfind.casesensitive', u'value': 0},
{u'name': u'accessibility.warn_on_browsewithcaret', u'value': True},
{u'name': u'accessibility.usetexttospeech', u'value': u''},
{u'name': u'accessibility.accesskeycausesactivation', u'value': True},
{u'name': u'accessibility.typeaheadfind.linksonly', u'value': False},
{u'name': u'isInstantiated', u'value': True}],
u'extensions': [{u'id': u'216ee7f7f4a5b8175374cd62150664efe2433a31',
u'isEnabled': True},
{u'id': u'1aa53d3b720800c43c4ced5740a6e82bb0b3813e', u'isEnabled': False},
{u'id': u'01ecfac5a7bd8c9e27b7c5499e71c2d285084b37', u'isEnabled': True},
{u'id': u'1c01f5b22371b70b312ace94785f7b0b87c3dfb2', u'isEnabled': True},
{u'id': u'fb723781a2385055f7d024788b75e959ad8ea8c3', u'isEnabled': True}],
u'fxVersion': u'9.0',
u'location': u'zh-CN',
u'operatingSystem': u'WINNT Windows NT 5.1',
u'surveyAnswers': u'',
u'task_guid': u'd69fbd15-2517-45b5-8a17-bb7354122a75',
u'tpVersion': u'1.2',
u'updateChannel': u'beta'},
u'survey_data': {
u'extensions': [{u'appDisabled': False,
u'id': u'testpilot?labs.mozilla.com',
u'isCompatible': True,
u'isEnabled': True,
u'isPlatformCompatible': True,
u'name': u'Test Pilot'},
{u'appDisabled': True,
u'id': u'dict?www.youdao.com',
u'isCompatible': False,
u'isEnabled': False,
u'isPlatformCompatible': True,
u'name': u'Youdao Word Capturer'},
{u'appDisabled': False,
u'id': u'jqs?sun.com',
u'isCompatible': True,
u'isEnabled': True,
u'isPlatformCompatible': True,
u'name': u'Java Quick Starter'},
{u'appDisabled': False,
u'id': u'?20a82645-c095-46ed-80e3-08825760534b?',
u'isCompatible': True,
u'isEnabled': True,
u'isPlatformCompatible': True,
u'name': u'Microsoft .NET Framework Assistant'},
{u'appDisabled': False,
u'id': u'?a0d7ccb3-214d-498b-b4aa-0e8fda9a7bf7?',
u'isCompatible': True,
u'isEnabled': True,
u'isPlatformCompatible': True,
u'name': u'WOT'}],
u'version_number': 1}}
def denorm(queries,iterable_of_things,default=None):
"""
'repeat', or 'stutter' to 'tableize' for downstream.
(I have no idea what a good word for this is!)
Think ``kronecker`` products, or:
``SELECT single,multiple FROM table;``
single multiple
------- ---------
id1 val1
id1 val2
Args:
queries: iterable of ``Q`` queries.
iterable_of_things: to be queried.
Returns:
list of 'stuttered' output, where if a query returns
a 'single', it gets repeated appropriately.
"""
def _denorm(queries,thing):
fields = []
results = []
for q in queries:
#print q
r = Ql(q,thing)
#print "-- result: ", r
if not r:
r = [default]
if type(r[0]) is type({}):
fields.append(sorted(r[0].keys())) # dicty answers
else:
fields.append([q]) # stringy answer
results.append(r)
#print results
#print fields
flist = list(flatten(*map(iter,fields)))
prod = itertools.product(*results)
for p in prod:
U = dict()
for (ii,thing) in enumerate(p):
#print ii,thing
if type(thing) is type({}):
U.update(thing)
else:
U[fields[ii][0]] = thing
yield U
return list(flatten(*[_denorm(queries,thing) for thing in iterable_of_things]))
def default_iget(fields,default=None,):
""" itemgetter with 'default' handling, that *always* returns lists
API CHANGES from ``operator.itemgetter``
Note: Sorry to break the iget api... (fields vs *fields)
Note: *always* returns a list... unlike itemgetter,
which can return tuples or 'singles'
"""
myiget = operator.itemgetter(*fields)
L = len(fields)
def f(thing):
try:
ans = list(myiget(thing))
if L < 2:
ans = [ans,]
return ans
except KeyError:
# slower!
return [thing.get(x,default) for x in fields]
f.__doc__ = "itemgetter with default %r for fields %r" %(default,fields)
f.__name__ = "default_itemgetter"
return f
def flatten(*stack):
"""
helper function for flattening iterables of generators in a
sensible way.
"""
stack = list(stack)
while stack:
try: x = stack[0].next()
except StopIteration:
stack.pop(0)
continue
if hasattr(x,'next') and callable(getattr(x,'next')):
stack.insert(0, x)
#if isinstance(x, (GeneratorType,listerator)):
else: yield x
def _Q(filter_, thing):
""" underlying machinery for Q function recursion """
T = type(thing)
if T is type({}):
for k,v in thing.iteritems():
#print k,v
if filter_ == k:
if type(v) is type([]):
yield iter(v)
else:
yield v
if type(v) in (type({}),type([])):
yield Q(filter_,v)
elif T is type([]):
for k in thing:
#print k
yield Q(filter_,k)
else:
# no recursion.
pass
def Q(filter_,thing):
"""
type(filter):
- list: a flattened list of all searches (one list)
- dict: dict with vals each of which is that search
Notes:
[1] 'parent thing', with space, will do a descendent
[2] this will come back 'flattened' jQuery style
[3] returns a generator. Use ``Ql`` if you want a list.
"""
if type(filter_) is type([]):
return flatten(*[_Q(x,thing) for x in filter_])
elif type(filter_) is type({}):
d = dict.fromkeys(filter_.keys())
#print d
for k in d:
#print flatten(Q(k,thing))
d[k] = Q(k,thing)
return d
else:
if " " in filter_: # i.e. "antecendent post"
parts = filter_.strip().split()
r = None
for p in parts:
r = Ql(p,thing)
thing = r
return r
else: # simple.
return flatten(_Q(filter_,thing))
def Ql(filter_,thing):
""" same as Q, but returns a list, not a generator """
res = Q(filter_,thing)
if type(filter_) is type({}):
for k in res:
res[k] = list(res[k])
return res
else:
return list(res)
def countit(fields,iter_of_iter,default=None):
"""
note: robust to fields not being in i_of_i, using ``default``
"""
C = Counter() # needs hashables
T = namedtuple("Thing",fields)
get = default_iget(*fields,default=default)
return Counter(
(T(*get(thing)) for thing in iter_of_iter)
)
## right now this works for one row...
def printout(queries,things,default=None, f=sys.stdout, **kwargs):
""" will print header and objects
**kwargs go to csv.DictWriter
help(csv.DictWriter) for more.
"""
results = denorm(queries,things,default=None)
fields = set(itertools.chain(*(x.keys() for x in results)))
W = csv.DictWriter(f=f,fieldnames=fields,**kwargs)
#print "---prod---"
#print list(prod)
W.writeheader()
for r in results:
W.writerow(r)
def test_run():
print "\n>>> print list(Q('url',ex1))"
print list(Q('url',ex1))
assert list(Q('url',ex1)) == ['url1','url2','url3']
assert Ql('url',ex1) == ['url1','url2','url3']
print "\n>>> print list(Q(['name','id'],ex1))"
print list(Q(['name','id'],ex1))
assert Ql(['name','id'],ex1) == ['Gregg','hello','gbye']
print "\n>>> print Ql('more url',ex1)"
print Ql('more url',ex1)
print "\n>>> list(Q('extensions',ex1))"
print list(Q('extensions',ex1))
print "\n>>> print Ql('extensions',ex1)"
print Ql('extensions',ex1)
print "\n>>> printout(['name','extensions'],[ex1,], extrasaction='ignore')"
printout(['name','extensions'],[ex1,], extrasaction='ignore')
print "\n\n"
from pprint import pprint as pp
print "-- note that the extension fields are also flattened! (and N/A) -- "
pp(denorm(['location','fxVersion','notthere','survey_data extensions'],[ex2,], default="N/A")[:2])
if __name__ == "__main__":
test_run()
|
class Light(object):
def __init__(self,Direction,GreenTime):
self.Direction = Direction #there are 2 light objects, one for the horizontal lanes and one for the vertical lanes
self.GreenTime = GreenTime
self.YellowTime = 6
self.RedTime=GreenTime+6
#def DetermineState(StartsGreen,(x+1)%((self.GreenTime+6)*2)): #to be defined/implemented. Determines current light based on starting cycle when cycle is advanced.
#if(StartsGreen):
#if((x+1)%((self.GreenTime+6)*2) <= self.GreenTime):
#print(Direction,"is green")
#elif((x+1)%((self.GreenTime+6)*2) <= self.GreenTime+self.YellowTime):
#print(Direction,"is yellow")
#else:
#print(Direction,"is red")
#else:
#if((x+1)%((self.GreenTime+6)*2) <= self.RedTime):
#print(Direction,"is red")
#elif((x+1)%((self.GreenTime+6)*2) <= self.RedTime+self.YellowTime):
#print(Direction,"is yellow")
#else:
#print(Direction,"is green")
class Instance(object):
def __init__(self, GreenTime, TotalCycles):#start a simulation by inputting the green light time and the total duration
self.GreenTime = GreenTime
self.TotalCycles = TotalCycles #The time duration gives us the number of cycles. Since no change can occur on a fraction of a cycle,
#the time duration must be an integer
#variables for outputting simulation stats when finished
self.AverageWaitTime=0
self.TotalWaitTime=0
self.TotalCars=0
self.LongestLaneLine=0
NS=Light("vertical",self.GreenTime)
EW=Light("horizontal",self.GreenTime)
print("green:",NS.GreenTime)
print("yellow:",NS.YellowTime)
print("red:",NS.RedTime)
#def Clock(z):
for x in range(self.TotalCycles):
print("Cycle:",x+1)
#if(StartsGreen):
if((x)%((self.GreenTime+6)*2) < NS.GreenTime):
print(NS.Direction,"is green")
elif((x)%((self.GreenTime+6)*2) < NS.GreenTime+NS.YellowTime):
print(NS.Direction,"is yellow")
else:
print(NS.Direction,"is red")
#else:
if((x)%((self.GreenTime+6)*2) < EW.RedTime):
print(EW.Direction,"is red")
elif((x)%((self.GreenTime+6)*2) < EW.RedTime+EW.YellowTime):
print(EW.Direction,"is green")
else:
print(EW.Direction,"is yellow")
#NS.DetermineState(True,(x+1)%((self.GreenTime+6)*2) )
#EW.DetermineState(False,(x+1)%((self.GreenTime+6)*2) )
#def AdvanceCycle():#to be defined/implemented, advances cycle and triggers the changes to the current state of the lights and lanes.
#def GetCurrentCycle(): #to be defined/implemented, getter for supplying current cycle to other functions
|
class Lane(object):
def __init__(self):
print("Lane created.")
self.carqueue=[]
'''def MoveCar(self,LightStatus):
#cars follow one set of rules with a green light
#starting at the head of the queue and moving towards the tail, for each
for x,item in reversed(list(enumerate(self.carqueue))): #iterate through the queue in descending order,
if self.carqueue[x][1] > 20:
self.carqueue[x][1]+=1
self.carqueue[x][0]+=1
if self.carqueue[x]==[25,26]:
self.carqueue.pop(0) #once a car's head and tail is clear of the intersection, pop it
elif ( self.PositionIsClear((self.carqueue[x][1]) ) ) and (self.carqueue[x][1] < 20):
self.carqueue[x][1]+=1
self.carqueue[x][0]+=1
elif self.PositionIsClear((self.carqueue[x][1]) ) and LightStatus=="green":
self.carqueue[x][1]+=1
self.carqueue[x][0]+=1
else:
pass
self.spawn()#at the end of the movement turn, roll the dice and see if a car spawns'''
def spawn(self):
if self.PositionIsClear(2) and self.PositionIsClear(1):
self.carqueue.append([1,2])
#print("PositionIsClear returned True for both squares")
#protip: to shift left all lines by one tab, highlight those lines and hit Shift+TabError
def __init__(self):
print("Lane created.")
self.carqueue=[]
def spawn(self):
if self.PositionIsClear(2) and self.PositionIsClear(1):
self.carqueue.append([1,2])
def PositionIsClear(self,location):
for x in self.carqueue:
for y in x:
if y==location:
#print("Position is not clear.")
return False
#print("All clear!")
return True
def MoveCar(self,LightStatus):
#cars follow one set of rules with a green light
#starting at the head of the queue and moving towards the tail, for each
for x,item in reversed(list(enumerate(self.carqueue))): #iterate through the queue in descending order
if self.carqueue[x][1] > 20: #once we're past the intersection line, we can keep going
self.carqueue[x][1]+=1 #...no matter what. The light will be yellow anyway.
self.carqueue[x][0]+=1
if self.carqueue[x][1] > 25:
self.carqueue.pop() #once a car's head is clear of the intersection, pop it
elif self.PositionIsClear((self.carqueue[x][1])+1) and self.carqueue[x][1] < 20:
self.carqueue[x][1]+=1
self.carqueue[x][0]+=1
elif (LightStatus == "green"):
self.carqueue[x][1]+=1
self.carqueue[x][0]+=1
else:#if the space in front is occupied, we cannot move the car
pass#so we do nothing and move on to the car behind it
print("Car:",x)
self.spawn()
print("Cars in lane:",self.carqueue)
'''Use the same formula Light uses for determining light status to determine what light status to use
when calling MoveCar. MoveCar determines movement by light status, Iterate determines movement by green time and where we are
in the cycle, given whether or not a light starts off green.'''
def Iterate(self,x,starts_green,green_time):
if(starts_green):
if((x)%((green_time+6)*2) < green_time):
self.MoveCar("green")
elif((x)%((green_time+6)*2) < green_time+6):
self.MoveCar("yellow")
else:
self.MoveCar("red")
else:
if((x)%((green_time+6)*2) < green_time+6):
self.MoveCar("red")
elif((x)%((self.GreenTime+6)*2) < green_time+12):
self.MoveCar("green")
else:
self.MoveCar("yellow")
class Light(object):
def __init__(self,Direction,GreenTime,StartsGreen):
self.Direction = Direction #there are 2 light objects, one for the horizontal lanes and one for the vertical lanes
self.GreenTime = GreenTime
self.YellowTime = 6
self.RedTime=GreenTime+6
self.StartsGreen=StartsGreen
self.Top=Lane()
self.Bottom=Lane()
def DetermineState(self,x): #to be defined/implemented. Determines current light based on starting cycle when cycle is advanced.
if(self.StartsGreen):
if((x)%((self.GreenTime+6)*2) < self.GreenTime):
print(self.Direction,"is green")
self.Top.Iterate(x,self.StartsGreen,self.GreenTime)
self.Bottom.Iterate(x,self.StartsGreen,self.GreenTime)
elif((x)%((self.GreenTime+6)*2) < self.GreenTime+self.YellowTime):
print(self.Direction,"is yellow")
self.Top.Iterate(x,self.StartsGreen,self.GreenTime)
self.Bottom.Iterate(x,self.StartsGreen,self.GreenTime)
else:
print(self.Direction,"is red")
self.Top.Iterate(x,self.StartsGreen,self.GreenTime)
self.Bottom.Iterate(x,self.StartsGreen,self.GreenTime)
else:
if((x)%((self.GreenTime+6)*2) < self.RedTime):
print(self.Direction,"is red")
self.Top.Iterate(x,self.StartsGreen,self.GreenTime)
self.Bottom.Iterate(x,self.StartsGreen,self.GreenTime)
elif((x)%((self.GreenTime+6)*2) < self.RedTime+self.YellowTime):
print(self.Direction,"is green")
self.Top.Iterate(x,self.StartsGreen,self.GreenTime)
self.Bottom.Iterate(x,self.StartsGreen,self.GreenTime)
else:
print(EW.Direction,"is yellow")
self.Top.Iterate(x,self.StartsGreen,self.GreenTime)
self.Bottom.Iterate(x,self.StartsGreen,self.GreenTime)
class Instance(object):
def __init__(self, GreenTime, TotalCycles):#start a simulation by inputting the green light time and the total duration
self.GreenTime = GreenTime
self.TotalCycles = TotalCycles #The time duration gives us the number of cycles. Since no change can occur on a fraction of a cycle,
#the time duration must be an integer
#variables for outputting simulation stats when finished
self.AverageWaitTime=0
self.TotalWaitTime=0
self.TotalCars=0
self.LongestLaneLine=0
NS=Light("vertical",self.GreenTime,True)
EW=Light("horizontal",self.GreenTime,False)
print("green:",NS.GreenTime)
print("yellow:",NS.YellowTime)
print("red:",NS.RedTime)
#def Clock(z):
for x in range(self.TotalCycles):
print("Cycle:",x+1)
NS.DetermineState(x)
EW.DetermineState(x)
print("Cars in north lane after", self.TotalCycles,"cycles:",len(NS.Top.carqueue))
print("Cars in south lane after", self.TotalCycles,"cycles:",len(NS.Bottom.carqueue))
print("Cars in east lane after", self.TotalCycles,"cycles:",len(EW.Top.carqueue))
print("Cars in west lane after", self.TotalCycles,"cycles:",len(EW.Bottom.carqueue))
#def AdvanceCycle():#to be defined/implemented, advances cycle and triggers the changes to the current state of the lights and lanes.
#def GetCurrentCycle(): #to be defined/implemented, getter for supplying current cycle to other functions
def main():
Highway=Instance(6,10)
main()
|
# def permutations(items):
# n = len(items)
# if n == 0:
# yield []
# else:
# for i in range(len(items)):
# for cc in permutations(items[:i] + items[i + 1:]):
# yield [items[i]] + cc
# for p in permutations(['r', 'e', 'd']):
# print(''.join(p))
# for p in permutations(list("game")):
# print(''.join(p) + ", ", end="")
# print()
# import itertools
# perms = itertools.permutations(['r','e','d'])
# print(type(perms))
# print(list(perms))
def k_permutations(items, n):
if n == 0:
yield []
else:
for i in range(len(items)):
for ss in k_permutations(items, n - 1):
if items[i] not in ss:
yield [items[i]] + ss
for p in k_permutations(['r', 'e', 'd', 's'], 3):
print(''.join(p))
|
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 3000))
while True:
# print ('waiting for a connection')
# Receive the client packet along with the address it is coming from
message, address = serverSocket.recvfrom(1024)
# show who connected to us
# print ('connection from', address)
# print ("Message: %s" % message)
print (message)
# Capitalize the message from the client
# # If rand is less is than 4, we consider the packet lost and do notrespond
# if rand < 4:
# continue
# Otherwise, the server responds
# serverSocket.sendto(message, address)
|
def bsearch(data,target):
if data!=[]:
top =0
bot=len(data)-1
while(top <=bot):
mid = ( top + bot )/2
if (data[mid]==target):
return mid
elif (data[mid]<target):
top=mid+1
bsearch (data,target )
elif (data[mid]>target):
bot=mid-1
bsearch (data,target)
if ( bot<top ):
return None
elif ( top <=bot):
return target[index]
|
'''
11650 좌표 정렬하기
알고리즘 :
1. x, y를 하나의 리스트에 담고, 여러개의 x,y들을 coord라는 리스트에 담아서 sort() 함수 사용해 정렬
'''
N =int(input())
coord = []
for i in range(N):
a = list(map(int, input().split()))
coord.append(a)
coord.sort()
for i in range(len(coord)):
print(coord[i][0], coord[i][1])
|
'''
6549 히스토그램에서 가장 큰 직사각형
알고리즘:
(아직도 이해 잘 안간다. 나중에 다시 할 것)
1. 모든 직사각형의 높이들을 탐색
2. 스택에 자기의 높이보다 큰 높이가 없으면 stack 에 push
3. 스택의 top이 나보다 높거나 같으면, 그 높이 pop해서 최대 넓이 계산
4. 남은 것들을 pop해서 넓이 비교
'''
import sys
def maxArea():
max_area = 0
stack = []
for i in range(N):
index = i
while stack and stack[-1][0] >= h[i]:
height, index = stack.pop() # 현재 나의 높이가 stack top의 높이보다 작거나 같은 경우 pop
tmp_area = height * (i-index) # i-index로 가로 계산
max_area = max(max_area, tmp_area)
# 맨 처음 막대인 경우 or
# stack top의 높이보다 현재 나의 높이가 더 높은 경우 push
stack.append([h[i], index])
# 직사각형을 모두 탐색했으면, stack에 남은 것들은 pop해서 넓이 비교
for height, index in stack:
max_area = max(max_area, height*(N-index))
return max_area
while True:
h = list(map(int, sys.stdin.readline().split()))
if h[0] == 0:
break
N = h[0]
h = h[1:]
print(maxArea())
|
'''
15651 N과 M(3)
알고리즘 :
1. N개 중에 중복을 허용해서 M개를 순서를 고려해서 뽑는 중복순열의 알고리즘을 이용
2. itertools의 product를 이용
'''
from itertools import product
N, M = map(int, input().split())
num_list = []
for i in range(N):
num_list.append(i+1)
a = list(product(num_list, repeat = M))
for i in range(len(a)):
for j in range(M):
print(a[i][j], end = ' ')
print()
|
'''
1541 잃어버린 괄호
알고리즘:
1. 입력을 '-'를 기준으로 list에 넣어준다.
2. 각 리스트를 숫자로 바꾼다. 이때 +가 있으면, 숫자로 바꾸고 더한 결과값으로 저장
3. 최소로 만들기 위해서는 최종 list에 남은 숫자들끼리 빼면된다.
'''
s = input().split('-')
num_list =[]
for x in s:
total = 0
if '+' in x:
temp = x.split('+')
for num in temp:
total += int(num)
num_list.append(total)
else:
num_list.append(int(x))
sumvalue = num_list[0]
for i in range(1, len(num_list)):
sumvalue -= num_list[i]
print(sumvalue)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.