text
stringlengths 37
1.41M
|
---|
'''
Faça um programa que calcule e mostre a área
de um quadrado. Sabe-se que: A = lado * lado.
'''
lado = float(input('Digite o tamanho do lado'))
A = lado * lado
print('A área do quadrado é: ')
print(A)
|
''' Q2
Crie um programa que preencha uma matriz 2x4 com
números inteiros, calcule e mostre:
■ a quantidade de elementos entre 12 e 20 em cada linha;
■ a média dos elementos pares da matriz.
matriz = []
for i in range(2):
linha = []
for j in range(4):
linha.append(int(input('Inserir: ')))
print(linha)
matriz.append(linha)
print(matriz)
'''
matriz = [[7, 4, 14, 1], [12, 13, 16, 4]]
cont = 0
soma_pares = 0
contp = 0
for i in range(2):
for j in range(4):
if(matriz[i][j]>12 and matriz[i][j]<20):
cont +=1 #contando elementos entre 12 e 20
if(matriz[i][j]%2==0):
soma_pares = soma_pares + matriz[i][j]
contp += 1
print('Na linha ',i,'tem', cont, 'elementos entre 12 e 20')
cont = 0 #zerando o cont
media_pares = soma_pares/contp
print('A média dos elementos pares da matriz:', media_pares)
|
# Өгөгдсөн тоо эерег тэгш тоо бол true үгүй бол false гэж хэвлэ.
def EeregTegshToo(n):
if n>0 and n%2==0:
return True
else: return False
n = int(input())
print(EeregTegshToo(n)) |
"""Hasan Qadri, 903138378, [email protected], I worked on this assignment alone,
using only this semester's course materials.
for seconds in timer(60)
"""
"""
def avoidWalls():
for x in range(timer(60)):
while getIR() != 1 or getObstacle('center') == 0:
forward(3,3)
if getIR() == 1 or getObstacle('center') != 0:
turnRight(1,100)
celebration()
and getObstacle("left") == 0 and getObstacle("right") == 0:
"""
from Myro import *
init()
def celebration():
beep(1, 800)
beep(1,900)
beep(3, 1000)
beep(5, 500)
beep(2, 200)
beep(4, 500)
beep(4, 2000)
turn(4, 90)
def avoidWalls():
for time in timer(60):
while getIR("left") == 1 and getIR("right") == 1:
backward(8, 1)
forward(1,2)
turnRight(1,1)
celebration()
"""
getObstacle("left") == 0 and getObstacle("right") == 0:
forward(1,1)
elif getIR() == 1:
backward(5,1)
turnRight(5, 1)
elif getObstacle() != 0:
turnRight(5,3)
"""
avoidWalls()
|
def DFS_help(graph, v, visited):
visited[v] = True
successors = graph.get_successors(v)
for i in successors:
if not visited[i]:
DFS_help(graph, i, visited)
def connected(graph):
n = graph.get_order()
visited = [False] * n
for i in range(n):
if len(graph.get_successors(i)) > 1:
break
if i == n - 1:
return True
DFS_help(graph, i, visited)
for i in range(n):
if not visited[i] and len(graph.get_successors(i)) > 0:
return False
return True
def euler_circuit(graph):
if not connected(graph):
return False
else:
for i in range(graph.get_order()):
if len(graph.get_successors(i)) % 2 != 0:
return False
return True
|
import requests
#This code uses Datamuse API
def get_concepts_from_item(source):
"""
use Datamuse API to get related words for given word
:param source: a word which related words are generated from
:return: list of related words
"""
source = source.lower()
myList = []
obj = requests.get('https://api.datamuse.com/words?ml='+source.replace(" ", "+")).json()
for data in obj:
if "score" in data.keys() and "word" in data.keys():
myList.append((data['word'], data['score']))
if len(myList)>9:
break
return myList
def get_concepts_from_list(source):
"""
use Datamuse API to get related words for given list of words
:param source: list of words that contains words which related words are generated from
:return: list of related words
"""
myList = []
for entry in source:
entry = entry.lower()
obj = requests.get('https://api.datamuse.com/words?ml='+entry.replace(" ", "+")).json()
for data in obj:
print data
if "score" in data.keys() and "word" in data.keys():
if data['word'] in [x[0] for x in myList]:
index = [x[0] for x in myList].index(data['word'])
myList[index] = (myList[index][0], myList[index][1]+data['score'])
else:
myList.append((data['word'], data['score']))
myList.sort(key=lambda tup: tup[1], reverse=True);
myList = myList[:10]
return myList
"""
#Code that uses ConceptNet API
def get_concepts_from_item(source):
source = source.lower();
print source;
myList = [];
obj = requests.get('http://api.conceptnet.io/c/en/'+source.replace(" ", "_")).json();
for edge in obj['edges']:
weight = edge['weight'];
if source not in edge['start']['label'].lower() and edge['start']['language'] == "en":
word = edge['start']['label'].lower();
myList.append((word, weight));
elif source not in edge['end']['label'].lower() and edge['end']['language'] == "en":
word = edge['end']['label'].lower();
myList.append((word, weight));
if len(myList)>9 and myList[len(myList)-1][1] < 4:
break;
return myList;
def get_concepts_from_list(source):
myList = [];
for entry in source:
entry = entry.lower();
print entry
obj = requests.get('http://api.conceptnet.io/c/en/'+entry.replace(" ", "_")).json();
for edge in obj['edges']:
weight = edge['weight'];
if entry not in edge['start']['label'].lower() and edge['start']['language'] == "en":
word = edge['start']['label'].lower();
if word in [x[0] for x in myList]:
index = [x[0] for x in myList].index(word)
myList[index] = (myList[index][0], myList[index][1]+weight);
else:
myList.append((word, weight));
elif entry not in edge['end']['label'].lower() and edge['start']['language'] == "en":
word = edge['end']['label'].lower();
if word in [x[0] for x in myList]:
index = [x[0] for x in myList].index(word)
myList[index] = (myList[index][0], myList[index][1] + weight);
else:
myList.append((word, weight));
myList.sort(key=lambda tup: tup[1], reverse=True);
for i in range(10,len(myList)):
if myList[i][1] <4 :
myList = myList[:i]
break;
return myList;
"""
"""
#Testing Area
word1 = "metropolis"
word2 = "Urban Center"
print word1, word2
#test = get_concepts_from_item(word1);
test = get_concepts_from_list([word1, word2]);
print len(test)
for p in test:
print p
"""
|
words = {}
text = {"This is a collection"}
print(text)
check_for_word = text.split()
for word in check_for_word:
frequency = words.get(word, 0)
words[word] = frequency + 1 |
#Example 1
result = 0
basket_items = {'pears': 5, 'grapes': 19, 'kites': 3, 'sandwiches': 8, 'bananas': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
# Your previous solution here
for key, value in basket_items.items():
for fruit in fruits:
if key == fruit:
result += value
print(result)
#Example 2
result = 0
basket_items = {'peaches': 5, 'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
# Your previous solution here
for key, value in basket_items.items():
for fruit in fruits:
if key == fruit:
result += value
print(result)
#Example 3
result = 0
basket_items = {'lettuce': 2, 'kites': 3, 'sandwiches': 8, 'pears': 4, 'bears': 10}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
# Your previous solution here
for key, value in basket_items.items():
for fruit in fruits:
if key == fruit:
result += value
print(result)
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 19:53:55 2018
@author: Marina
"""
# Browse the complete list of string methods at:
# https://docs.python.org/3/library/stdtypes.html#string-methods
# and try them out here
name="Marina Lenza"
print(name.capitalize())
print(name.isalnum())
print(name.isspace())
print(name.lower())
print(name.upper()) |
multiples_3 = [x*3 for x in range(1,21)]
print(multiples_3) |
""""
This script is serverd as a practise of Algorithm and data structure learning in Python
"""
# def FindSecondMini(input_list):
# if not isinstance(input_list, list):
# raise ValueError("input must be list type!")
# if len(input_list)==0:
# return None
# if len(input_list)==1:
# return input_list[0]
# minimum = float('inf')
# sec_minimum = minimum
# for i in input_list:
# if i<minimum:
# sec_minimum = minimum
# minimum = i
# elif i<sec_minimum:
# sec_minimum = i
# return sec_minimum
#
# def MaxSubArray(input_list):
# if not isinstance(input_list, list):
# raise ValueError("input must be list type!")
# if len(input_list)==0:
# return None
# if len(input_list)==1:
# return input_list[0]
# maximum = 0
# max_scan = 0
# for i in input_list:
# max_scan = max_scan + i
# if max_scan < 0:
# max_scan = 0
# if max_scan > maximum:
# maximum = max_scan
# return maximum
#
#
# def InsertionSort(input_list):
# if not isinstance(input_list, list):
# raise ValueError("Input must be list type!")
#
# if len(input_list) <=1:
# return input_list
#
# for i in range(1,len(input_list)):
# j = i-1
# temp = input_list[i]
# while(temp < input_list[j] and j>=0):
# input_list[j+1] = input_list[j]
# j -= 1
# input_list[j+1] = temp
# return input_list
#
#
# def MergeSort(input_list):
# def mergeHelper(li, p, q):
# if p<q:
# r = (p+q)//2
# mergeHelper(li, p, r)
# mergeHelper(li, r+1, q)
# Merge(li, p, q, r)
#
# def Merge(li, p, q, r):
# n1 = r-p+1
# n2 = q-r
# left_list = [0]*n1
# right_list = [0]*n2
# for i in range(n1):
# left_list[i] = li[p+i-1]
# for j in range(n2):
# right_list[j] = li[r+j]
# i,j = 0,0
# k=p
# while i<n1 and j<n2:
# if left_list[i]<right_list[j]:
# li[k-1] =left_list[i]
# i+=1
# else:
# li[k - 1] = right_list[j]
# j += 1
# k += 1
# if i==n1:
# li[k-1:q]=right_list[j:]
# else:
# li[k-1:q]=left_list[i:]
#
#
# mergeHelper(input_list, 1, len(input_list))
# return input_list
#
# def HeapSort(input_list):
# return MaxHeap(input_list).heapSort()
#
# class MaxHeap(object):
# def __init__(self, values):
# self.list = list(values)
# self.length = len(values)
#
# def _getParentIndex(self, index):
# return (index + 1) // 2 -1
#
# def _getLeftChildIndex(self, index):
# return (index + 1) * 2 - 1
#
# def _getRightChildIndex(self, index):
# return (index + 1)* 2
#
# def heapify(self, index):
# largest = index
# l = self._getLeftChildIndex(index)
# r = self._getRightChildIndex(index)
# if l < self.heapSize and self.list[l] > self.list[largest]:
# largest = l
# if r < self.heapSize and self.list[r] > self.list[largest]:
# largest = r
# if largest != index:
# temp = self.list[largest]
# self.list[largest] = self.list[index]
# self.list[index] = temp
# self.heapify(largest)
#
# def _buildInitialHeap(self):
# self.heapSize = self.length
# for i in reversed(range(self.length//2)):
# self.heapify(i)
#
# def heapSort(self):
# self._buildInitialHeap()
# for i in reversed(range(self.length)):
# temp = self.list[0]
# self.list[0] = self.list[i]
# self.list[i] = temp
# self.heapSize -= 1
# self.heapify(0)
# return list(self.list)
#
#
# def QuickSort(input_list):
# if not isinstance(input_list, list):
# raise ValueError("Input must be list type!")
#
# if len(input_list) <=1:
# return input_list
#
# def partition(input_list, p, r):
# x = input_list[r]
# i = p-1
# for j in range(p, r):
# if input_list[j] <= x:
# i += 1
# temp = input_list[j]
# input_list[j] = input_list[i]
# input_list[i] = temp
# input_list[r] = input_list[i+1]
# input_list[i+1] = x
# return i + 1
#
# def QuickSortHelper(input_list, p, r):
# if p<r:
# q = partition(input_list, p, r)
# QuickSortHelper(input_list, p, q-1)
# QuickSortHelper(input_list, q, r)
#
# QuickSortHelper(input_list, 0, len(input_list)-1)
#
# return input_list
#
# def FindMedian(input_list):
# def partition(input_list, p, r):
# pivot = input_list[p-1]
# i = p
# for j in range(p, r):
# if input_list[j] <= pivot:
# input_list[j], input_list[i] = input_list[i], input_list[j]
# i += 1
# input_list[i-1] , input_list[p-1] = input_list[p-1] , input_list[i-1]
# return i
#
# if not input_list:
# return None
# elif len(input_list) == 1:
# return input_list[0]
#
# def FindMedianHelper(input_list, p, r, k):
# if p==r:
# return input_list[p-1]
# q = partition(input_list, p, r)
# q_relative = q-p+1
# if q_relative == k:
# return input_list[q-1]
# elif q_relative>k:
# return FindMedianHelper(input_list, p, q-1, k)
# elif q_relative<k:
# return FindMedianHelper(input_list, q+1, r, k-q_relative)
#
#
# ind = len(input_list) // 2
# return FindMedianHelper(input_list, 1, len(input_list), ind+1)
#
#
#
# def log2nRecursion(n):
# return 1 + log2nRecursion(n//2) if n>1 else 0
#
# def log2Iteration(n):
# log = 0
# while n > 1:
# n //= 2
# log += 1
# return log
#
# print(log2nRecursion(3), log2Iteration(3))
# print(log2nRecursion(7), log2Iteration(7))
# print(log2nRecursion(8), log2Iteration(8))
# print(log2nRecursion(64), log2Iteration(64))
# print(log2nRecursion(65), log2Iteration(65))
#
#
# def printInorder(root):
# if root:
# printInorder(root.left)
# print(root.val)
# printInorder(root.right)
#
#
# def tribonacci(n):
# if (n == 0):
# return 0
# elif (n == 1 or n == 2):
# return 1
# return tribonacci(n-2) + tribonacci(n-1) + tribonacci(n-3)
#
#
# mem_list = [0] * 38
# def tribonacciWithMem(n):
# if (n == 0):
# mem_list[0] = 0
# return 0
# elif (n == 1 or n == 2):
# mem_list[n] = 1
# return 1
# else:
# if mem_list[n] != 0:
# return mem_list[n]
# else:
# mem_list[n] = tribonacciWithMem(n-2) + tribonacciWithMem(n-1) + tribonacciWithMem(n-3)
# return mem_list[n]
#
# print(tribonacciWithMem(25))
#
# def tribonacciIteration(n):
# if (n == 0):
# return 0
# elif (n == 1 or n == 2):
# return 1
# else:
# T3 = 0
# T2 = T1 = 1
# for i in range(3,n+1):
# tribonacci = T1 + T2 + T3
# T3 = T2
# T2 = T1
# T1 = tribonacci
#
# return tribonacci
# print(tribonacciIteration(25))
#
#
# def minmaxGasDist(stations, K):
# left, right = 0, stations[-1] - stations[0]
# while (left + 10e-6 < right):
# mid = (left + right) / 2
# count = 0
#
# for i in range(len(stations) - 1):
# count += (stations[i + 1] - stations[i]) // mid
#
# if count > K:
# left = mid
# else:
# right = mid
#
# return right
#
#
# st = [5, 8, 10, 25, 28, 31, 72, 80, 85, 100]
# K = 8
# print(minmaxGasDist(st, K))
#
#
# class solution:
# def gas_dis(self, lis, m):
# dist = [lis[i] - lis[i - 1] for i in range(1, len(lis))]
# if lis[0] > 0:
# dist.append(lis[0])
# if lis[-1] < m:
# dist.append(m - lis[-1])
# dist.sort()
# return dist
#
# def minmaxGasDist(self, dist, t):
# lo = 0
# hi = st[-1]
# while lo < hi:
# mi = lo + (hi - lo) // 2
# # print(lo, mi, hi)
# cnt = 0
# for i in range(len(dist)):
# if dist[i] > mi:
# cnt += dist[i] // mi + (dist[i] % mi > 0) - 1
# if cnt <= t:
# hi = mi
# else:
# lo = mi + 1
# return lo
#
# # test:
# st= [5, 8, 10, 25, 28, 31, 72, 80, 85, 100]
# m = 125
# t = 8
# solution = solution()
# dist = solution.gas_dis(st, m)
# print("dist:", dist)
# print("minmaxGasDist:", solution.minmaxGasDist(dist, t))
#
# class Node:
# def __init__(self, val):
# self.val = val
# self.prev = None
# self.next = None
# def printNode(self):
# root = self
# while (root):
# print(root.val)
# root = root.next
#
# def recursiveSort(root: Node) -> Node:
# if not root or (not root.prev and not root.next):
# return root
# next = root.next
# root.next = root.prev
# root.prev = next
# if not root.prev:
# return root
# return recursiveSort(root.prev)
# root1 = Node(1)
# root2 = Node(2)
# root3 = Node(3)
# root4 = Node(4)
# root5 = Node(5)
# root1.next = root2
# root2.prev = root1
# root2.next = root3
# root3.prev = root2
# root3.next = root4
# root4.prev = root3
# root4.next = root5
# root5.prev = root4
# a = recursiveSort(root1)
# a.printNode()
class Solution:
def readBinaryWatch(self, num: int):
avaliableLight = [i for i in range(11)]
result = []
eachCombination = []
self.getNFromAll(avaliableLight, eachCombination, 1, result)
return self.convertCombinationToTime([len(i) == num for i in result])
def getNFromAll(self, input, eachCombination, next: int, result):
result.append(eachCombination.copy())
for i in range(next, len(input) + 1):
eachCombination.append(input[i - 1])
self.getNFromAll(input, eachCombination, next + 1, result)
eachCombination.pop()
return
def convertCombinationToTime(result):
hours = [1, 2, 4, 8]
mins = [1, 2, 4, 8, 16, 32]
hour = 0
minute = 0
str_result = []
for combination in result:
for num in combination:
if (num < 5):
hour += hours[num]
else:
minute += mins[num]
if (hour > 11 or minute > 59):
continue
minute = str(minute) if minute > 9 else '0' + str(minute)
str_result.append(str(hour)+ ':' + minute)
return str_result
solution = Solution()
solution.readBinaryWatch(4)
# implement a queue from a stack
class queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, val):
self.stack1.append(val)
def dequeue(self):
if not self.stack1 and not self.stack2:
print('Queue is empty')
return
if (not self.stack2):
while (self.stack1):
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
q = queue()
for i in range(5):
q.enqueue(i)
for i in range(5):
print(q.dequeue())
|
"""Generates data in the form of a dictionary with x and y.
shape of x as (200,2), 2 numbers based on make_moons from sklearn
shape of y as (200,2) multiclass labels for x"""
import numpy as np
from time import time
np.random.seed(int(time())) # is this for make_moons?
import sklearn.datasets as datasets
x,y = datasets.make_moons(200,noise=0.20)
actY = np.zeros([200,2])
actY[range(200),y]=1
dataset = {"x":x,"y":actY}
import pickle
pickle.dump(dataset,open("data.txt","wb"))
|
#! /usr/bin/env python3
from __future__ import annotations
from abc import ABC, abstractmethod
class Creator(ABC):
"""
The creator class declares the factory method
"""
@abstractmethod
def factory_method(self):
"""
Note that the Creator may also provide some default
implementation of the factory method
"""
pass
def some_operation(self) -> str:
"""
Also note that, despite its name, the Creator's primary responsibility
is not creating products. Usually, it contains some core business logic
that relies on Product objects, returned by the factory method.
Subclasses can indirectly change that business logic by overriding the
factory method and returning a different type of product from it.
"""
# Call the factory method to create a Product object.
product = self.factory_method()
# Now , use the product
result = f"Creator: The same creator's code has just worked with {product.operation()}"
return result
class ConcreteCreator1(Creator):
"""
Note that
"""
def factory_method(self) -> Product:
return ConcreteProduct1()
class ConcreteCreator2(Creator):
def factory_method(self) -> Product:
return ConcreteProduct2()
class Product(ABC):
"""
The Product interface
"""
@abstractmethod
def operation(self) -> str:
pass
class ConcreteProduct1(Product):
def operation(self) -> str:
return "{Result of the ConcreteProduct1}"
class ConcreteProduct2(Product):
def operation(self) -> str:
return "{Result of the ConcreteProduct2}"
def client_code(creator: Creator) -> None:
"""
The client code
"""
print(f"Client: I'm no aware of the creator's class, but it still works.\n"
f"{creator.some_operation()}", end="")
if __name__ == "__main__":
print("App: Launched with the ConcreteCreator1.")
client_code(ConcreteCreator1())
print("\n")
print("App: Launched with the ConcreteCreator2.")
client_code(ConcreteCreator2())
|
from player import Player
from mechanics import Move, Result
# Has equal chance of choosing split/steal
class RandomPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
return self.random_action()
# Always split
class NicePlayer(Player):
def __init__(self):
super().__init__()
def action(self):
return self.split()
# Always steal
class GreedyPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
return self.steal()
# Alternate between split and steal
# Initial choice is random
class FicklePlayer(Player):
def __init__(self):
super().__init__()
def action(self):
if self.round == 1:
return self.random_action()
else:
if self.previous_actions[-1] == Move.SPLIT:
return self.steal()
else:
return self.split()
# Always split, but once opponent steals, always steal
class GrudgePlayer(Player):
def __init__(self):
super().__init__()
def action(self):
if Result.SPLIT_LOST in self.previous_results:
return self.steal()
else:
return self.split()
# Copy the previous move made by the opponent
# Initial choice is split
class CopycatPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
if self.round == 1:
return self.split()
else:
return self.opponent.previous_actions[-1]
# Split when winning, steal when losing
class SoreLoserPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
if self.money >= self.opponent.money:
return self.split()
else:
return self.steal()
# If opponent stole in the previous 2 rounds, steal
# Otherwise, always split
class CautiousPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
if Move.STEAL in self.opponent.previous_actions[-2:]:
return self.steal()
else:
return self.split()
# Always split, until the opponent steals twice
# Then becomes a CopycatPlayer
class CopykittenPlayer(Player):
def __init__(self):
super().__init__()
self.limit = 2
def action(self):
if self.round == 1:
return self.split()
if self.opponent.previous_actions[-1] == Move.STEAL:
self.limit -= 1
if self.limit <= 0:
return self.opponent.previous_actions[-1]
else:
return self.split()
# Starts with split, steal, split, split
# If opponent retaliates with steal, plays like a CopycatPlayer
# Otherwise, always steal
class StrategicPlayer(Player):
def __init__(self):
super().__init__()
def action(self):
if self.round == 1 or self.round == 3 or self.round == 4:
return self.split()
elif self.round == 2:
return self.steal()
elif Move.STEAL in self.opponent.previous_actions:
return self.opponent.previous_actions[-1]
else:
return self.steal() |
from enum import Enum
class Move(Enum):
ROCK = 1
PAPER = 2
SCISSORS = 3
class Strategy(Enum):
STEP0 = 0
STEP1 = 1
STEP2 = -1
class Result(Enum):
WIN = 1
TIE = 0
LOSE = -1
# ROCK beats SCISSORS; PAPER beats ROCK; SCISSORS beat PAPER
MATCHUP = {1: 3, 2: 1, 3: 2}
# Return 1 if move1 wins, 0, if tie, -1 if move2 wins
def compare(move1, move2):
if move1 == move2:
return 0
elif MATCHUP[move1.value] == move2.value:
return 1
else:
return -1 |
#https://projecteuler.net/problem=3
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
import math
def listprimes(num):
primes = []
for posnum in range(3, int(math.sqrt(num)), 2):
print('checking', posnum)
if num % posnum == 0:
add = True
for prime in primes:
if posnum % prime == 0:
add = False
if add:
primes.append(posnum)
return primes
print(listprimes(600851475143)[-1])
|
"""Solution to problem 22 on Project Euler"""
# https://projecteuler.net/problem=22
# Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names,
# begin by sorting it into alphabetical order. Then working out the alphabetical value for each name,
# multiply this value by its alphabetical position in the list to obtain a name score.
# For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53,
# is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
# What is the total of all the name scores in the file?
import re
ALPHA = "abcdefghijklmnopqrstuvwxyz"
name_regex = re.compile(r'''(
(")
(\w+)
(")
)''', re.VERBOSE | re.IGNORECASE)
def score_name(name):
"""returns the lexiographic score of a word"""
total = 0
for letter in name:
letter = letter.lower()
total += ALPHA.find(letter) + 1
return total
def get_names(file_name):
"""Given a file name, return a list of all names"""
names = []
try:
file = open(file_name)
lines = file.readlines()
text = "".join(lines)
matches = name_regex.findall(text)
for match in matches:
names.append(match[2])
except:
print('error with file')
finally:
return names
def get_total_score(sorted_names):
total = 0
for name in enumerate(sorted_names):
total += (name[0] + 1) * score_name(name[1])
return total
FILE_NAME = r"problem022_names.txt"
names = get_names(FILE_NAME)
names.sort()
print(get_total_score(names)) |
def ordenador():
x=input("dime un numero")
cifras=0
while x>0:
x=x/10
cifras=cifras+1
print cifras
ordenador()
|
def sumador_acumulador():
n=input("Dime hasta que numero quieres sumar")
suma=0
for cont in range (1,n+1,1):
suma=suma+cont
print"suma=",suma
sumador_acumulador()
|
import pandas
## @package CSV
# Documentation for the module CSV
#
# More details.
# Documentation for the CSV Class
#
# More details.
class CSV:
## Variable of the csv's route.
_route = "../Others/"
## The constructor.
# @param self The object pointer.
# @param name The CSV name to be load.
def __init__(self, name = "CSV"):
try:
self._csv = pandas.read_csv(self._route+name)
self._name = name
except :
assert("CSV not found.")
## Method that shows the CSV.
# @param self The object pointer.
def show(self):
print(self._csv)
## Method that shows the csv.
# @param route The route where is the csv.
def set_route(self, route):
self._route = route
cantidad_csv = 3
lista_csv = []
for i in range(cantidad_csv):
nombre = "csv{}.csv".format(i+1)
csv = CSV(nombre)
lista_csv.append(csv)
for csv in lista_csv:
csv.show()
print("-"*50) |
import cv2
print ("whats with that smile")
train_face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
smile_detector = cv2.CascadeClassifier("haarcascade_smile.xml")
#grab video cam feed
webcam = cv2.VideoCapture(0)
#show current webcam frame
while True:
succesful_webcam_read,frame = webcam.read()
grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#detect faces and smile
detecting_faces = train_face_detector.detectMultiScale(grayscaled_frame)
#detecting_smile = smile_detector.detectMultiScale(grayscaled_frame,scaleFactor=1.75,minNeighbors=20)
for (x, y, w, h) in detecting_faces:
#drawing rectangle around faces
cv2.rectangle(frame, (x, y), (x + w, x + h), (0 ,0,255), 5)
#getting face subframe
the_face: object = frame[ y:y+h, x:x+w]
grayscaled_face = cv2.cvtColor(the_face, cv2.COLOR_BGR2GRAY)
#find all smiles within face
detecting_smile = smile_detector.detectMultiScale(grayscaled_face, scaleFactor=1.75, minNeighbors=20)
for (x_, y_, w_, h_) in detecting_smile:
cv2.rectangle(the_face, (x_, y_), (x_ + w_, y_ + h_), (0, 255, 0), 5)
#labelling face
if len(detecting_smile)>0:
cv2.putText(frame,"smiling",(x,y+h+40),fontScale=3,fontFace= cv2.FONT_HERSHEY_COMPLEX,color=(255,0,255))
cv2.imshow("detected_face", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
webcam.release()
cv2.destroyAllWindows()
# |
s = input()
if "1"*7 in s or '0'*7 in s:
print("YES")
else:
print("NO") |
import math
def isPrime(a):
if a==1 or a==2:
return True
for i in range(2,int(math.sqrt(a))+1):
if a%i==0:
return False
return True
def gcd(a,b):
if b==0:
return a
gcd(b, a%b)
test = int(input())
for t in range(test):
n = int(input())
l = list(map(int, input().split()))
flag = True
for i in range(1,n+1):
if i!=l[i-1]:
if i%l[i-1]!=0:
flag = False
if flag:
print("YES")
else:
print("NO") |
def lessthan(n):
i=1
while(1):
if(n<pow(2,i)):
return i-1
i+=1
tc=int(input())
for i in range(tc):
n=int(input())
if(n==1):
print("0")
elif(n==2 or n==3):
print("1")
else:
res=lessthan(n)
if(res%4==2):
print("2")
elif(res%4==3):
print("3")
elif(res%4==0):
print("0")
elif(res%4==1):
print("9") |
from os import system
print("1: Set Alarm for 6:00 am")
print("2: Turn off Zach Light")
print("3: Turn on Zach Light")
print("4: Stop")
for i in range(0,10):
number = input("Input your number here: ")
if (number == 1):
system("say Alexa, set an alarm for 6 in the morning")
if (number == 2):
system("say Alexa, turn off Zach Light")
if (number == 3):
system("say Alexa, turn on Zach Light")
if (number == 4):
system("say Alexa, stop")
|
from os import system as sys
global command
command = ""
while (True):
print("Edit\nView\nRun")
editing = raw_input("What do you want to do? ")
if editing == "Edit":
command = "vim "
print("You can now Edit")
elif editing == "edit":
command = "vim "
print("You can now edit")
elif editing == "View":
command = "cat "
print("You can only View")
elif editing == "view":
command = "cat "
print("you can only view")
elif editing == "Run":
command = "python "
print("You can only Run")
elif editing == "run":
command == "python "
print("You can only run")
elif editing == "exit":
break
elif editing == "quit":
break
else:
print("Sorry that can not be done")
break
print("Which file do you want to run?")
sys("ls")
program = raw_input("File: ")
if program == "quit":
break
elif program == "exit":
break
else:
sys(command+program)
con = raw_input("Do you want to continue? ")
if con == "yes":
sys("clear")
elif con == "no":
break
else:
sys("clear")
print("Well lets continue then")
|
worker = {
'name': 'Michal',
'nazwisko': 'Znaj',
'wiek': 21,
'dzieci': ['Jas' , 'Zosia'],
'rodzice': ['Anna' , 'Robert']
}
print(worker)
print(worker['dzieci'])
print ('Dziecko 1: ' + str(worker["dzieci"][0]))
print ('Dziecko 2: ' + str(worker["dzieci"][1]))
worker['height'] = 180
worker['weight'] = 80
print(worker)
key='age'
if key in worker:
del worker[key]
print(f'Klucz o nazwie {key} został usunięty')
else:
print(f'Klucz o nazwie {key} nie został znaleziony w słowniku')
print(worker)
print(worker)
for key, value in worker.items():
print(f'{key}:{value}') |
# -*- coding: UTF-8 -*-
#
# Merge Sort Algorithm
# The All ▲lgorithms library for python
#
# Contributed by: Carlos Abraham Hernandez
# Github: @abranhe
#
def merge_sort(arr):
if len(arr) == 1:
return arr
left = merge_sort(arr[:(len(arr)//2)])
right = merge_sort(arr[(len(arr)//2):])
out = []
while bool(left) or bool(right):
if bool(left) ^ bool(right):
alias = left if left else right
else:
alias = left if left[0] < right[0] else right
out.append(alias[0])
alias.remove(alias[0])
return out
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""
The following are generic functions that are used
for grouping purposes
"""
#used to mine frequency patterns from non-numeric attributes
#ex: country frequency, frequency of weapon type and sub weapon type, etc
def freq_grouping(df, attribute, attribute_val, dist_attr, dist_sub_attr=None):
attr_list = [dist_attr]
if dist_sub_attr is not None:
attr_list.append(dist_sub_attr)
return df[df[attribute] == attribute_val].groupby(attr_list)
#used to mine time-series patterns
def time_series_grouping(df, attributes, start=1974, end=2016):
return df[(df.loc[:,'iyear'] >= start) & (df.loc[:,'iyear'] <= end)].loc[:,attributes + ['iyear', 'imonth']].groupby(['iyear', 'imonth'])
#using to retrieve totals in numerical data
def total_grouping(df, total_attr, start=1974):
return (df.iloc[:,2:].set_index(['Indicator Name'])
.rename_axis(None)
.T[15:].dropna(axis=1, thresh=20)
.loc[:,total_attr].sum().values
)
def get_numeric_attributes(df, ):
|
print('1. Reverse the order of the items in an array.')
a=[1,2,3,4,5]
print(a)
a.reverse()
print(a)
print()
print('2. Get the number of occurrences of var b in array a.')
a=[1,1,2,2,2,2,3,3,3]
print(a)
b=2
print(b)
a.count(2)
print('The number of occurrences of var b in array a is:')
print(a.count(2))
print()
print('3. Given a sentence as string, count the number of words in it.')
a='Ana are mere si nu are pere'
print(a)
res=len(a.split())
print ('The number of words in string are: ' + str(res))
|
import re
from itertools import imap
# Magic ASCII number
A = 97
# Can't have these
bad = re.compile(r'i|o|l')
# Must have two pairs
pairs = re.compile(r'([a-z])\1.*([a-z])\2')
# Check if we have a sequence of type 'abc'
def has_sequence(password):
# Switch chars to numbers
nums = map(ord, password)
# This checks if the current three are a run
has_run = lambda a,b,c: a == b - 1 and b == c - 1
# This maps our has_run on offset sequences and let's us know if anythin
# makes a run.
return any(imap(has_run, nums, nums[1:], nums[2:]))
def get_next_char(c):
# Reduce number to 0-26 range, then add 1
base_num = ord(c) - A + 1
# Convert back to char, keeping within 0-26, then add back up to [a-z] range
return chr((base_num % 26) + A)
def increment_string(s):
if not s:
return ''
next_char = get_next_char(s[-1:])
# If we overflow, recursively overflow on earlier substrings
if next_char == 'a':
return increment_string(s[:-1]) + 'a'
next_string = s[:-1] + next_char
return next_string
# Checks against all required predicates
def is_valid(password):
return (has_sequence(current_password)
and pairs.search(current_password)
and not bad.search(current_password))
current_password = 'XXXXXXXX'
while not is_valid(current_password):
current_password = increment_string(current_password)
# And get next after that...
current_password = increment_string(current_password)
while not is_valid(current_password):
current_password = increment_string(current_password)
print current_password
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author coolharsh55
# Harshvardhan J. Pandit
# LOGIC
# Given a point (x,y), we need to find the number that occurs
# at that point. To do that, we need to find the diagonal that it belongs to.
# Each diagonal has (i in 1 to x +y-1)∑i numbers.
# Given (x,y), it occurs somewhere between that range.
# In the diagonal, there are always z numbers above it, where
# z is the row of the number - 1.
# Therefore, the position of (x,y) can be translated into number as:
# (i: 1->x+y-1)∑i - x + 1
# which is, sum of all numbers in diagonals, subtracted by the numbers
# still above it, specified by x (row) and adding 1 for itself.
# Code Generation
# First code is 20151125
# Each code after that is:
# (previous * 252533) % 33554393
# point in the manual for the code
point_x, point_y = 2981, 3075
# code seeds
code = 20151125
multiplier = 252533
divisor = 33554393
# number of code (as in index)
number = 0
# I: find out the index number of code
# diagonal is x + y - 1
diagonal = point_x + point_y - 1
for i in range(1, diagonal):
number += i
# positions to calculate in the final diagonal
# is the length of the diagonal - rows skipped
# + 1 for the number itself
pos_left = diagonal - point_x + 1
for i in range(0, pos_left):
number += 1
# II: calculate code for given number iteratively
for i in range(2, number + 1):
code = (code * multiplier) % divisor
print(code)
|
import re
inp = 'XXXXXXXX'
# This is a little complicated, we find a digit and capture all of its
# repetitions, in the second capture group we have the single digit itself
repeating_digits = re.compile(r'((\d)\2*)')
for i in range(0,50):
new_input = ''
# Unpack into the total match and the single digit.
for match, character in repeating_digits.findall(inp):
new_input += str(len(match))
new_input += character
inp = new_input
print(len(inp))
|
import numpy as np
import cv2
'''
The Process of Canny edge detection algorithm can be broken down to 5 different steps:
1. Apply Gaussian filter to smooth the image in order to remove the noise
2. Find the intensity gradients of the image
(cite: from Wikipedia for reference)
'''
def edge_detection():
# Step 1
img = smoothing()
# Step 2
get_intensity_gradients(img)
'''
This methods calculates partial derivatives vectors and returns its magnitude and direction.
'''
def get_intensity_gradients(img):
# Pass array and dataType in this method
# Kernel for Gradient in x-direction
Mx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.int32)
# Kernel for Gradient in y-direction
My = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.int32)
# Apply kernels to the image
Ix = convolve(img, Mx)
cv2.imshow('Image Derivative - X (dx)', Ix)
cv2.waitKey(10000)
Iy = convolve(img, My)
cv2.imshow('Image Derivative - Y (dy)', Iy)
cv2.waitKey(10000)
magnitude = np.hypot(Ix, Iy)
cv2.imshow('Edge Map', magnitude)
cv2.waitKey(10000)
direction = np.arctan2(Iy, Ix)
cv2.imshow('Orientation Map', direction)
cv2.waitKey(10000)
return magnitude, direction
def convolve(image, kernel):
m, n = kernel.shape
y, x = image.shape
y = y - m + 1
x = x - m + 1
convoluted = np.zeros((y,x))
for i in range(y):
for j in range(x):
convoluted[i][j] = np.sum(image[i:i+m, j:j+m]*kernel)
return convoluted
def main():
edge_detection()
def smoothing(n=3):
kernel = np.ones((n, n))
kernel = kernel / np.sum(kernel)
array = []
img = cv2.imread(r'C:\Users\Prashant\Desktop\CV imgs\capitol.jpg', 0)
cv2.imshow('Original Image', img)
cv2.waitKey(10000)
for j in range(n):
temp = np.copy(img)
temp = np.roll(temp, j - 1, axis=0)
for i in range(n):
temp_X = np.copy(temp)
temp_X = np.roll(temp_X, i - 1, axis=1) * kernel[j, i]
array.append(temp_X)
array = np.array(array)
array_sum = np.sum(array, axis=0)
for i in range(len(array_sum)):
for j in range(len(array_sum[0])):
img.itemset((i,j), array_sum[i][j])
cv2.imshow('After Smoothing with Size ' + str(n) + ' kernel', img)
cv2.waitKey(10000)
return img
main() |
#!/usr/bin/env python2
"""
Masked wordcloud
================
Using a mask you can generate wordclouds in arbitrary shapes.
"""
from os import path
import numpy as np
from PIL import Image
from wordcloud import WordCloud
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'article.txt')).read()
# read the mask image
# taken from
# http://www.stencilry.org/stencils/movies/alice%20in%20wonderland/255fk.jpg
origin_image = Image.open(path.join(d, "map.png"))
alice_mask = np.array(origin_image)
wc = WordCloud(background_color=None, max_words=2000, mask=alice_mask,
width=1423, height=601, mode="RGBA")
# generate word cloud
wc.generate(text)
text_cloud_image = wc.to_image()
text_cloud_image.save('out.png')
image_with_bg = Image.open(path.join(d, "map_with_bg.png"))
image_with_bg.paste(text_cloud_image, (0, 0), text_cloud_image)
image_with_bg.show()
image_with_bg.save("bg.png", "PNG")
|
def twoSum(nums: List[int], target: int) -> List[int]:
map = {}
for index in range(len(nums)):
if target - nums[index] not in map:
map[nums[index]] = index
else:
return [index, map[target - nums[index]]]
print(twoSum([2, 7, 3], 9))
|
cs = 3 #次数
while cs > 0:
password = input('请输入密码:')
cs = cs - 1
if password =='a123456':
print('登录成功')
break
elif cs > 0: #3-cs>0
print('密码错误,您还有', cs, '次机会')
else:
print('密码错误,您已经没有机会了,请您改天再试试吧')
|
"""
Uso: Comparacion 2
Creador: Andrés Hernández Mata
Version: 1.0.0
Python: 3.9.1
Fecha: 15 Junio 2021
"""
calif_parcial = int( input("Parcial: ") )
CALIF_APROB = 70
print( calif_parcial, type(calif_parcial) )
print( CALIF_APROB, type(CALIF_APROB) )
print(calif_parcial > CALIF_APROB)
print( str(calif_parcial) + " > " + str(CALIF_APROB) + " = ", calif_parcial > CALIF_APROB)
print( str(calif_parcial) + " >= " + str(CALIF_APROB) + " = ", calif_parcial >= CALIF_APROB)
print( str(calif_parcial) + " < " + str(CALIF_APROB) + " = ", calif_parcial < CALIF_APROB)
print( str(calif_parcial) + " <= " + str(CALIF_APROB) + " = ", calif_parcial <= CALIF_APROB)
print( str(calif_parcial) + " == " + str(CALIF_APROB) + " = ", calif_parcial == CALIF_APROB)
print( str(calif_parcial) + " != " + str(CALIF_APROB) + " = ", calif_parcial != CALIF_APROB)
|
"""
Uso: Comparacion 4
Creador: Andrés Hernández Mata
Version: 1.0.0
Python: 3.9.1
Fecha: 15 Junio 2021
"""
def es_bool(str):
if str == "true":
return True
elif str == "false":
return False
else:
print('Respuesta incorrcta intenta con "TRUE" o "FALSE" ')
tiene_efectivo = es_bool( input("Tiene efectivo: ").lower() )
tiene_credito = es_bool( input("Tiene credito: ").lower() )
print( tiene_efectivo , type(tiene_efectivo) )
print( tiene_credito , type(tiene_credito ) )
puede_comprar = tiene_efectivo or tiene_credito
print(puede_comprar)
print()
print( "tiene_efectivo: " + str(tiene_efectivo) + " or " + "tiene_credito: " + str(tiene_credito) + " puede_comprar: " + str(puede_comprar) )
|
#!/usr/bin/env python2.5
# a simple script that takes a surface form (word)
# as input and runs the kimmo recognizer on it
# using spanish.yaml as the configuration file.
from kimmo import *
import sys
k = KimmoRuleSet.load('spanish.yaml')
if len(sys.argv[1:]) == 0:
print "usage: %s <word> [<trace>]" %(sys.argv[0])
sys.exit()
word = sys.argv[1]
trace = 1
if len(sys.argv) > 2:
trace = sys.argv[2]
print list(k.recognize(word, TextTrace(trace))), '<=', word
|
name= raw_input("Enter the name of your macro:\n")
name = name.upper().lstrip().rstrip()
macro_file = file("macros.txt","a")
macro = raw_input("Enter the instructions for the macro (separated by a semicolon):\n")
macro = macro.lstrip().rstrip()
lines = macro.split(";")
string = ""
for line in lines:
string = string + "#" +line
macro_file.write(name + string + '\n')
macro_file.close()
|
import math
def power(x,n=2):
s=1
while n>0:
n=n-1
s=s*x
return s
def enroll(name, gender, age=6, city='Beijing'):
print('name: ',name)
print('gender: ',gender)
print('age: ',age)
print('city: ',city)
print()
#n =power(5,3)
#print(n)
#m=power(4)
#print(m)
#s = enroll('Xiaowang','男',city='Nanjing')
#print(s)
def calc(*numbers):
sum=0
for n in numbers:
sum=sum+n*n
return sum
nums = [1,2,3,4]
sum = calc(*nums)
print(sum)
def person(name, age, **kw):
if 'city' in kw:
#有city参数
pass
if 'job' in kw:
#有job参数
pass
print('name:',name,'age:',age,'other:',kw)
print(person('Bob',18,city='Beijing',job='Enginer'))
extra = {'city':'Beijing','job':'Engineer'} #dict
print(person('Bob',20,**extra))
print(person('Bob',24,city = 'Beijing',addr='changyang',zipcode=111)) |
from pathlib import Path
import csv
budget_data = Path("budget_data.csv")
with open('budget_data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
csv_header = next(csv_reader)
months = 0
total_return = 0
value = 0
change = 0
profits = []
dates = []
first_row = next(csv_reader)
months += 1
total_return += int(first_row[1])
value = int(first_row[1])
for row in csv_reader:
dates.append(row[0])
change = int(row[1]) - value
profits.append(change)
value = int(row[1])
total_return += int(row[1])
months += 1
ave_change = sum (profits) / len(profits)
greatest_increase = max(profits)
greatest_index = profits.index(greatest_increase)
greatest_date = dates[greatest_index]
greatest_decrease = min(profits)
least_index = profits.index(greatest_decrease)
least_date = dates[least_index]
print("Financial Analysis")
print("----------------------------")
print(f'Total Months: {months}')
print(f"Total: ${total_return}")
print(f"Average Change: ${str(round(ave_change,2))}")
print(f"Greatest Increase in Profits: {greatest_date} (${str(greatest_increase)})")
print(f"Greatest Decrease in Profits: {least_date} (${str(greatest_decrease)})")
output = open("budget_data.txt", "w")
line_1 = "Financial Analysis"
line_2 = "----------------------------"
line_3 = str(f'Total Months: {months}')
line_4 = str(f"Total: ${total_return}")
line_5 = str(f"Average Change: ${sum (profits) / len(profits)}")
line_6 = str(f"Greatest Increase in Profits: {greatest_date} (${str(greatest_increase)})")
line_7 = str(f"Greatest Decrease in Profits: {least_date} (${str(greatest_decrease)})")
output.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(line_1,line_2,line_3,line_4,line_5,line_6,line_7))
|
# -*- coding: utf-8 -*-
# Programa em Python para gerar a frase de destino, começando a partir
# de frase aleatória usando algoritmo genético
# Referencia: https://www.geeksforgeeks.org/genetic-algorithms/
import random
# Número de indivíduos em cada geração
POPULATION_SIZE = 100
# Genes válidos
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890, .-;:_!"#%&/()=?@${[]}'''
# Frase de destino a ser gerada
TARGET = "Eu nao sou um robo!"
class Individual(object):
'''
Classe representando indivíduo na população
'''
def __init__(self, chromosome):
self.chromosome = chromosome
self.fitness = self.cal_fitness()
@classmethod
def mutated_genes(self):
'''
Criar genes aleatórios para mutação
'''
global GENES
gene = random.choice(GENES)
return gene
@classmethod
def create_gnome(self):
'''
Criar cromossomo ou frase de genes
'''
global TARGET
gnome_len = len(TARGET)
return [self.mutated_genes() for _ in range(gnome_len)]
def mate(self, par2):
'''
Realizar acasalamento e produzir novos descendentes
'''
# cromossomo para descendentes
child_chromosome = []
for gp1, gp2 in zip(self.chromosome, par2.chromosome):
# random probability
prob = random.random()
# if prob is less than 0.45, insert gene
# from parent 1
if prob < 0.45:
child_chromosome.append(gp1)
# if prob is between 0.45 and 0.90, insert
# gene from parent 2
elif prob < 0.90:
child_chromosome.append(gp2)
# otherwise insert random gene(mutate),
# for maintaining diversity
else:
child_chromosome.append(self.mutated_genes())
# criar novos Indivíduos (descendentes) usando
# cromossomo gerado para o descendente
return Individual(child_chromosome)
def cal_fitness(self):
'''
Calcula a pontuação de fittness, é o número de
caracteres da frase que diferem da
frase de destino.
'''
global TARGET
fitness = 0
for gs, gt in zip(self.chromosome, TARGET):
if gs != gt:
fitness += 1
return fitness
# Driver code
def main():
global POPULATION_SIZE
# Geração corrente
generation = 1
found = False
population = []
# Cria a população Inicial
for _ in range(POPULATION_SIZE):
gnome = Individual.create_gnome()
population.append(Individual(gnome))
while not found:
# classificar a população em ordem crescente de pontuação de aptidão
population = sorted(population, key=lambda x: x.fitness)
# se o indivíduo com menor pontuação de aptidão ou seja.
# 0 então sabemos que chegamos ao alvo
# e sai do loop
if population[0].fitness <= 0:
found = True
break
# Caso contrário, gerar novos descendentes para a nova geração
new_generation = []
# Perform Elitism, que significa 10% da população mais apta
# vai para a próxima geração
s = int((10*POPULATION_SIZE)/100)
new_generation.extend(population[:s])
# De 50% da população mais apta, Indivíduos
# vai acasalar para produzir descendentes
s = int((90*POPULATION_SIZE)/100)
for _ in range(s):
parent1 = random.choice(population[:50])
parent2 = random.choice(population[:50])
child = parent1.mate(parent2)
new_generation.append(child)
population = new_generation
print("Geração: {}\tFrase: {}\tAvaliação: {}".
format(generation,
"".join(population[0].chromosome),
population[0].fitness))
generation += 1
print("Geração: {}\tFrase: {}\tAvaliação: {}".
format(generation,
"".join(population[0].chromosome),
population[0].fitness))
if __name__ == '__main__':
main()
|
# =============================================================================
# Foydalanuvchidan aylaning radiusini qabul qilib olib,
# uning radiusini, diametrini, perimetri va yuzini
# lug'at ko'rinishida qaytaruvchi funksiya yozing
# =============================================================================
def radius(r):
d=2*r
p=2*3.14*r
s=3.14*(r**2)
diction={
'radius':r,
'diameter':d,
'perimeter':p,
'surface':s
}
return diction
n=int(input("enter radius: "))
m=radius(n)
print(m)
|
# =============================================================================
# from datetime import *
# # now=datetime.now()
# # time=datetime.now().time()
# # print(now.second,now.minute,now.hour)
# # print(time)
# # print('today:'+str(date.today()))
# # tomorrow=date(2021,10,2)
# # print('tomorrow:'+str(tomorrow))
# # =============================================================================
# # today=date.today()
# # ramadan=date(2022,4,2)
# # remained_days=ramadan-today
# # print(f"{remained_days.days} days last till ramadan month")
# # =============================================================================
#
# =============================================================================
import math
pi=math.pi
pi=math.e
cosx=math.cos(0)
sinx=math.sin(math.pi/2)
print(math.degrees(3*math.pi/2))
print(math.radians(145))
|
print("We gonna create a list of products for market")
products={}
i=1
while True :
product=input(f"Please enter {i}-product's name':")
value=int(input(f"Please enter {product}'s price':"))
products[product]=value
i+=1
msg=input("Do you want again?(yes/no)")
if msg!='yes':
break
print(products) |
class Student:
def __init__(self,name,surname,born):
self.name = name
self.surname=surname
self.born=born
def get_know(self):
print(f"{self.name} {self.surname} was born in {self.born}")
def get_name(self):
"""Talabaning ismini qaytaradi"""
return self.name
def get_lastname(self):
"""Talabaning familiyasini qaytaradi"""
return self.lastname
def get_fullname(self):
"""Talabaning ism-familiyasini qaytaradi"""
return f"{self.name} {self.surname}"
def tanishtir(self):
print(f"Ismim {self.name} {self.surname}. {self.born} yilda tu'gilganman")
student1 = Student("Olim","Mavlonov",1998)
student2=Student('Shahrizod','Saidov',1999)
student3=Student('Xurshid','Dushanov',2000) |
# from math import sqrt
# nums = list(range(11)) # 0 dan 10 gacha numbers_list ro'yxati
# square_root = list(map(sqrt,nums))
# numbers_list = list(range(11))
# def daraja2(x):
# """Berilgan sonning kvadratini qaytaruvchi funksiya"""
# return x*x
# print(list(map(daraja2,numbers_list)))
# def numbers(x):
# return x**2
# kv=[]
# for son in numbers_list:
# son=numbers(son)
# kv.append(son)
# print(kv)
# print(list(map(lambda x:x**2,numbers_list)))
# a = [4, 5, 6]
# b = [7, 8, 9]
# a_plus_b = list(map(lambda x,y:x+y,a,b))
# print(a_plus_b)
# names = ['hasan','husan','olim','umid']
# print(list(map(lambda x:x.upper(),names)))
# import random as r
# sonlar = r.sample(range(100),10)
# def juftmi(x):
# return x%2==0
# juft_sonlar = list(filter(juftmi,sonlar))
# print(sonlar)
# print(juft_sonlar)
from random import sample
from math import sqrt,floor
x=list(range(0,1001))
y=sample(x,k=10)
print(y)
print(list(((map(lambda x:sqrt(x),y)))))
print(list(filter(lambda x:(x%2!=0),y)))
print(list(filter(lambda x:(x%2==0),y)))
|
from abc import ABC, abstractmethod
from typing import List
import random
class SModel(ABC):
"""
The Strategy interface declares operations common to all supported versions
of some algorithm.
The Context uses this interface to call the algorithm defined by Concrete
Strategies.
"""
@abstractmethod
def train(self):
pass
@abstractmethod
def predict(self, data:List):
pass
def shuffle_data(self):
c = list(zip(self.x_train,self.y_train))
random.shuffle(c)
x, y = zip(*c)
self.x_train = list(x)
self.y_train = list(y)
@abstractmethod
def get_val_y(self):
pass
class IModel():
"""
The model context defines the interface of interest to clients.
"""
def __init__(self, model_strategy: SModel) -> None:
"""
Usually, the Context accepts a strategy through the constructor, but
also provides a setter to change it at runtime.
"""
self._model = model_strategy
@property
def model(self) -> SModel:
"""
The Context maintains a reference to one of the Strategy objects. The
Context does not know the concrete class of a strategy. It should work
with all strategies via the Strategy interface.
"""
return self._model
@model.setter
def strategy(self, model_strategy: SModel) -> None:
"""
Usually, the Context allows replacing a Strategy object at runtime.
"""
self._model = model_strategy
def train(self) -> None:
"""
The Context delegates some work to the Strategy object instead of
implementing multiple versions of the algorithm on its own.
"""
self._model.train()
def predict(self,data) -> None:
"""
The Context delegates some work to the Strategy object instead of
implementing multiple versions of the algorithm on its own.
"""
return self._model.predict(data)
def set_data(self, x_train, y_train, x_validation=None, y_validation=None):
self._model.set_data(x_train, y_train, x_validation, y_validation)
def get_val_y(self):
return self._model.get_val_y()
|
#ax^2+bx+c=0
import math
print("entrez les coefficients :")
a=input("a = :")
b=input("b = :")
c= input("c= :")
a=float(a)
b=float(b)
c=float(c)
if a!= :
d=b*b-4*a*c
D=float(d)
if D>0:
x1=(-b-math.sqrt(D))/2*a
x2=(-b+math.sqrt(D))/2*a
print("l'équation a deuxx solutions : ",x1,x2)
elif D==0 :
x0=-b/2*a
print("x0 = :",x0)
else :
print("l'equation n'a pas de solution") |
import math
a=int (input("entrez un nombre : "))
b=False
for i in range(2,int(math.sqrt(a))):
if a%i==0:
b=True
if b:
print(a, " est un nombre premier")
else :
print(a, " n'est pas un nombre premier") |
ageUser=input("Donnz votre age: ")
try:
ageUser=int(ageUser)
except:
print("L'age indiqué est erroné")
else:
'''ce qui se passe en cas de reussite'''
print("Tu as ",ageUser, "ans")
finally:
print("Fin programme...") |
# write your code here
import random
def dinner():
print("Enter the number of friends joining (including you):")
number = int(input())
print()
if number > 0:
dictionary = create(number)
bill = pay(dictionary)
lucky(dictionary, bill)
print(dictionary)
else:
print("No one is joining for the party")
def create(number):
friend_list = []
print("Enter the name of every friend (including you), each on a new line:")
for _ in range(number):
friend_list.append(input())
print()
return dict.fromkeys(friend_list, 0)
def pay(dictionary):
print("Enter the total bill value:")
bill = int(input())
print()
split = round(bill / len(dictionary), 2)
for i in dictionary:
dictionary[i] = split
return bill
def lucky(dictionary, bill):
print('Do you want to use the "Who is lucky?" feature? Write Yes/No:')
decision = input()
print()
if decision == "Yes":
participants = []
for i in dictionary:
participants.append(i)
random.seed()
chosen = random.choice(participants)
print(f"{chosen} is the lucky one!")
print()
lucky_pay(dictionary, bill, chosen)
else:
print("No one is going to be lucky")
print()
def lucky_pay(dictionary, bill, chosen):
split = round(bill / (len(dictionary) - 1), 2)
for i in dictionary:
if i == chosen:
dictionary[i] = 0
else:
dictionary[i] = split
dinner()
|
from typing import List
from .algorithm import Algorithm
from .result import Result
class Simple(Algorithm):
@property
def name(self) -> str:
return "Simple"
def solve(self, coefitients: List[float], value: float) -> Result:
solution = 0
additions_count = 0
multiply_count = 0
power = len(coefitients)
for cf_index in range(len(coefitients)):
# Manual power loop
value_to_power = 1
for i in range(power - cf_index - 1):
multiply_count += 1
value_to_power *= value
solution += coefitients[cf_index] * value_to_power
multiply_count += 1
additions_count += 1
return Result(self, solution, multiply_count, additions_count) |
def validateInteger(n,val,x):
s = str(val)
if s.isdecimal() or s[1:].isdecimal() :
li =-(2**n)
ls = (2**n)+x
print(li,val,ls)
if li <= val and val <= ls:
return None
return {'Type':"numeric",'Descripción':"Valor entero fuera del rango establecido"}
def beforePointD(max,val):
s = str(val)
min = -max
if val <0 :
s = s[1:]
if min <= len(s) and len(s) <= max:
return True
return False
def beforePointN(max,val):
s = str(val)
if val <0 :
s = s[1:]
if max == len(s):
return True
return False
def afterPoint(max,val):
s = str(val)
if len(s) <= max:
return True
return False
def validateDecimal( col,val):
n = str(val)
p = col['size'][0]
s = col['size'][1]
if "." in n:
lts = n.split(".")
x = beforePointD(p-s,int(lts[0]))
y = afterPoint(s,int(lts[1]))
print(x,y)
if x and y:
return None
else:
if beforePointD(p-s,val):
return None
return {'Type':"numeric",'Descripción':"Valor decimal fuera del rango establecido"}
def validateNumeric(col,val):
n = str(val)
p = col['size'][0]
s = col['size'][1]
if "." in n:
lts = n.split(".")
x = beforePointN(p-s,int(lts[0]))
y = afterPoint(s,int(lts[1]))
print(x,y)
if x and y:
return None
else:
if beforePointN(p-s,val):
return None
return {'Type':"numeric",'Descripción':"Valor numeric fuera del rango establecido"}
def validateReal( col,val):
n = str(val)
#p = col['size']
if "." in n:
lts = n.split(".")
x = validateInteger(31,int(lts[0]),0)
y = afterPoint(6,int(lts[1]))
print(x,y)
if x and y:
return None
else:
if validateInteger(31,int(lts[0]),0):
return None
return {'Type':"numeric",'Descripción':"Valor real fuera del rango establecido"}
def validateDouble( col,val):
n = str(val)
#p = col['size']
if "." in n:
lts = n.split(".")
x = validateInteger(63,int(lts[0]),0)
y = afterPoint(15,int(lts[1]))
print(x,y)
if x and y:
return None
else:
if validateInteger(63,int(lts[0]),0):
return None
return {'Type':"numeric",'Descripción':"Valor double fuera del rango establecido"}
def validateMoney(val):
max = (2**63+0.07)
min = -(2**63+0.08)
if min <= val and val <= max :
return None
return {'Type':"numeric",'Descripción':"Valor money fuera del rango establecido"} |
#CREATE A DICTIONARY TO STORE THE SYMBOLS AND A COUNTER FOR THE INDEX
symbolTable=dict()
#CREATE A NEW SYMBOL AND STORE IT INTO THE SYMBOL TABLE, INCREASE COUNTER BY 1
def add_symbol(name_,type_,value_,row_,column_,ambit_):
symbolTable[name_]=[type_,value_,row_,column_,ambit_]
#SEARCH A SYMBOL WITH name_ IF IS FOUND, THE RETURN name_, type_ AND value_
def search_symbol(name_):
if name_ in symbolTable:
return name_,symbolTable[name_][1],symbolTable[name_][2]
else:
return 0
#MODIFY THE VALUE OF A SYMBOL, THE type_ VERIFICATION MUST BE DONE BEFORE EXECUTE THIS
def modify_symbol(name_,value_):
if name_ in symbolTable:
symbolTable[name_]=[symbolTable[name_][1],value_] |
class Heap(object):
"""
Une heap est une structure de données sous forme d'arbre.
https://en.wikipedia.org/wiki/Heap_(data_structure)
"""
def insert(self, value: int) -> None:
"""
Ajoute une valeur dans l'arbre
"""
pass
def find_min(self) -> int:
"""
Retourne la valeur minimum dans l'arbre
"""
pass
def delete_min(self) -> int:
"""
Supprime et retourne la valeur minimum dans l'arbre
"""
pass
def merge(self, fibonnaci_heap: object) -> None:
"""
Fusionne deux arbres
"""
pass
class Tree(object):
def __init__(self):
self.nodes = []
self.count = 0
def add_value(self, value):
self.nodes.append(value)
self.count = self.count + 1
def __repr__(self):
return repr(self.nodes)
class FibonacciHeap(Heap):
"""
Une fibonnaci heap est un arbre permettant de stocker et trier des donnés efficacement
https://en.wikipedia.org/wiki/Fibonacci_heap
L'implémentation est décrite en anglais : https://en.wikipedia.org/wiki/Fibonacci_heap#Implementation_of_operations
et en français : https://fr.wikipedia.org/wiki/Tas_de_Fibonacci#Implémentation_des_opérations
"""
def __init__(self):
self.nodes = []
self.count = 0
self.min_node = None
def insert(self, value: int) -> None:
"""
Ajoute une valeur dans l'arbre
"""
new_tree = Tree()
new_tree.add_value(value)
if self.min_node is None or self.min_node > value:
self.min_node = value
self.nodes.append(new_tree)
self.count = self.count + 1
def find_min(self) -> int:
"""
Retourne la valeur minimum dans l'arbre
"""
return self.min_node
def delete_min(self) -> int:
"""
Supprime et retourne la valeur minimum dans l'arbre
"""
def merge(self, fibonnaci_heap: Heap) -> None:
"""
Fusionne deux arbres
"""
new_heap = FibonacciHeap()
data = [10, 12, 14, 52, 54, 101, 152, 4, 7, 17]
# data = [[10, [17]], [12], [14], [52], [101], [152], [4], [7]]
# data = [[10, [17]], [14], [52], [101], [152], [4], [7, [12]]]
for value in data:
new_heap.insert(value)
print("La liste est donc :")
print(new_heap.nodes)
print ("Le minimum est :")
print(new_heap.find_min())
new_heap.insert(3)
print ("Valeur insérée est 3")
print ("La nouvelle liste est donc :")
print(new_heap.nodes)
print("Le nouveau minimum est donc :")
print(new_heap.find_min())
|
class A:
def __init__(self, val=0):
self.val = val
def add(self, x):
self.val += x
def print_val(self):
print(self.val)
a = A()
b = A(2)
c = A(4)
a.add(2)
b.add(2)
a.print_val()
b.print_val()
c.print_val() |
def test_substring(full_string, substring):
assert substring in full_string, f"expected '{substring}' to be substring of '{full_string}'"
test_substring('full_string', 'string')
#s = 'My Name is Julia'
#if 'Name' in s:
# print('Substring found') |
seq1 = 'ATGTTATAG'
#print every 3
for i in range(0,len(seq1),3):
print(i, seq1[i])#indexing
#or you could do
print(seq1[0::3])
#print first 3, next 3, so on
for i in range(0,len(seq1),3):
print(seq1[i:i+3]) #slicing
|
try:
num = int(input("Choose a number: "))
print(10/num)
except ZeroDivisionError:
print("Can't divide by 0")
except ValueError:
print("Please input a valid number")
|
"""
IS 590PR - Programming for Analytics & Data Processing
Final Project- Goalkeeper Success Rate Simulation
Authors:
Samuel John
Salonee Shah
Claire Wu
"""
from random import choice, randint
from collections import Counter
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class Player:
"""
The Player class has been created to create instances of players, both strikers and goalkeeper.
It also has an instance of team which is a collection of player instances.
The class has a number of functions that simulate the various aspects of a penalty kick from both the stiker's
as well as the goalkeeper's point of view.
The goalkeeper can be trained to use adaptive training techniques by recording strikers' kick directions
or the team's kick direction and act accordingly
"""
# create instances for team, keeper and team jump direction
team = []
keeper = None
team_jump_dir = []
# define an init class with the initial parameters of class objects
def __init__(self, name=None):
"""
This function checks if a player is a striker or keeper.
Strikers are added to the shooting team while a keeper is assigned the role of a Goalkeeper.
:param:name:Name of the player either 'Player' as Striker or 'Goalie' as goalkeeper
:return: none
"""
if name != 'Goalie':
Player.team.append(self)
else:
Player.keeper = self
self.name = name
(self.wins_case1, self.wins_case2, self.wins_case3) = (0, 0, 0)
(self.losses_case1, self.losses_case2, self.losses_case3) = (0, 0, 0)
self.tendency = [1, 1, 1]
self.jump_dir_history = []
@staticmethod
def choose_direction_goalie(team, consider_direction, striker):
"""
This function chooses is used to select the goalkeeper's jump direction.
The keeper's direction is chosen randomly in scenario 1, based on team tendency in scenario 2 or based on
striker's tendency in scenario 3.
:param team: indicates if the team tendency is being considered, holds value of true or false
:param consider_direction: indicates if direction is being considered, holds value of true or false
:param striker: player who kicks the ball
:return: jump_dir,direction: direction in which goalie should jump randomly or the direction left,right
or middle
>>> np.random.seed(1)
>>> team=True
>>> consider_direction=True
>>> striker='Player A'
"""
# consider direction is false for scenario 1 and true for scenario 2 and 3
if not consider_direction:
# if scenario 1, select random value of right, left or middle
directions = ['Right', 'Left', 'Middle']
jump_dir = choice(directions)
return jump_dir
else:
if team:
# if scenario 2 check the count of all directions of entire team
counter = Counter(Player.team_jump_dir)
else:
# if scenario 3 check the count of all directions for that player
counter = Counter(striker.jump_dir_history)
# find the most frequent direction and return that direction. If the player hasn't shot before,
# meaning there is no frequent direction, then the goalie selects a random direction
if counter == {}:
directions = ['Right', 'Left', 'Middle']
direction = choice(directions)
else:
max_count = max(counter.values())
mode = [i for i, j in counter.items() if j == max_count]
direction = choice(mode)
return direction
def choose_direction_striker(self, consider_direction):
"""
Function to choose striker's direction - randomly from the list of direction when consider_direction is
false or based on striker's tendency when consider_direction is true
:param self: Striker
:param consider_direction: indicates if direction is being considered, holds value of true or false
:return: jump_dir,left,right,middle: direction in which goalie should jump randomly
or the direction left,right or middle
>>> np.random.seed(1)
>>> consider_direction=True
>>> consider_direction=False
"""
# consider direction is false for scenario 1 and true for scenario 2 and 3
if not consider_direction:
# if scenario 1, striker selects a random direction
directions = ['Right', 'Left', 'Middle']
jump_dir = choice(directions)
return jump_dir
else:
# if scenario 2 or 3, striker selects a direction based on their tendency
n = randint(1, sum(self.tendency))
if n <= self.tendency[0]:
self.tendency[0] += 1
jump_dir = 'Right'
elif n <= self.tendency[0] + self.tendency[1]:
self.tendency[1] += 1
jump_dir = 'Left'
else:
self.tendency[2] += 1
jump_dir = 'Middle'
# add player's selection to the list of last 5 shot directions for player and team
# FIFO - pop oldest value and append latest value
if len(Player.team_jump_dir) == 5:
Player.team_jump_dir.pop(0)
if len(self.jump_dir_history) == 5:
self.jump_dir_history.pop(0)
Player.team_jump_dir.append(jump_dir)
self.jump_dir_history.append(jump_dir)
return jump_dir
@staticmethod
def record_play(gk: 'Player', opponent: 'Player', opp_dir: str, winner: 'Player', consider_direction, team):
"""
To record goalie's wins or losses count when the goalie jumps in random direction to save the goal
or jumps in the team's frequent direction or striker's frequent direction
by calculating team's tendency or striker's tendency respectively
:param gk: Player
:param opponent: Player
:param opp_dir: opponent's direction
:param winner: Player who can be either striker or a goalie
:param consider_direction: direction of strikers either true or false
:param team: team of strikers, true for team else false
:return: none
"""
# record goalies wins and losses
if winner == gk: # Goalie win count
if not consider_direction: # Scenario 1
winner.wins_case1 += 1
else:
if team: # Scenario 2
winner.wins_case2 += 1
else: # Scenario 3
winner.wins_case3 += 1
else: # Goalie loss count
if not consider_direction:
Player.keeper.losses_case1 += 1
else:
if team:
Player.keeper.losses_case2 += 1
else:
Player.keeper.losses_case3 += 1
def penalty_sim(self, match, striker, tests, print_result=False, team=False, consider_direction=False):
"""
To calculate penalty simulation by considering the striker's and goalie's direction,
when both are in same direction results in goalie's win for maximum cases else striker wins
:param self: Goalie
:param match: n scenarios for range in tests
:param striker: opponent player
:param tests: number of cases for which simulation should work
:param print_result: prints saved or missed, it's either true or false
:param team: team of strikers, true only for team else false
:param consider_direction: direction of strikers, either true or false
:return: wins_case1,wins_case2,wins_case3: Goalie's win % for case 1,case 2 or case 3
"""
# In this function, goalie is 'self' and 'striker' is the player who is currently taking the penalty kick
if team and match < 5: # For scenario 2, run the code 5 times to obtain enough values to start
striker_direction = striker.choose_direction_striker(consider_direction)
return 0
# goalie and striker choose directions by calling respective functions
goalie_direction = self.choose_direction_goalie(team, consider_direction, striker)
striker_direction = striker.choose_direction_striker(consider_direction)
# Case 1 - goalie selects the right direction
if goalie_direction == striker_direction:
different = False
# Call fail or succeed to check if goalie saved the goal
result = fail_or_succeed(striker_direction, different)
if result == "Miss" or result == "Save":
winner = self
else:
winner = striker
else:
# Goalie selected the wrong direction
different = True
# Call fail or succeed function to check if striker missed the goal
result = fail_or_succeed(striker_direction, different)
if result == "Miss":
winner = self
else:
winner = striker
# Record goalie stats
Player.record_play(self, striker, striker_direction, winner, consider_direction, team)
# print the results of the match if print option is set to True
if print_result:
if result == "Miss":
print(match, "Player", striker.name, "missed the goal entirely. The winner is the the Goalie")
else:
print(match, "Player", striker.name, "kicked to the ", striker_direction,
", goal keeper jumped to the ", goalie_direction, ", the winner is ", winner.name)
# Return the results as a win percentage
if not consider_direction:
return (self.wins_case1 / tests) * 100
else:
if team:
return (self.wins_case2 / tests) * 100
else:
return (self.wins_case3 / tests) * 100
# outside class Player
def fail_or_succeed(strike_dir, different, n=None, sc=None, gc=None):
"""
To check whether the goal has been saved or missed by the goalie by considering 0,1 and 2
values based on convenience to reach
:param strike_dir: Striker's direction either left right or middle
:param different: different is just true or false where if both direction are same it is true
or if both direction are different it is false
:param n: a parameter added for doctest, passing 1 will return miss, passing anything else will run the next code
:param sc: a parameter added for doctest in order to have a SET select_difficulty value for doctest
:param gc: a parameter added for doctest in order to have a SET goalie_difficulty value for doctest
:return: 'Save' or 'Goal' or 'Miss'
>>> fail_or_succeed('Left', True, 3, 1, 1)
'Goal'
>>> fail_or_succeed('Left', True, 1)
'Miss'
>>> fail_or_succeed('Left', False, 3, 2, 2)
'Save'
>>> fail_or_succeed('Right', True, 3, 2, 1)
'Goal'
>>> fail_or_succeed('Right', False, 3, 0, 0)
'Save'
>>> fail_or_succeed('Middle', True, 3)
'Goal'
>>> fail_or_succeed('Middle', False, 3, 2, 0)
'Goal'
"""
# create 1 out of 10 chance for player to miss the goal entirely
if n is None:
n = randint(1, 10)
if n == 1:
return "Miss"
# if player misses, function ends here and returns 'Miss' for both cases, goalie jumps in same/opposite direction
# if goalie had jumped in opposite direction and player did not miss, function skips the else and returns 'Goal'
# if goalie jumped in the same direction and player did not miss, program moves to else
# goal has been divided into three sections, left, center, right, (Seen below) each section has subsection which
# have been assigned difficulty values with respect to how difficult it is for the goalie to reach that subsection
# 0 being the easiest to reach and 2 being the hardest to reach
# ___________________________
# || 2 | 1 || 1 | 1 || 1 | 2 ||
# || 1 | 0 || 0 | 0 || 0 | 1 ||
# || 1 | 0 || 0 | 0 || 0 | 1 ||
# goal has been divided into three sections, left, center, right, (Seen below) each section has subsection which
# have been assigned difficulty values with respect to how difficult it is for the goalie to reach that subsection
# 0 being the easiest to reach and 2 being the hardest to reach
# ___________________________
# || 2 | 1 || 1 | 1 || 1 | 2 ||
# || 1 | 0 || 0 | 0 || 0 | 1 ||
# || 1 | 0 || 0 | 0 || 0 | 1 ||
else:
if not different:
if strike_dir == "Left" or strike_dir == "Right":
striker_difficulty = [0, 0, 1, 1, 1, 2]
goalie_difficulty = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2]
else:
striker_difficulty = [0, 0, 0, 0, 1, 1]
goalie_difficulty = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
if sc is None:
select_difficulty = choice(striker_difficulty)
else:
select_difficulty = sc # added for doc test
if gc is None:
goalie_choice = choice(goalie_difficulty)
else:
goalie_choice = gc # added for doc test
if select_difficulty == goalie_choice:
return "Save"
else:
return "Goal"
return "Goal"
if __name__ == '__main__':
# define number of runs
input_check = 1
while input_check == 1:
try:
program_run = int(input("Enter the number of times to repeat the entire program: "))
input_check = 0
except ValueError:
print('\nYou did not enter a valid integer')
# define the number of tests cases per scenario
input_check = 1
while input_check == 1:
try:
tests = int(input("Enter the number of test cases per scenario (preferably a larger value > 1000): "))
input_check = 0
except ValueError:
print('\nYou did not enter a valid integer')
# define a dataframe to store overall results
df = pd.DataFrame(columns=['Scenario 1', 'Scenario 2', 'Scenario 3'])
for i in range(0, program_run):
temp_result = []
print("Beginning Run ", (i + 1))
# SCENARIO 1: goal keeper jumps in random direction
# step 1: create 5 striker and 1 goalie
print("\nBeginning Scenario 1 - Goalie jumps in Random Direction")
print("-------------------------------------------------------")
Player(name='Player A')
Player(name='Player B')
Player(name='Player C')
Player(name='Player D')
Player(name='Player E')
Player(name='Goalie')
# step 2: run n scenarios where each player kicks in a random direction and goalie jumps in random direction
for match in range(tests):
# select a random player as kick_taker from the team and select goalie as goal_keeper
kick_taker = choice(Player.team)
goal_keeper = Player.keeper
# run the program for these two players and obtain the goalie's win % as a result
win_perc = goal_keeper.penalty_sim(match, kick_taker, tests, print_result=False, team=False,
consider_direction=False)
print("Number of penalties: ", tests, "\nGoals: ", goal_keeper.losses_case1, "\nSaves: ",
goal_keeper.wins_case1,
"\nGoalkeeper Success Rate: ", round(win_perc, 2), "%")
temp_result.append(win_perc)
print("Scenario 1 done\n\nStarting scenario 2 - Goalie jumps in Team's frequent kick direction")
print("-------------------------------------------------------")
# SCENARIO 2: goal keeper jumps in the direction of team's frequent shot direction
# clear goalie's statistics from scenario 1
(Player.keeper.wins_case1, Player.keeper.wins_case2, Player.keeper.wins_case3) = (0, 0, 0)
(Player.keeper.losses_case1, Player.keeper.losses_case2, Player.keeper.losses_case3) = (0, 0, 0)
(Player.keeper.count_r_total, Player.keeper.count_l_total, Player.keeper.count_m_total) = (0, 0, 0)
for match in range(tests):
kick_taker = choice(Player.team)
goal_keeper = Player.keeper
# run 5 tests to obtain enough data to start comparisons
if match < 5:
train = goal_keeper.penalty_sim(match, kick_taker, tests, print_result=False, team=True,
consider_direction=True)
else:
# run scenario for team stats and obtain goalie's win % as result
win_perc = goal_keeper.penalty_sim(match, kick_taker, tests, print_result=False, team=True,
consider_direction=True)
print("Number of penalties: ", tests, "\nGoals: ", goal_keeper.losses_case2, "\nSaves: ",
goal_keeper.wins_case2,
"\nGoalkeeper Success Rate: ", round(win_perc, 2), "%")
temp_result.append(win_perc)
print("Scenario 2 done\n\nStarting scenario 3 - Goalie jumps in Player's frequent kick direction")
print("-------------------------------------------------------")
# SCENARIO 3: goal keeper jumps in the direction the individual players' frequent shot direction
# clear goalie stats from scenario 2
(Player.keeper.wins_case1, Player.keeper.wins_case2, Player.keeper.wins_case3) = (0, 0, 0)
(Player.keeper.losses_case1, Player.keeper.losses_case2, Player.keeper.losses_case3) = (0, 0, 0)
(Player.keeper.count_r_total, Player.keeper.count_l_total, Player.keeper.count_m_total) = (0, 0, 0)
for match in range(tests):
kick_taker = choice(Player.team)
goal_keeper = Player.keeper
# run program for player stats and obtain goalie's win % as result
win_perc = goal_keeper.penalty_sim(match, kick_taker, tests, print_result=False, team=False,
consider_direction=True)
print("Number of penalties: ", tests, "\nGoals: ", goal_keeper.losses_case3, "\nSaves: ",
goal_keeper.wins_case3,
"\nGoalkeeper Success Rate: ", round(win_perc, 2), "%")
temp_result.append(win_perc)
print("Scenario 3 done")
print("-------------------------------------------------------\n\n")
# append values from all 3 scenarios to the dataframe
df = df.append(pd.Series(temp_result, index=df.columns), ignore_index=True)
df.loc['Average'] = df.iloc[[x for x in range(0, len(df.axes[0]) - 1)]].mean() # find average of all runs
df = df.round(2)
print(df)
# Output observations from the tests run above
print("\n\n***** Results *****\n")
print("Observation 1:\nIn Case 1 where the goalie and player both chose random directions, the goalie saved ",
df.loc['Average']['Scenario 1'], "% of the goals, on average.")
print(
"Observation 2:\nIn Case 2 where the goalie selected direction based on team's past 5 kicks and players choose "
"direction based on their individual tendency, the goalie saved ",
df.loc['Average']['Scenario 2'], "% of the goals, on average.\n\nConclusion 1: ")
diff_1and2 = df.loc['Average']['Scenario 2'] - df.loc['Average']['Scenario 1']
if diff_1and2 == 0: # no difference in results of scenario 1 and 2
print(
"There is no change in win % if the goalie knows the team's last 5 directions compared to the goalie "
"choosing random directions.")
elif diff_1and2 > 0: # increase in win % for scenario 2
print("There is an increase of ", format(diff_1and2, '.2f'),
"% if the goalie knows the team's last 5 directions compared to the goalie choosing random directions.")
else: # decrease in win % for scenario 2
print("There is an decrease of ", format(diff_1and2, '.2f'),
"% if the goalie knows the team's last 5 directions compared to the goalie choosing random directions.")
print(
"\nObservation 3:\nIn Case 3 where the goalie selected direction based on player's past 5 kicks and players "
"choose direction based on their individual tendency, the goalie saved ",
df.loc['Average']['Scenario 3'], "% of the goals, on average.\n\nConclusion 2:")
diff_1and3 = df.loc['Average']['Scenario 3'] - df.loc['Average']['Scenario 1']
if diff_1and3 == 0: # no difference in results of scenario 1 and 3
print(
"There is no change in win % if the goalie knows the player's last 5 directions compared to the goalie "
"choosing random directions.")
elif diff_1and3 > 0: # increase in win % for scenario 3
print("There is an increase of ", format(diff_1and3, '.2f'),
"% if the goalie knows the player's last 5 directions compared to the goalie choosing random directions.")
else: # decrease in win % for scenario 3
print("There is an decrease of ", format(diff_1and3, '.2f'),
"% if the goalie knows the player's last 5 directions compared to the goalie choosing random directions.")
# convert the data from dataframe in to a graph that shows the results of each run and the average across all runs
plt.rcParams["figure.figsize"] = 18, 13
df.index = np.arange(1, len(df) + 1)
as_list = df.index.tolist()
as_list[-1] = 'Average'
df.index = as_list
ax = df.plot.bar(rot=0)
plt.xlabel('Scenarios per Run and Average of Each Scenario over All Runs')
plt.ylabel('Win percentage of a Goalie')
plt.title("Plot of Goalie's win % over the 3 scenarios for each run")
print("\nA graph of the above observations is displayed in a separate window\nClose the Graph to end the program.")
plt.show()
|
def factorial(i):
if i>1 :
return i*factorial(i-1)
else :
return 1
i=int(input())
print(factorial(i)) |
import socket
import select
serversIP = ["192.168.0.101", "192.168.0.102", "192.168.0.103"]
serversSockets = []
clientsOpenedSockets = []
requestsQueue = []
isServerAvailable = {}
handledConnections = {}
def peekServer(serversList, msg):
if msg[0] == "P" or msg[0] == "V":
for s in serversList[0:2]:
if isServerAvailable[s]:
# print(msg, " to ", s.getpeername())
return s
if (msg[0] == "M"):
if isServerAvailable[serversList[2]]:
# print(msg, " to ", serversList[2].getpeername())
return serversList[2]
# default case - choose someone
for s in serversList:
if isServerAvailable[s]:
# print(msg, " to ", s.getpeername())
return s
# all servers are busy
return None
# connectiong to servers
for ip in serversIP:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (ip, 80)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)
serversSockets.append(sock)
isServerAvailable[sock] = True
# wait for clients
# Create a TCP/IP socket
listeningSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('10.0.0.1', 80)
print ('starting up on %s port %s' % server_address)
listeningSock.bind(server_address)
# Listen for incoming connections
listeningSock.listen(1)
while True:
readable, writable, _ = select.select(serversSockets + clientsOpenedSockets + [listeningSock], serversSockets, [])
# transfer response to clients
for read in readable:
if read is listeningSock:
# add new connection to list
connectionToClient, client_address = listeningSock.accept()
# connectionToClient.setblocking(0)
clientsOpenedSockets.append(connectionToClient)
elif read in clientsOpenedSockets:
# recieve request and store it in queue
data = connectionToClient.recv(2)
if data:
requestsQueue.append((read, data))
# else:
# if s in outputs:
# outputs.remove(s)
# inputs.remove(s)
# s.close()
# del message_queues[s]
else: #server socket
# send response to client
dataResponse = read.recv(2)
returnTo = handledConnections[read]
returnTo.send(dataResponse)
# print("server ", read.getpeername(), " free")
# notify that server is enable
isServerAvailable[read] = True
# remove connection and close it
clientsOpenedSockets.remove(returnTo)
returnTo.close()
if (writable):
if (requestsQueue):
# get next request
connection, msg = requestsQueue[0]
# need to choose wisely the server to send to
connectionToServer = peekServer(serversSockets, msg)
#send meassage from queue
if (connectionToServer is not None):
# remove next request from queue
requestsQueue.remove((connection, msg))
print("forward %s from: %s to server: %s" % (msg, connection.getpeername(), connectionToServer.getpeername()))
# handle request
handledConnections[connectionToServer] = connection
isServerAvailable[connectionToServer] = False
connectionToServer.send(msg)
|
import math
def check_decimal(num):
if(num==1):
return False
for i in range(2,int(math.sqrt(num))+1):
if(num%i==0):
return False
return True
if __name__=="__main__":
count=int(input())
result=0
numbers=[int(i) for i in input().split()]
for i in numbers:
if(check_decimal(i)):
result+=1
print(result) |
def zero_count_Combination(n,m):
f_num = 1
two_count = 0
five_count = 0
for i in range(m+1, n + 1):
while (i % 2 == 0):
two_count += 1
i=int(i/2)
while (i % 5 == 0):
five_count +=1
i = int(i / 5)
for i in range(2,n-m+1):
while (i % 2 == 0):
two_count -= 1
i=int(i/2)
while (i % 5 == 0):
five_count -=1
i = int(i / 5)
if(two_count<five_count):
return two_count
else:
return five_count
if __name__ == "__main__":
#nCm 조합 n!/(m!*(n-m)!)
n,m=[int(i) for i in input().split()]
print(zero_count_Combination(n,m)) |
'''Write a Python function to implement the quick sort algorithm over a singly linked list.
The input of your function should be a reference pointing to the first node of a linked list,
and the output of your function should also be a reference to the first node of a linked
list, in which the data have been sorted into the ascending order.'''
class Node:
def __init__(self, element):
self.element = element
self.pointer = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def is_empty(self):
return self.size == 0
def add(self, e):
new_node = Node(e)
if self.head == None:
self.head = new_node
else:
current = self.head
while current.pointer != None:
current = current.pointer
current.pointer = new_node
self.size += 1
# Move node to a new linked list
def move(self, node):
if self.head == None:
self.head = node
self.tail = node
else:
node.pointer = self.head
self.head = node
self.size += 1
def delete_head(self):
answer = self.head
self.head = self.head.pointer
self.size -= 1
if self.is_empty():
self.tail = None
return answer
# Delete current_node
def delete(self, previous, current):
previous.pointer = current.pointer
current.pointer = None
if current == self.tail:
self.tail = previous
self.size -= 1
return current
# "Glue" together a list with myList
def append(self, myList):
self.tail.pointer = myList.head
self.tail = myList.tail
self.size += myList.size
def __str__(self):
myList = []
node = self.head
while node != None:
myList.append(node.element)
node = node.pointer
return str(myList)
def quick_sort(myList):
if myList.size == 0 or myList.size == 1:
return myList
previous = myList.head
pivot = previous.element
current = previous.pointer
leftSide = LinkedList()
# Partition between left side and right side w.r.t. pivot
while current != None:
if current.element <= pivot:
current = myList.delete(previous, current)
leftSide.move(current)
else:
previous = current
current = previous.pointer
removed = myList.delete_head()
leftSide = quick_sort(leftSide)
rightSide = quick_sort(myList)
rightSide.move(removed)
# Return sorted list
if leftSide.is_empty(): # in case if the pivot is the smallest number
return rightSide
else:
leftSide.append(rightSide)
return leftSide
def main():
myList = LinkedList()
while True:
n = input("Please enter a number (or press any letter to stop):")
try:
n = float(n)
myList.add(n)
except ValueError:
print("Before sorting:", myList.__str__())
myList = quick_sort(myList)
print("After sorting:", myList.__str__())
try:
print("The first node of the list:", myList.head.element)
except AttributeError:
print("The list is empty.")
break
main()
|
for i in range(1, int(input()) + 1):
exercise = input().split()
if int(exercise[2]) > int(exercise[1]):
result = -1
elif int(exercise[2]) < int(exercise[0]):
result = int(exercise[0]) - int(exercise[2])
else:
result = 0
print("#%d %d" % (i, result)) |
from random import randint
numbers = []
# 수 생성
while len(numbers) < 3:
new_number = randint(0, 9)
while new_number in numbers:
new_number = randint(0, 9)
numbers.append(new_number)
print("0과 9 사이의 서로 다른 세 숫자를 랜덤한 순서로 뽑았습니다.")
# 숫자 입력받기
strike = 0
tries = 0
while strike < 3:
# 초기화
strike = 0
ball = 0
guess = []
n = 1
print("세 수를 하나씩 차례대로 입력하세요.")
while len(guess) < len(numbers):
user = int(input("%d 번째 수를 입력하세요." % n))
if user > 9 or user < 0:
print("범위를 벗어나는 수입니다. 다시 입력해 주세요.")
elif user in guess:
print("중복되는 수 입니다. 다시 입력해 주세요.")
else:
guess.append(user)
n = n + 1
tries += 1
# 볼카운트
for j in range(3):
if numbers[j] == guess[j]:
strike += 1
elif numbers[j] in guess:
ball += 1
print("%dS %dB" % (strike, ball))
print("축하합니다. %d번만에 세 숫자의 값과 위치를 모두 맞추셨습니다." % tries) |
text = input()
def uppercase():
return text.upper()
print(uppercase()) |
#!/usr/bin/env python
# From: http://people.ds.cam.ac.uk/mcj33/themagpi/The-MagPi-issue-29-en.pdf
from Tkinter import *
window = Tk()
window.title('GUI Tkinter 1')
window.geometry("300x250") # w x h
window.resizable(0,0)
#define labels
box1 = Label(window,text="Entry 1: ")
#place the label in the window object
box1.grid(row = 1, column = 1, padx = 5, pady = 5)
#define functions for button(s)
def btn1():
print ("button pressed")
#create button objects
btn_tog2 = Button(window, text ='button1', command=btn1)
btn_exit = Button(window, text ='exit',command=exit)
#place button objects
btn_tog2.grid(row = 1, column = 2, padx = 5, pady = 5)
btn_exit.grid(row = 2, column = 2, padx = 5, pady = 5)
#define labels
button1 = Label(window, text="click button")
button2 = Label(window, text="exit program")
#place labels
button1.grid(row = 1, column = 1, padx = 5, pady = 5)
button2.grid(row = 2, column = 1, padx = 5, pady = 5)
window.mainloop() |
count=0
temp=str=""
strs=[]
while str!="q":
str=input(f"请输入第{count + 1}个单词(输入q结束): ")
strs.append(str)
count+=1
print(f"排序前的结果为: {strs}")
print("-"*20+"\n")
for index,value in strs:
print(f"index:{index}")
print(f"value:{value}") |
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# for bicycle in bicycles:
# if bicycle == 'cannondale':
# print(bicycle.upper())
# else:
# print(bicycle)
# print("a" == "A")
#检查多个条件
# condition_1 and condition_2
#检查列表中特定值
# print('trek' in bicycles)
# age = 12
#
# if age<4:
# price = 0
# elif age <18:
# price = 5
# else:
# price = 10 #也可省略else,如加入剩余条件
#
# print(price)
# practice
# alien_color = ['green', 'yellow', 'red']
# if 'green' in alien_color:
# print("You got 5 points")
#确定列表非空
# if bicycles:
# print(1)
|
# with open('pi_digits.txt') as file_object:
# contents = file_object.read()
# print(contents) #末尾会多出一个空行,read()到达文件末尾会返回一个空字符串,形成空行,可用rstrip()消除
#可用相对路径和绝对路径,绝对路径可以存储在一个变量中再引用,因为太长不方便
#linux下用 / ,windows下用 \
file_name = 'pi_digits.txt'
#逐行读取
# with open(file_name) as file_object:
# for line in file_object:
# print(line)
#此时空白行更多,因为每行的末尾有一个换行符,print语句也会加一个换行符
# print(line.rstrip())
#readlines方法
# #创建包含各行内容的列表
# with open(file_name) as file_object:
# lines = file_object.readlines()
# for line in lines:
# print(line)
# pi_string = ''
# for line in lines:
# pi_string += line.rstrip()
#对于想处理的数据量,python没有要求,只要系统的内存足够多,想处理多少都可以
#写入文件
#写入空文件
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("i love programming")
#python只能将字符串写入文本文件,要写入数值的话,要先用str()转化成字符串格式
#写入多行
# file_object.write("i asdasd asdasd\n")
#添加内容,而不是覆盖
# with open(filename,'a') as file_object:
|
#列表生成式
list1 = [i for i in range(1,10,2)]
print(list1) |
# coding: utf-8
# ## Using Beautiful Soup to web scrape MLB statistics ##
# I will be adapting the excellent tutorial at [Nylon Calculus](http://nyloncalculus.com/2015/09/07/nylon-calculus-101-data-scraping-with-python/) to scrape stats from [baseball-reference.com](http://www.baseball-reference.com/leagues/MLB/bat.shtml). I'll start with annual stats for the entire league, and in this section I'll focus specifically on batting. I will repeat the procedure for pitching and then dive into individual player statistics.
# All of this is an exercise in web scraping and data cleaning as I prepare for my first year in a Fantasy Baseball league. It will likely be obvious I have no idea what I'm talking about at some points.
# We begin by importing the necesary modules and loading the webpage with our data into the magic that is BeautifulSoup.
# In[1]:
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
import datetime
def int_if_possible(string):
try:
return(int(string))
except:
return(string)
def team_batting_calc(teams=['CHW'], start=2016, end=2016):
batting_df = pd.DataFrame()
url_template = "http://www.baseball-reference.com/teams/{team}/{year}.shtml"
for tm in teams:
for year in range(start, end + 1):
team = tm
url = url_template.format(team=team, year=str(year))
html = urlopen(url)
soup = BeautifulSoup(html, 'lxml')
headers = soup.findAll('tr')[0].findAll('th')
column_headers = [th.getText() for th in headers[1:]]
data_rows = soup.findAll('tbody')[0].findAll('tr')
data_rows[0].findAll('td')[2].getText()
player_data = [[td.getText() for td in data_rows[i].findAll('td')]
for i in range(len(data_rows))]
player_data= int_if_possible(player_data)
player_df = pd.DataFrame(player_data, columns = column_headers)
player_df = player_df[player_df.Pos.notnull()]
player_df.insert(0, 'Year', year)
batting_df = batting_df.append(player_df, ignore_index=True)
#print(batting_df)
for i in batting_df.columns:
batting_df[i] = pd.to_numeric(batting_df[i], errors='ignore')
column_headers.insert(0,'Year')
batting_df = batting_df.reindex_axis(column_headers, axis = 1)
current_date = datetime.date.today()
writer = pd.ExcelWriter('br-data-by-team.xlsx')
batting_df.to_excel(writer,'{}'.format(current_date))
writer.save()
return(batting_df)
stl = team_batting_calc(teams=['STL'],start=2015, end = 2016)
stl['Year']
|
def my_list_sort(my_list):
x_list = []
r_list = []
for i in range(len(my_list)):
if my_list[i][0] == 'x':
x_list.append(my_list[i])
else:
r_list.append(my_list[i])
r_list.sort()
x_list.sort()
return x_list + r_list
print(my_list_sort(['bbb', 'ccc', 'axx', 'xzz', 'xaa']))
print(my_list_sort(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']))
|
# New Patterns by Kalyn Beach
import turtle;
# Create a blue pen and determine the window's width and height:def init():
def init():
pen = turtle.Pen();
pen.color(0, 0, 1); # blue
width = pen.window_width();
height = pen.window_height();
return pen, width, height;
# Given a number, design a pattern:
def pattern(number): # Example: pattern(5);
pen, w, h = init();
# Switch off tracing for higher speed:
pen.tracer(False);
for x in range(-w/2, +w/2):
for y in range (-h/2, +h/2):
draw(pen, number, x, y);
# Temporarily switch on tracing to observe drawing:
if (x % 100 == 0):
pen.tracer(True); pen.tracer(False);
pen.tracer(True);
# If this program freezes on a Mac, add the following line:
#turtle._root.mainloop();
# Draw a pattern element at point (x, y):
def draw(pen, number, x, y):
a = y * (number / 100.0);
b = x * (number / 100.0);
ez = int(a*a+(b*a) + b*b+(a*b));
# Try ez = int(a*a + b*b) and other expressions.
if (ez % 2 == 0):
pen.up(); pen.goto(x, y); pen.down();
pen.circle(1);
#pattern(5);
|
# Seconds Calculations by Kalyn Beach
# Convert hours, minutes, and seconds to seconds using a pretest loop:
def secondsPretest():
ans = raw_input('Ready to convert? [Yes/No]: ');
while (ans == 'Yes' or ans == 'yes' or ans == 'Y' or ans == 'y'):
while (True):
hours = input("Enter hours (non-nagetive): ");
if (0 <= hours): break;
while (True):
minutes = input("Enter minutes (0..59): ");
if (0 <= minutes < 60): break;
while (True):
seconds = input("Enter seconds (0..59): ");
if (0 <= seconds < 60): break;
secondsTotal = seconds + (60 * minutes) + (3600 * hours);
print "The total time is ", secondsTotal, "seconds.";
ans = raw_input('Convert more? [Yes/No]: ');
print "So long...";
# Convert hours, minutes, and seconds to seconds using a interrupted loop:
def secondsInterrupted():
while (True):
while (True):
hours = input("Enter number of hours (non-negative): ");
if (0 <= hours): break;
while (True):
minutes = input("Enter minutes (0..59): ");
if (0 <= minutes < 60): break;
while (True):
seconds = input("Enter seconds (0..59): ");
if (0 <= seconds < 60): break;
secondsTotal = seconds + (60 * minutes) + (3600 * hours);
print "The total time is ", secondsTotal, "seconds.";
ans = raw_input('Convert more? [Yes/No]: ');
if (ans == "No" or ans == "no"): break;
print "So long...";
|
# Dean's List Evaluator by Kalyn Beach
# Given a grade, calculate the student's GPA and determine if the student made
# the Dean's list:
def list():
gradeA = input("Enter number of A's: ");
gradeB = input("Enter number of B's: ");
gradeC = input("Enter number of C's: ");
gradeD = input("Enter number of D's: ");
gradeF = input("Enter number of F's: ");
gpaA = gradeA * 4.0;
gpaB = gradeB * 3.0;
gpaC = gradeC * 2.0;
gpaD = gradeD * 1.0;
gpaF = gradeF * 0.0;
gpa = (gpaA + gpaB + gpaC + gpaD + gpaF) / (gradeA + gradeB + gradeC + gradeD + gradeF);
if (gpa >= 3.5):
evaluation = "You made it to the Dean's List!";
else:
evaluation = "You cannot make it to the Dean's List.";
print "GPA is ", gpa;
print evaluation;
|
# Sum Evaluator by Kalyn Beach
def sumTotal(a, b):
theSum = 0;
while (a <= b):
theSum = theSum + a;
a = a + 1;
return theSum;
def repeat():
print "This program sums up sequences of numbers."
while (True):
bottom = input("Enter sequence bottom: ");
top = input("Enter sequence top: ");
theSum = sumTotal(a = bottom, b = top);
print "Bottom:", bottom, "Top:", top;
print "Sum: ", theSum;
ans = raw_input("Sum up more? [Yes/No]: ");
if(ans == "No" or ans == "no"): break;
print "Bye.";
|
list = [1,2,3,4,5,6]
for num in list:
if num > 4:
print(num, 'число > 4')
else:
print(num)
list.append(input('введите число'))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Task 6: Classifier. (bonus)
# Take a dict with values of different type, return a dict of type:
# {value_type: number_of_elements_of_that_type}.
# {'a': 1, 3: [1,5], 'e': 'abc', '6': []} >> {'str': 1, 'list': 2, 'int': 1}
def classificator(d):
counts = dict()
for val in d.values():
key = type(val).__name__
counts[key] = counts.get(key, 0) + 1
return counts
# Test
if __name__ == '__main__':
assert classificator({'a': 1, 3: [1,5], 'e': 'abc', '6': []}) == \
{'str': 1, 'list': 2, 'int': 1}
print 'OK!'
|
# -*- coding: utf-8 -*-
import csv
import os
from hw5_solution import Person
def modifier(fname):
"""Add fullname and age columns to a CSV file."""
fhand = open(fname, 'r')
dictreader = csv.DictReader(fhand)
fout = open('temp', 'w')
fields = dictreader.fieldnames[:]
fields.insert(3, 'fullname')
fields.append('age')
writer = csv.DictWriter(fout, fieldnames=fields)
writer.writeheader()
for row in dictreader:
surname = row['surname']
first_name = row['name']
birth_date = row['birthdate']
nickname = row['nickname']
person = Person(surname, first_name, birth_date, nickname)
row['fullname'] = person.get_fullname()
row['age'] = person.get_age()
writer.writerow(row)
fhand.close()
fout.close()
os.rename('temp', fname)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Task 4: Odd-even.
# Take a list of any numbers and filter it:
# - remove odd numbers if the number of elements in the list is even;
# - remove even numbers if the number of elements in the list is odd.
# [3, 7, 12] >> [3, 7]
# [3, 7, 12, 7] >> [12]
def odd_even(t):
if len(t)%2 != 0:
new_t = [i for i in t if i%2 != 0]
else:
new_t = [i for i in t if i%2 == 0]
return new_t
# Test
if __name__ == '__main__':
assert odd_even([3, 7, 12]) == [3, 7]
assert odd_even([3, 7, 12, 7]) == [12]
print 'OK!'
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 19:44:40 2019
@author: Pale
"""
dict1={0:'Zero',1:'One',2:'Two',3:'Three',4:'four',\
5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
n=input("Enter number= ")
for i in n:
print( dict1[ord(i)-48],end=" ")
print() |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 08:20:26 2019
@author: Pale
"""
s1="***a barking dog\doesn\'t bite a man***"
print(s1)
s1.split()
s1.replace('dog','cat')
s1.find('barking')
s1.find('Barking')
s1.strip('*')
s1.rstrip('*')
"*".join("123")
"hello".center(30)
"hello how are you".title() |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 19:37:26 2019
@author: Pale
"""
def Stars(rows):
n=0
for i in range(1,rows+1):
for j in range(1,(rows-i)+1):
print(end=" ")
while n!=(2*i-1):
print("*", end="")
n=n+1
n=0
print()
k=1
n=1
for i in range(1,rows):
for j in range(1,k+1):
print(end=" ")
k=k+1
while n<=(2*(rows-i)-1):
print("*",end="")
n=n+1
n=1
print()
rows=int(input("Enter number of rows: "))
Stars(rows)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 20:17:38 2019
@author: Pale
"""
income=float(input("Enter Income:"))
familysize=int(input("Enter family size:"))
if (income>=500000):
tax=income*0.3
print("Tax =",tax)
if (income<500000) and (income>=100000):
if(familysize>3):
tax=income*0.15
print("Tax =",tax)
if(familysize<=3):
tax=income*0.2
print("Tax =",tax)
if (income<100000) and (income>=30000):
if(familysize>=5):
tax=income*0.05
print("Tax =",tax)
if(familysize>=3) and (familysize<5):
tax=income*0.07
print("Tax =",tax)
if(familysize<3):
tax=income*0.1
print("Tax =",tax)
if (income<30000) :
print("Not Tax!")
print("End!")
|
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 23:25:42 2019
@author: Pale
"""
name=input("Type your name: ")
print('Hi, I have seen you before:'+name.upper()+'!\n')
len_name=len(name)
print("The length of your name is:"+str((len_name))+'\n')
name_f3=name[0:3]
print('The first 3 letters of your name are: '+name_f3.upper()+'\n')
name_l3=name[-3:]
print('The last 3 letters in your name are: '+name_l3.upper()+'\n')
print("Goodbye!") |
#!/usr/bin/python3
if __name__ == "__main__":
import sys
argv = sys.argv[1:]
argv_count = len(argv)
index = 1
if argv_count == 0:
print("{} arguments.".format(argv_count))
elif argv_count == 1:
print("{} argument:".format(argv_count))
print("{}: {}".format(index, sys.argv[1]))
else:
print("{} arguments:".format(argv_count))
while index <= argv_count:
print("{}: {}".format(index, sys.argv[index]))
index += 1
|
# coding:utf-8
from functools import partial
from itertools import groupby
import itertools
import re
ss = '111221'
def countAndSay(self, n):
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(list(group))) + digit
for digit, group in itertools.groupby(s))
return s
for digit, group in itertools.groupby('111221'):
print(digit, group)
print(list(group))
print(re.findall(r'((.)\2*)', ss))
def fun(n):
s = '1'
for _ in range(n - 1):
s = re.sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s)
return s
def repeatedSubstringPattern(str):
"""
:type str: str
:rtype: bool
"""
if not str:
return False
# print((str + str))
ss = (str + str)[1:-1]
# print(ss)
return ss.find(str) != -1
print(repeatedSubstringPattern('abcabcabc'))
# abab abcabc aaa abcabcab
# abab
# abababab
# bababa
# abcabcd str
# abcabcdabcabcd str + trs
# bcabcdabcabc ss
ss = 'abcabcabc'
# print(re.findall(r'(.)\1*', ss))
from string import ascii_uppercase
def titleToNumber(s):
"""
:type s: str
:rtype: int
"""
s = reversed(s.upper())
print(ascii_uppercase)
dct = {v:k for k, v in enumerate(ascii_uppercase, start=1)}
return sum([(26**idx)*dct[i] for idx, i in enumerate(s)])
# print(titleToNumber('ZY'))
lst = [1, 2, 2, 2, 3, 4, 5]
def removeElement(nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
ret = [i for i in nums if i != val]
return ret, len(ret)
# print(removeElement([3,2,2,3, 2, 3, 4, 5], 3))
nums = [3, 2, 4]
target = 6
from copy import copy
for idx, i in enumerate(nums):
ret = (target - i)
temp = copy(nums)
temp.pop(idx)
if ret in temp:
print([idx, temp.index(ret) + 1] if ret == i else [idx, nums.index(ret)])
|
import abc
__author__ = 'Jubril'
class Room(object):
__metaclass__ = abc.ABCMeta
max_occupants = 4
def __init__(self, name):
self.name = name
self.occupants = []
def get_member_details(self):
"""
Get the details of the occupants in a room
:return: occupants
"""
return self.occupants
def is_room_filled(self):
"""
This method checks if the room is filled
:return: Boolean
"""
if len(self.occupants) >= self.max_occupants:
return True
else:
return False
def has_no_occupant(self):
"""
This method checks if the current room has any occupants
:return: Boolean
"""
if len(self.occupants) > 0:
return True
else:
return False
class LivingSpace(Room):
def __repr__(self):
return self.name
def __eq__(self, obj):
return self.name == obj.name
class Office(Room):
max_occupants = 6
def __repr__(self):
return self.name
def __eq__(self, obj):
return self.name == obj.name
|
student_list = []
str = "a b c d e f g h i j k l m n o p q r s t".split(" ")
for index in range(len(str)):
student_list.append(str[index])
print(student_list)
for names in student_list:
if names == 'b':
print(f"found {names}")
break
print(f"currently testing :: {names}")
for names in student_list:
if names == "c":
continue
print("testing ::" + names)
x = 0
while x < 10:
print("Hello While iteration : ", x)
x += 1
|
print('Hello world')
bonus = (0.10 or 0.15)
if sales > 1000:
bonus = 1000 * 0.10
elif sales < 1000:
bonus = 1000 * 0.15
print(sales)
while sales >= 1000:
bonus = 1000 * 0.10 or 1000 * 0.15
print(sales)
|
import time
while True:
inp = input('Give your input or END: ')
t=time.time()%10
if inp=='END':
exit()
if t>=0 and t<3:
print('rock')
elif t>=3 and t<7:
print('paper')
else:
print('scissor') |
def add_time(start, duration, day_name=None):
day_count = 0
name_in_week = {
1: 'Saturday',
2: 'Sunday',
3: 'Monday',
4: 'Tuesday',
5: 'Wednesday',
6: 'Thursday',
7: 'Friday'
}
start_time_list = start.split()
hour = int(start_time_list[0].split(':')[0])
minute = int(start_time_list[0].split(':')[1])
time_meridian = start_time_list[1].upper()
duration_hour = int(duration.split(':')[0])
duration_minute = int(duration.split(':')[1])
# print(hour, minute, time_meridian)
# print(duration_hour, duration_minute)
if duration_hour >= 24:
day_count = duration_hour // 24
duration_hour = duration_hour % 24
new_hour = hour + duration_hour
new_minute = minute + duration_minute
# print(new_hour, new_minute, time_meridian)
if new_minute > 60:
new_hour += new_minute // 60
new_minute = new_minute % 60
# print(new_hour, new_minute, time_meridian)
if new_hour >= 12:
if new_hour > 24:
day_count += new_hour // 24
# print(new_hour)
if new_hour % 12 == 0:
new_hour = 12
else:
new_hour %= 12
# print(new_hour, new_minute, time_meridian)
if time_meridian == 'AM' and (duration_hour != 24 and duration_minute != 0):
time_meridian = 'PM'
elif time_meridian == 'PM' and (duration_hour != 24 and duration_minute != 0):
time_meridian = 'AM'
day_count += 1
# print(day_count)
# print(new_hour, new_minute, time_meridian)
new_time = '{:d}:{:02d} {time_meridian}'.format(new_hour, new_minute, time_meridian=time_meridian)
if day_name:
key = [k for k, v in name_in_week.items() if v == day_name.capitalize()][0]
key += day_count
if key % 7 == 0:
key = 7
else:
key %= 7
# print(key)
new_day_name = name_in_week[key]
new_time += f', {new_day_name}'
if day_count != 0:
if day_count == 1:
new_time += ' (next day)'
else:
new_time += f' ({day_count} days later)'
return new_time |
import math
import random
import sys
from asteroid import Asteroid
from screen import Screen
from ship import Ship
from torpedo import Torpedo
DEFAULT_ASTEROIDS_NUM = 5
ROTATION = 7
ASTEROID_SIZE = 3
AST_SPEED = [-4, -3, -2, -1, 1, 2, 3, 4]
DEFAULT_LIFE = 3
TORPEDO_LIFETIME = 200
SCORE_MARKERS = {
1: 100, # small asteroid
2: 50, # med asteroid
3: 20 # large asteroid
}
MAX_TORPEDO = 10
def calc_new_spot(screen_min, screen_max, old_spot, speed):
"""
This function calculate the new location of for our object.
:param screen_min: The min value of the screen i.e the coord of the bottom of the screen.
:param screen_max: The max value of the screen i.e the coord of the top of the screen.
:param old_spot: float or int. The coordinate that we want to calculate x or y it is symmetric.
:param speed: float or int. The speed in the x or y direction, it is symmetric.
:return: type int or float, representing our new coordinate according to input.
"""
delta = screen_max - screen_min
return screen_min + (old_spot + speed - screen_min) % delta
def accelerate_object(obj):
"""
calculate new speed of obj after acceleration.
:param obj: object like ship or asteroid or torpedo
:return: None, this will change the objects property.
"""
speed = obj.get_speed()
heading = math.radians(obj.get_angle())
new_speed = (speed[0] + math.cos(heading), speed[1] + math.sin(heading))
obj.change_speed(new_speed)
class GameRunner:
"""
This class runs the game.
params:
__screen_max_x The coordinate of the right of the screen.
__screen_max_y The coordinate of the top of the screen.
__screen_min_x The coordinate of the left of the screen.
__screen_min_y The coordinate of the bottom of the screen.
__screen type Screen the screen that the game is ran on.
__score type int The current score fo the player.
__lives type int The number of lives remaining for the player.
__torpedos type dict of torpedos with ints as keys.
The keys represent the game tick when the torpedo should be deleted.
__counter type int The current tick of the game.
__ship type Ship The ship the player will manipulate.
__asteroids type list of Asteroids. Keeps track of all the asteroids on the screen.
"""
def __init__(self, asteroids_amount):
"""
inits a new game.
:param asteroids_amount: The number of asteroids to be created.
"""
self.__screen = Screen()
self.__score = 0
self.__screen_max_x = Screen.SCREEN_MAX_X
self.__screen_max_y = Screen.SCREEN_MAX_Y
self.__screen_min_x = Screen.SCREEN_MIN_X
self.__screen_min_y = Screen.SCREEN_MIN_Y
# get random coordinates.
random_x, random_y = self.random_location()
self.__lives = DEFAULT_LIFE
self.__torpedos = {}
self.__counter = 0
self.__ship = Ship((random_x, 0), (random_y, 0), 0)
self.__asteroids = []
self.create_asteroids(asteroids_amount)
def create_asteroids(self, asteroids_amount):
"""
This function creates all the asteroids such that they do not collide with the ship.
:param asteroids_amount: The number of asteroids to be created.
:return: None the function changes self.__asteroids and self._screen.
"""
for i in range(asteroids_amount):
asteroid = self.create_asteroid()
# check if location of asteroid not crash with the ship
while asteroid.has_intersecion(self.__ship):
asteroid = self.create_asteroid()
# add the now asteroid to our internal list, and to self.__screen.
self.__asteroids.append(asteroid)
self.__screen.register_asteroid(asteroid, ASTEROID_SIZE)
def run(self):
self._do_loop()
self.__screen.start_screen()
def _do_loop(self):
# You should not to change this method!
self._game_loop()
# Set the timer to go off again
self.__screen.update()
self.__screen.ontimer(self._do_loop, 5)
def _game_loop(self):
self.__counter += 1
# turn the ship
self.turn()
# accelerate the ship.
self.accelerate()
# formats our data to the required format
to_func = (*self.__ship.get_cordinates()), self.__ship.get_angle()
self.__screen.draw_ship(*to_func) # draws ship
# manage the torpedo and asteroids.
self.torpedo_managere()
self.print_asteroid()
# check if we have won i.e 0 asteroids on the screen
if len(self.__asteroids) == 0:
msg = f"Congratulations you won! You ended the game with {self.__lives} lives and {self.__score} points"
self.game_over("Congratulations", msg)
# checks if the user wants to end the game
if self.__screen.should_end():
msg = f"Good bye, sad to see you leave. You have finished the game with " \
f"{self.__lives} lives and {self.__score} points"
self.game_over("Good bye", msg)
def game_over(self, over_massage, msg):
"""This function is called when we want to end the game.
:param over_massage: the Title of the message.
:param msg: The message to print.
:return None"""
self.__screen.show_message(over_massage, msg)
self.__screen.end_game()
sys.exit()
def astoids_torp_col_check(self, torp):
"""This function checks if a given torpedo collides with one of the asteroids.
:param torp: The torpedo we will check for collisions
:return True if there was a collision, False otherwise.
"""
for astro in self.__asteroids:
if astro.has_intersecion(torp):
astro_size = astro.get_size()
# if we need to split the asteroid
if astro_size > 1:
self.split_asteroid(astro, torp)
# add the score
self.__score += SCORE_MARKERS[astro_size]
self.__screen.set_score(self.__score) # changes current score
# removes the old asteroid
self.__screen.unregister_asteroid(astro)
self.__asteroids.remove(astro)
return True
return False
def split_asteroid(self, asteroid, torpedo):
"""This function does all the pre-computing for a collision.
:param asteroid: The asteroid we want to remove.
:param torpedo: The torpedo that hit the asteroid.
:return None we will change self.__asteroids """
coords = asteroid.get_cordinates()
# get asteroid speed for x and y
old_as_spx, old_as_spy = asteroid.get_speed()
# get torpedo speed
torp_speedx, torp_speedy = torpedo.get_speed()
# get the magnitude of the speeds
norma = math.sqrt(old_as_spx ** 2 + old_as_spy ** 2)
# get new speed according to formula
new_as_speed_x = (torp_speedx + old_as_spx) / norma
new_as_speed_y = (torp_speedy + old_as_spy) / norma
new_size = asteroid.get_size() - 1
# creates two new asteroids according to parameters above
new_as_1 = Asteroid((coords[0], new_as_speed_x), (coords[1], new_as_speed_y), new_size)
new_as_2 = Asteroid((coords[0], -1 * new_as_speed_x), (coords[1], -1 * new_as_speed_y), new_size)
# add the asteroids to the screen
self.__screen.register_asteroid(new_as_1, new_size)
self.__screen.register_asteroid(new_as_2, new_size)
self.__asteroids += [new_as_1, new_as_2] # add to internal list
def torpedo_managere(self):
"""This function manages the toledo i.e creates them and deletes them and draws them,
and manages collisions with asteroids. """
# if the user wants to shoot.
if self.__screen.is_space_pressed() and len(self.__torpedos) < MAX_TORPEDO:
self.create_torpedo()
# if we need to remove a torpedo
if self.__counter in self.__torpedos:
self.__screen.unregister_torpedo(self.__torpedos[self.__counter]) # removes the current expired torpedo
self.__torpedos.pop(self.__counter) # remove from out list
col_torps = [] # This will store the key of the torpedo that had collisions.
# moves all our torpedo
for torp in self.__torpedos.values():
self.change_location_object(torp)
# check for collisions with al the asteroids
if self.astoids_torp_col_check(torp):
# get the key of the current torpedo
key = list(self.__torpedos.keys())[list(self.__torpedos.values()).index(torp)]
col_torps.append(key)
x_loc, y_loc = torp.get_cordinates()
angle = torp.get_angle()
self.__screen.draw_torpedo(torp, x_loc, y_loc, angle)
# remove all the collision torpedo
for inde in col_torps:
# gets and removes the throed from interior dict
torp = self.__torpedos.pop(inde)
self.__screen.unregister_torpedo(torp)
def create_torpedo(self):
"""This function shoots a torpedo.
:return None
"""
x_speed, y_speed = self.__ship.get_speed()
x_coord, y_coord = self.__ship.get_cordinates()
angle = math.radians((self.__ship.get_angle()))
torpedo_x = (x_coord, x_speed + 2 * math.cos(angle))
torpedo_y = (y_coord, y_speed + 2 * math.sin(angle))
# creates the torpedo
torp = Torpedo(torpedo_x, torpedo_y, angle)
# adds the torpedo to the dict with current tick + Torp_life_time = 200 as the key
self.__torpedos[self.__counter + TORPEDO_LIFETIME] = torp
self.__screen.register_torpedo(torp)
def create_asteroid(self):
"""This function creates a random asteroid according the the requirements.
:return Asteroid, the random asteroid created"""
# get random x, y coords
random_x, random_y = self.random_location()
# create the random accelerating params.
random_accelerate_x, random_accelerate_y = random.choice(AST_SPEED), random.choice(AST_SPEED)
asteroid = Asteroid((random_x, random_accelerate_x), (random_y, random_accelerate_y), ASTEROID_SIZE)
return asteroid
def random_location(self):
"""This function creates two random x y coords, in the screen.
:return: random_x, random_y two floats
"""
random_x = random.randint(self.__screen_min_x, self.__screen_max_x) # get random value for x coordinate
random_y = random.randint(self.__screen_min_y, self.__screen_max_y) # get random value for y coordinate
return random_x, random_y
def turn(self):
"""This function turns the ship.
:return None, it changes the ship"""
if self.__screen.is_right_pressed():
angle = self.__ship.get_angle()
self.__ship.change_angle(angle - ROTATION)
# maybe this will cause problems with if and not elif
if self.__screen.is_left_pressed():
angle = self.__ship.get_angle()
self.__ship.change_angle(angle + ROTATION)
def print_asteroid(self, if_col=False):
"""
This function prints all our asteroids, it also moves them and checks for collisions with the ship.
:param if_col: bool if there was a collision.:
:return: None
"""
ind = 0
for astro in self.__asteroids:
self.change_location_object(astro)
# draw the asteroid
self.__screen.draw_asteroid(astro, *astro.get_cordinates())
# check for collision with ship
if astro.has_intersecion(self.__ship):
if_col = True
ind = self.__asteroids.index(astro)
# if there was a collision with the ship
if if_col:
self.__screen.show_message("You hit a asteroid", "You lose 1 life")
self.__screen.remove_life()
self.__lives -= 1
astro = self.__asteroids.pop(ind)
self.__screen.unregister_asteroid(astro)
# if the user has no remaining lives
if self.__lives == 0:
self.game_over("Game over", "You have run out of lives, so you lose.")
def accelerate(self):
"""This function accelerates the ship."""
if self.__screen.is_up_pressed():
# accelerate the ship
accelerate_object(self.__ship)
self.change_location_object(self.__ship)
def change_location_object(self, obj):
"""
this function changes the location of the object.
:param obj: object like ship or asteroid or torpedo
:return: None
"""
speed, coords = obj.get_speed(), obj.get_cordinates()
# get the new x,y coords.
new_spot_x = calc_new_spot(self.__screen_min_x, self.__screen_max_x, coords[0], speed[0])
new_spot_y = calc_new_spot(self.__screen_min_y, self.__screen_max_y, coords[1], speed[1])
obj.change_coords((new_spot_x, new_spot_y))
def main(amount):
runner = GameRunner(amount)
runner.run()
if __name__ == "__main__":
if len(sys.argv) > 1:
try:
main(int(sys.argv[1]))
# if the input is not a integer
except ValueError:
pass
else:
main(DEFAULT_ASTEROIDS_NUM)
|
#############################################################
# LOGIN : volberstan
# ID NUMBER : 206136749
# WRITER : elchanan volbersten
# I discussed the exercise with : chaim goldblat
# Internet pages I looked for : wikipedia
##############################################################
import math
def golden_ratio():
print( (1+5**0.5)/2)
def six_squared():
print(6**2)
def hypotenuse():
print ((12**2+5**2)**0.5)
def pi():
print(math.pi)
def e():
print(math.e)
def squares_area():
print(1*1,2*2,3*3,4*4,5*5,6*6,7*7,8*8,9*9,10*10)
if __name__ == "__main__":
golden_ratio()
six_squared()
hypotenuse()
pi()
e()
squares_area()
#for i in range(1, 11):
# squared = str(i ** 2);
# nums = nums + squared + ", "
#print nums |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.