text stringlengths 37 1.41M |
|---|
''' password validation in python code'''
import re
def check_valid_password(password):
while True:
if len(password) < 8:
return "Make sure your password is at least 8 letters"
elif re.search('[0-9]', password) is None:
return "Make sure your password has a number in it"
elif re.search('[A-Z]', password) is None:
return "Make sure your password has a capital letter in it"
else:
return password
break
password = input("Enter a password: ")
output = check_valid_password(password)
print(output) |
# def my_repeat(data, times):
# i = 1
# record = []
# while i <= times:
# record.append(data)
#
# i += 1
#
# return record
#
#
# obj = my_repeat('admin', 10)
def my_repeat(data, times):
return data * times
print(my_repeat('admin', 10))
|
# Программа отбирающая файлы с датой позже чем заданная
import os
# Запрос исходных данных: путь к корневой папке и дата после которой
# были созданы файлы
path = input("Введите путь к иследуемой папке с файлами: ")
date_file = input("Дата последних изменений файлов: ")
# Получаем перечень всех файло и папок
list_file = list(os.walk(path))
list1 = []
for item_generly in list_file:
for file_item in item_generly[2]:
list1.append(file_item)
print(list1)
# Проходим по всем файлам каждой папки
# дата создания позже заданой даты
# Если да, то сохраняем в файл с путем от корневой паки проекта
# Если нет проверяем следующий файл
# Если папки и файлы закончились, выдаем сообщение об окончании |
import heapq
class ParkingSpot:
def __init__(self, floor, spot):
self.floor = floor
self.spot = spot
def __lt__(self, other):
# For heapify
if self.floor == other.floor:
return self.spot < other.spot
else:
return self.floor < other.floor
class ParkingLot:
def __init__(self):
l = [] # dummy data
for i in range(1,3):
for j in range(1,5):
l.append(ParkingSpot(i, j))
self.parkingLot = l# all the spots contains an array of all the Spot objects
self.pqueue = [] # to store the empty spots
self.occupied = set() # to store the spots which are occupied
for i in self.parkingLot:
heapq.heappush(self.pqueue, i)
def park(self):
# Time Complexity : O(log n) where n is the number of empty spots available
spot = heapq.heappop(self.pqueue)
self.occupied.add(spot)
return spot
def unpark(self, spot): # if they give me the floor number and spot number then create a object of parkingspot and use that for the set and queue
# Instead of creating the object again, we can store the floornumber_spotnumber as a key in the dictionary instead of a hashset just storing the objects
# In the dictionary key is the floornumber_spotnumber and the value is the ParkingSpot object
# Time Complexity : O(log n) where n is the number of empty spots available. Whenever we push or pop to a priority queue, heapify happens and that take O(log n) complexity
self.occupied.remove(spot)
heapq.heappush(self.pqueue, spot)
if __name__ == '__main__':
pl = ParkingLot()
sp1 = pl.park()
print(sp1.floor, sp1.spot)
sp2 = pl.park()
print(sp2.floor, sp2.spot)
sp3 = pl.park()
print(sp3.floor, sp3.spot)
pl.unpark(sp1)
sp4 = pl.park()
print(sp4.floor, sp4.spot) |
#!/usr/bin/env python
"""circuits Hello World"""
from circuits import Component, Event
class hello(Event):
"""hello Event"""
class App(Component):
def hello(self):
"""Hello Event Handler"""
return "Hello World!"
def started(self, component):
"""
Started Event Handler
This is fired internally when your application starts up and can be used to
trigger events that only occur once during startup.
"""
x = self.fire(hello()) # Fire hello Event
yield self.wait("hello") # Wait for Hello Event to fire
print(x.value) # Print the value we got back from firing Hello
raise SystemExit(0) # Terminate the Application
def main():
App().run()
if __name__ == "__main__":
main()
|
"""
VirtualHost
This module implements a virtual host dispatcher that sends requests
for configured virtual hosts to different dispatchers.
"""
from urllib.parse import urljoin
from circuits import BaseComponent, handler
class VirtualHosts(BaseComponent):
"""
Forward to anotehr Dispatcher based on the Host header.
This can be useful when running multiple sites within one server.
It allows several domains to point to different parts of a single
website structure. For example:
- http://www.domain.example -> /
- http://www.domain2.example -> /domain2
- http://www.domain2.example:443 -> /secure
:param domains: a dict of {host header value: virtual prefix} pairs.
:type domains: dict
The incoming "Host" request header is looked up in this dict,
and, if a match is found, the corresponding "virtual prefix"
value will be prepended to the URL path before passing the
request onto the next dispatcher.
Note that you often need separate entries for "example.com"
and "www.example.com". In addition, "Host" headers may contain
the port number.
"""
channel = "web"
def __init__(self, domains):
super().__init__()
self.domains = domains
@handler("request", priority=1.0)
def _on_request(self, event, request, response):
path = request.path.strip("/")
header = request.headers.get
domain = header("X-Forwarded-Host", header("Host", ""))
prefix = self.domains.get(domain, "")
if prefix:
path = urljoin("/%s/" % prefix, path)
request.path = path
|
"""
Session Components
This module implements Session Components that can be used to store
and access persistent information.
"""
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from hashlib import sha1 as sha
from uuid import uuid4 as uuid
from circuits import Component, handler
def who(request, encoding="utf-8"):
"""Create a SHA1 Hash of the User's IP Address and User-Agent"""
ip = request.remote.ip
agent = request.headers.get("User-Agent", "")
return sha(f"{ip}{agent}".encode(encoding)).hexdigest()
def create_session(request):
"""
Create a unique session id from the request
Returns a unique session using ``uuid4()`` and a ``sha1()`` hash
of the users IP Address and User Agent in the form of ``sid/who``.
"""
return f"{uuid().hex}/{who(request)}"
def verify_session(request, sid):
"""
Verify a User's Session
This verifies the User's Session by verifying the SHA1 Hash
of the User's IP Address and User-Agent match the provided
Session ID.
"""
if "/" not in sid:
return create_session(request)
user = sid.split("/", 1)[1]
if user != who(request):
return create_session(request)
return sid
class Session(dict):
def __init__(self, sid, data, store):
super().__init__(data)
self._sid = sid
self._store = store
@property
def sid(self):
return self._sid
@property
def store(self):
return self._store
def expire(self):
self.store.delete(self.sid)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
self.store.save(self.sid, self)
class Store(metaclass=ABCMeta):
@abstractmethod
def delete(self, sid):
"""Delete the session data identified by sid"""
@abstractmethod
def load(self, sid):
"""Load the session data identified by sid"""
@abstractmethod
def save(self, sid):
"""Save the session data identified by sid"""
class MemoryStore(Store):
def __init__(self):
self._data = defaultdict(dict)
@property
def data(self):
return self._data
def delete(self, sid):
del self.data[sid]
def load(self, sid):
return Session(sid, self.data[sid], self)
def save(self, sid, data):
self.data[sid] = data
class Sessions(Component):
channel = "web"
def __init__(self, name="circuits", store=MemoryStore, channel=channel):
super().__init__(channel=channel)
self._name = name
self._store = store()
@property
def name(self):
return self._name
@property
def store(self):
return self._store
@handler("request", priority=10)
def request(self, request, response):
if self.name in request.cookie:
sid = request.cookie[self._name].value
sid = verify_session(request, sid)
else:
sid = create_session(request)
request.session = self.store.load(sid)
response.cookie[self.name] = sid
|
"""
Author: Rajiv Malhotra
Program: sort_and_search_array.py
Date: 10/11/20
Search and Sort Array Assignment
"""
import array as arr
def search_array(n_array, a_value):
"""
Function searches for a value in the Array and returns the index value. -1 if not found
:param n_array: An Array
:param a_value: A value that is searched in the Array
:return: Either the index value or -1
:rtype: Int
"""
try:
index = n_array.index(a_value)
return index
except ValueError:
return -1
def sort_array(n_array):
"""
Function sorts the Array
:param n_array: An Array
:return: Sorted Array
:rtype: Array
"""
print(n_array)
for i in range(0, len(n_array)):
for j in range(i+1, len(n_array)):
if n_array[i] > n_array[j]:
temp = n_array[i]
n_array[i] = n_array[j]
n_array[j] = temp
return n_array #return was coded to pass back the sorted Array
if __name__ == '__main__':
n_array = arr.array('i', [1, 4, 5, 3, 2])
a_value = int(input("Enter a value to search in the array: "))
index_value = search_array(n_array, a_value)
print("Index found: {}".format(index_value))
print(sort_array(n_array))
|
# Author: Dariush Azimi
# Created: April 22, 2020
import matplotlib.pyplot as plt
import matplotlib
import os
import pandas as pd
import streamlit as st
import seaborn as sns
matplotlib.use('Agg')
def main():
""" Machine Learning Dataset Explorer App """
st.title("Machine Learning Dataset Explorer App")
st.subheader("Simple Data Exploration")
# html_temp = """
# <div style = "background-color:tomato;"> <p style="color:white; font-size:10px";> This is great</p.
# """
# st.markdown(html_temp, unsafe_allow_html=True)
def file_selector(folder_path='./datasets'):
filenames = os.listdir(folder_path)
selected_filename = st.selectbox("Select a file", filenames)
return os.path.join(folder_path, selected_filename)
filename = file_selector()
# show the user that they have actually selected the file
# st.write("You selected {}".format(filename))
# lets make it more beutiful with some colors
st.info("You selected {}".format(filename))
# read data
df = pd.read_csv(filename)
# show dataset
if st.checkbox("show Dataset"):
# you can limite the number of rows if you want
# number = st.number_input("number of rows to view", 5, 10)
number = st.number_input("Number of rows", min_value=0, value=5, step=1)
st.dataframe(df.head(number))
# show columns
if st.button("column names"):
st.write(df.columns)
# st.map()
# show shape
if st.checkbox("Show datata shad"):
# Removed the line below as we now have a condition to show either rows or columns
# st.write(df.shape)
data_dim = st.radio("show dimention by ", ("Rows", "Columns"))
if data_dim == 'Rows':
st.text("Number of Rows")
st.write(df.shape[0])
elif data_dim == 'Columns':
st.text("Number of Columns")
st.write(df.shape[1])
else:
st.write(df.shap)
# select columns
if st.checkbox("Selected columns to show"):
all_columns = df.columns.tolist()
selected_columns = st.multiselect("Select", all_columns)
new_df = df[selected_columns]
st.write('# Selected Columns')
st.dataframe(new_df)
# select rows
if st.checkbox("Selected rows to show"):
selected_indices = st.multiselect('Select rows:', df.index)
selected_rows = df.loc[selected_indices]
st.write('# Selected Rows', selected_rows)
# show values
if st.button("value counts"):
st.text("value counts by target/class")
# we are slecting the last column
st.write(df.iloc[:, -1].value_counts())
# show datatypes
if st.button("Data types"):
st.text("value counts by target/class")
st.write(df.dtypes)
# show summary
if st.checkbox("Summary"):
st.write(df.describe())
# Transpose summary
if st.checkbox("Transpose"):
st.write(df.describe().T)
# Plot and visualization
st.subheader("Data Visualization")
# Correlation
# Seaborn Plot
if st.checkbox("Correlation plot[seaborn]"):
st.write(sns.heatmap(df.corr(), annot=True))
st.pyplot()
# Pie Chart
if st.checkbox("Pie Plot"):
all_columns_names = df.columns.tolist()
if st.button('Generating Pie Plot'):
st.success('Generating a Pie Plot')
st.write(df.iloc[:, -1].value_counts().plot.pie(autopct="%1.1f%%"))
st.pyplot()
# Count plot
if st.checkbox("plot of value count"):
st.text("Value counts by Traget/Class")
all_columns_names = df.columns.tolist()
primary_col = st.selectbox("Primary column to groupby", all_columns_names)
selected_columns_names = st.multiselect("select columns ", all_columns_names)
if st.button("Plot"):
st.text("Generate Plot")
if selected_columns_names:
vc_plot = df.groupby(primary_col)[selected_columns_names].count()
else:
vc_plot = df.iloc[:, -1].value_counts
st.write(vc_plot.plot(kind='bar'))
st.pyplot()
# Customizable Plot
st.subheader("Customizable Plot")
all_columns_names = df.columns.tolist()
type_of_plot = st.selectbox("Slect type of plot", ['area', 'bar', 'line', 'hist', 'box', 'kde'])
# we need to be able to slect the columns
selected_columns_names = st.multiselect('Select columns to plot', all_columns_names)
if st.button("Generate Plot"):
st.success("Genrating Customizable Plot of {} for {}".format(type_of_plot, selected_columns_names))
# Plot by Streamlit
if type_of_plot == 'area':
# create a custom data
cust_data = df[selected_columns_names]
# and now plot it by passing in our custom dataset
st.area_chart(cust_data)
elif type_of_plot == 'bar':
# create a custom data
cust_data = df[selected_columns_names]
# and now plot it by passing in our custom dataset
st.bar_chart(cust_data)
elif type_of_plot == 'line':
# create a custom data
cust_data = df[selected_columns_names]
# and now plot it by passing in our custom dataset
st.line_chart(cust_data)
# Custome plot
elif type_of_plot:
# create a custom data
cust_plot = df[selected_columns_names].plot(kind=type_of_plot)
# and now plot it by passing in our custom dataset
st.write(cust_plot)
st.pyplot()
if st.button("Life is great :) "):
st.balloons()
if __name__ == '__main__':
main()
|
def do_flatten(iterable):
nested_list = iterable[:]
while nested_list:
sublist = nested_list.pop(0)
if isinstance(sublist, list):
nested_list = sublist + nested_list
elif sublist or sublist == 0:
yield sublist
def flatten(iterable):
return [i for i in do_flatten(iterable)] |
import re
while True:
print("Voer je mobiele nummer in:")
invoer = input("> ")
patroon = '^06-?\d{8}$'
matches = re.findall(patroon, invoer)
if (len(matches) > 0):
break
print("Bedankt nummer in juiste formaat:", matches[0]) |
print("Introduceti un numar intreg: ", end="")
n = int(input())
money_values = [1000, 500, 200, 100, 50, 20, 10, 5, 1]
print("Suma introdusa poate fi descompusa in urmatoarele bancnote")
while n > 0:
for value in money_values:
# operatoru // ia partea intreaga de la impartire
if n//value > 0:
print("{} x {} lei".format(n//value, value))
n %= value
|
import math
def show_if_not_prime(number):
for x in range(2, number):
if number % x == 0:
return print('{} '.format(number), end='')
print("Introduceti un numar intreg: ", end="")
n = int(input())
for i in range(1, int(math.sqrt(n))):
if n % i == 0:
show_if_not_prime(i)
show_if_not_prime(n//i)
print()
|
"""
A program for calculating the number of units of each type of product
from the purchased by each customer of the online store in lexicographic order,
after the name of each product - the number of units of the product.
Sample Input 1:
5
Руслан Пирог 1
Тимур Карандаш 5
Руслан Линейка 2
Тимур Тетрадь 12
Руслан Хлеб 3
Sample Output 1:
Руслан:
Линейка 2
Пирог 1
Хлеб 3
Тимур:
Карандаш 5
Тетрадь 12
"""
from collections import defaultdict
def create_dict_with_information(n):
all_users = defaultdict(dict)
for _ in range(n):
name, good, count = input().split()
all_users[name][good] = all_users[name].setdefault(good, 0) + int(count)
return all_users
def show_list(all_users):
for name, goods in sorted(all_users.items()):
print(f'{name}:')
for good, count in sorted(goods.items()):
print(f'{good} {count}')
def main():
n = int(input())
all_users = create_dict_with_information(n)
show_list(all_users)
if __name__ == '__main__':
main()
|
person = {
'name': '',
'money': 1000,
'cargo': {},
# 'level': 1,
# 'experience': 0,
'skills': {
'luck': 4,
'eloquence': 7,
'agility': 0
}
}
goods = [{'type': "Техника", "price_in":1000, "price_out": 5000, "risk_precent": 10},
{'type': "Сигареты", "price_in":100, "price_out": 300, "risk_precent": 10},
{'type': "Алкоголь", "price_in":250, "price_out": 600, "risk_precent": 15},
{'type': "Драгоценности", "price_in":5000, "price_out": 15000, "risk_precent": 20}]
def purchase(lucky_person):
print("choose your goods")
for i,n in enumerate(goods):
print(i, f"{n['type']} цена покупки:{n['price_in']} цена продажи: {n['price_out']} \
вероятный навар: {n['price_out'] - n['price_in']} риск:{n['risk_precent']}%") # f - форматирование строки
lucky_person['cargo'] = goods[int(input("Enter number "))]
lucky_person['money'] -= lucky_person["cargo"]["price_in"] * ((100 - lucky_person["skills"]["eloquence"])/100)
def sale(lucky_person):
lucky_person['money'] += lucky_person["cargo"]["price_out"] * ((100 + lucky_person["skills"]["luck"])/100)
lucky_person['cargo'] = {}
purchase(person)
print(person)
sale(person)
print(person)
|
import math
def MuyuanC(T):
if T > 0:
print 'Hello Muyuan Chen'
else:
print 'Good bye Muyuan Chen'
F = [1, 2]
def fibNEven(N):
if( N <= 0):
print 'please input a valid number'
return
print F[0]
while( N - 1 > 0 ):
a = F[0]+F[1]
if(a % 2 == 1):
F[0] = F[1]
F[1] = a
else:
F[0] = F[1]
F[1] = a
print a
N -= 1
def tandf(N):
if (N <= 0 ):
print 'please input a valid number'
return
for a in range (1, N):
if(a % 3 == 0 and a % 5 == 0):
print 'FizzBuzz'
elif (a % 3 == 0):
print 'Fizz'
elif (a % 5 == 0):
print 'Buzz'
else:
print a
print math.sqrt(4)
print 'Calm down, Li Wang'
fibNEven(7)
tandf(15)
MuyuanC(20)
|
import time
def time_exc(s):
start = time.clock()
result = eval(s)
run_time = time.clock() - start
return result, run_time
def spin_loop(n):
i = 0
while i < n:
i +=1
print time_exc('1+1')
print time_exc('spin_loop(10000)')
print time_exc('spin_loop(10 ** 7)')[1]
|
"""
Authors: EYW and Addison Spiegel
Allows you to have two modifiable colors and the ability to change the greyscale threshold
Created: 10/1
"""
import cv2
import numpy
import os.path
# this function does nothing, it is for the creation of the cv2 createTrackbar, it requires a function as an argument
def nothing(x):
pass
print ("Save your original image in the same folder as this program.")
filename_valid = False
# keep asking for the correct file to be inputted
while filename_valid == False:
filename = input("Enter the name of your file, including the "\
"extension, and then press 'enter': ")
if os.path.isfile(filename) == True:
filename_valid = True
else:
print ("Something was wrong with that filename. Please try again.")
# returns a the image in rgb
original_image = cv2.imread(filename,1)
# returns the image in greyscale
grayscale_image_simple = cv2.imread(filename, 0)
# converts the greyscale image back to bgr
grayscale_image = cv2.cvtColor(grayscale_image_simple, cv2.COLOR_GRAY2BGR)
# Creates a new window on the display with the name you give it
# cv2.namedWindow('Original Image')
# cv2.namedWindow('Grayscale Image')
# cv2.namedWindow('Red Parts of Image')
# cv2.namedWindow('Yellow Parts of Image')
cv2.namedWindow('Customized Image')
cv2.namedWindow('sliderWindow')
# the height of the image
image_height = original_image.shape[0]
# the width of the image
image_width = original_image.shape[1]
# how many channels the image has, in this case, 3
image_channels = original_image.shape[2]
#creating the trackbar that will adjust the grayscale threshold
cv2.createTrackbar("threshold", "sliderWindow",100,255,nothing)
rgbl = ['R','G','B']
# Creating all the trackbars, this for loop set up will make it easier in the future to make more sliders quickly
for i in range(1,3):
for a in rgbl:
cv2.createTrackbar(f"Color {i}{a}", "sliderWindow",150,255,nothing)
while True:
# adjusting the grayscale threshold with the cv2 function that gets the position of the trackbar
grayscale_break = cv2.getTrackbarPos('threshold', 'sliderWindow')
# creating an empty image for the red and yellow images
red_paper = numpy.zeros((image_height,image_width,image_channels), numpy.uint8)
yellow_paper = numpy.zeros((image_height,image_width,image_channels),
numpy.uint8)
# changing every pixel in the color "paper" to the colors in the sliders
red_paper[0:image_height,0:image_width, 0:image_channels] = [cv2.getTrackbarPos('Color 1B', 'sliderWindow')
,cv2.getTrackbarPos('Color 1G', 'sliderWindow'),
cv2.getTrackbarPos('Color 1R', 'sliderWindow')]
# changing every pixel in the color "paper" to the colors in the sliders
yellow_paper[0:image_height,0:image_width, 0:image_channels] = [cv2.getTrackbarPos('Color 2B', 'sliderWindow')
,cv2.getTrackbarPos('Color 2G', 'sliderWindow'),
cv2.getTrackbarPos('Color 2R', 'sliderWindow')]
#making the range of greyscales
min_grayscale_for_red = [0,0,0]
max_grayscale_for_red = [grayscale_break,grayscale_break,grayscale_break]
min_grayscale_for_yellow = [grayscale_break+1,grayscale_break+1,
grayscale_break+1]
max_grayscale_for_yellow = [255,255,255]
# converting these arrays to numpy arrays
min_grayscale_for_red = numpy.array(min_grayscale_for_red, dtype = "uint8")
max_grayscale_for_red = numpy.array(max_grayscale_for_red, dtype = "uint8")
min_grayscale_for_yellow = numpy.array(min_grayscale_for_yellow,
dtype = "uint8")
max_grayscale_for_yellow = numpy.array(max_grayscale_for_yellow,
dtype = "uint8")
# returns a mask that is made up of pure black and white pixels.
# Converts grayscale pixels within the range of the two arguments
# All the red parts turn white
block_all_but_the_red_parts = cv2.inRange(grayscale_image,
min_grayscale_for_red,
max_grayscale_for_red)
# converts all the yellow parts of the image to white
block_all_but_the_yellow_parts = cv2.inRange(grayscale_image,
min_grayscale_for_yellow,
max_grayscale_for_yellow)
# applies the mask onto the solid red and yellow images
# the black from the previous 'block' variables goes on top of the solid red and yellow images
red_parts_of_image = cv2.bitwise_or(red_paper, red_paper,
mask = block_all_but_the_red_parts)
yellow_parts_of_image = cv2.bitwise_or(yellow_paper, yellow_paper,
mask = block_all_but_the_yellow_parts)
# combines the two images, the black part on the yellow image is merged with the red from the other image
customized_image = cv2.bitwise_or(red_parts_of_image, yellow_parts_of_image)
# showing the image in the previously created windows
#cv2.imshow('Original Image', original_image)
#cv2.imshow('Grayscale Image',grayscale_image)
#cv2.imshow('Red Parts of Image',red_parts_of_image)
#cv2.imshow('Yellow Parts of Image',yellow_parts_of_image)
cv2.imshow('Customized Image',customized_image)
# if the key is pressed it will close all the windows
keypressed = cv2.waitKey(1)
if keypressed == 27:
cv2.destroyAllWindows()
break
# if s is pressed, it will save the images
elif keypressed == ord('s'):
cv2.imwrite('photo_GS_1.jpg',grayscale_image)
cv2.imwrite('photo_RY_1.jpg',customized_image)
cv2.destroyAllWindows()
break
quit()
|
#!/usr/bin/env python3
from lazylist import LazyList
def fibonacci(a=0, b=1):
while True:
yield a
a, b = b, a + b
lazyfib = LazyList(fibonacci())
print(lazyfib[0], lazyfib[3], lazyfib[10]) # prints 0, 2, 55
print(lazyfib[8], lazyfib[7]) # prints 21, 13
for x in lazyfib[3:7]:
print(x) # prints 2, 3, 5, 8
for x in lazyfib[:5]:
print(x) # prints 0, 1, 1, 2, 3
c = 0
for x in lazyfib[10:]:
if c >= 3:
break
print(x) # prints 55, 89, 144
c += 1
print(lazyfib[100]) # prints 354224848179261915075
# This will not work
try:
foo = lazyfib[5:10]
print(foo[3])
except TypeError as err:
# throws TypeError("'LazyListIterator' object does not support indexing")
print(repr(err))
# The following works, but is memory-inefficient
foo = LazyList(lazyfib[5:10])
print(foo[3]) # prints 21
# The values 5, 8, 13, 21 are now stored twice: in the original lazyfib's cache,
# and also in foo's cache.
# Any of the following would cause the program to hang forever and eat all your
# memory. They would work if the generator you constructed with was finite,
# however (like a file stream).
if False:
print(len(lazyfib))
if False:
print(lazyfib[-7])
if False:
foo = lazyfib[5:-1]
if False:
for x in lazyfib[10:]:
pass
|
# # -*- coding: utf-8 -*-
# ''' This program takes a excel sheet as input where each row in first column of sheet represents a document. '''
#
# import pandas as pd
# import numpy as np
#
# data = pd.read_excel('C:\\Users\medicisoft\Downloads\\data.xlsx',dtype=str) # Include your data file instead of data.xlsx
#
# idea = data.iloc[:, 0:1] # Selecting the first column that has text.
#
# # Converting the column of data from excel sheet into a list of documents, where each document corresponds to a group of sentences.
# corpus = []
# for index, row in idea.iterrows():
# corpus.append(row['Idea'])
#
# '''Or you could just comment out the above code and use this dummy corpus list instaed if don't have the data.
#
# corpus=['She went to the airport to see him off.','I prefer reading to writing.','Los Angeles is in California. It's southeast of San Francisco.','I ate a burger then went to bed.','Compare your answer with Tom's.','I had hardly left home when it began to rain heavily.','If he had asked me, I would have given it to him.
# ','I could have come by auto, but who would pay the fare? ','Whatever it may be, you should not have beaten him.','You should have told me yesterday','I should have joined this course last year.','Where are you going?','There are too many people here.','Everyone always asks me that.','I didn't think you were going to make it.','Be quiet while I am speaking.','I can't figure out why he said so.'] '''
#
# # Count Vectoriser then tidf transformer
#
# from sklearn.feature_extraction.text import CountVectorizer
#
# vectorizer = CountVectorizer()
# X = vectorizer.fit_transform(corpus)
#
# # vectorizer.get_feature_names()
#
# # print(X.toarray())
#
# from sklearn.feature_extraction.text import TfidfTransformer
#
# transformer = TfidfTransformer(smooth_idf=False)
# tfidf = transformer.fit_transform(X)
# # print(tfidf.shape)
#
# from sklearn.cluster import KMeans
#
# num_clusters = 5 # Change it according to your data.
# km = KMeans(n_clusters=num_clusters)
# km.fit(tfidf)
# clusters = km.labels_.tolist()
#
# idea = {'Idea': corpus, 'Cluster': clusters} # Creating dict having doc with the corresponding cluster number.
# frame = pd.DataFrame(idea, index=[clusters], columns=['Idea', 'Cluster']) # Converting it into a dataframe.
#
# print("\n")
# print(frame) # Print the doc with the labeled cluster number.
# print("\n")
# print(frame['Cluster'].value_counts()) # Print the counts of doc belonging to ach cluster.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
num_vectors = 1000
num_clusters = 3
num_steps = 100
vector_values = []
for i in range(num_vectors):
if np.random.random() > 0.5:
vector_values.append([np.random.normal(0.5, 0.6),
np.random.normal(0.3, 0.9)])
else:
vector_values.append([np.random.normal(2.5, 0.4),
np.random.normal(0.8, 0.5)])
df = pd.DataFrame({"x": [v[0] for v in vector_values],
"y": [v[1] for v in vector_values]})
sns.lmplot("x", "y", data=df, fit_reg=False, size=7)
plt.show()
vectors = tf.constant(vector_values)
centroids = tf.Variable(tf.slice(tf.random_shuffle(vectors),
[0,0],[num_clusters,-1]))
expanded_vectors = tf.expand_dims(vectors, 0)
expanded_centroids = tf.expand_dims(centroids, 1)
print(expanded_vectors.get_shape())
print(expanded_centroids.get_shape())
distances = tf.reduce_sum(tf.square(tf.sub(expanded_vectors, expanded_centroids)), 2)
assignments = tf.argmin(distances, 0)
means = tf.concat(0, [
tf.reduce_mean(
tf.gather(vectors,
tf.reshape(
tf.where(
tf.equal(assignments, c)
),[1,-1])
),reduction_indices=[1])
for c in range(num_clusters)])
update_centroids = tf.assign(centroids, means)
init_op = tf.initialize_all_variables()
#with tf.Session('local') as sess:
sess = tf.Session()
sess.run(init_op)
for step in range(num_steps):
_, centroid_values, assignment_values = sess.run([update_centroids,
centroids,
assignments])
print("centroids")
print(centroid_values)
data = {"x": [], "y": [], "cluster": []}
for i in range(len(assignment_values)):
data["x"].append(vector_values[i][0])
data["y"].append(vector_values[i][1])
data["cluster"].append(assignment_values[i])
df = pd.DataFrame(data)
sns.lmplot("x", "y", data=df,
fit_reg=False, size=7,
hue="cluster", legend=False)
plt.show()
|
# a = input('숫자를 입력하시오! : ')
#
# if int(a)%2 == 0:
# print('짝수')
#
# else:
# print('홀수')
# def mod(val):
# if val%2 == 0:
# print('짝수')
# else:
# print('홀수')
#
# print(mod(10))
# a = input('이름을 입력하시오! ')
#
# import pandas as pd
# emp = pd.read_csv("d:\data\emp.csv")
# salary = emp[['sal']][emp['ename'] == a].values[0]
#
# if salary >= 3000:
# print('고소득자')
#
# elif salary >= 2000:
# print('적당')
#
# else:
# print('저소득자')
# num1 = int(input('첫번째 숫자 입력! '))
# num2 = int(input('두번째 숫자 입력! '))
#
# sub1 = (num1 + num2)/2
# sub2 = (num2 - num1 + 1)
# result = sub1 * sub2
#
# print(num1,'부터',num2,'까지의 숫자 합은 ',result,'입니다')
# num1 = int(input('첫번째 숫자 입력! '))
# num2 = int(input('두번째 숫자 입력! '))
#
# if num1 < num2:
# sub1 = (num1 + num2) / 2
# sub2 = (num2 - num1 + 1)
# result = sub1 * sub2
# print(num1,'부터',num2,'까지의 숫자 합은 ',result,'입니다')
#
# else:
# print('첫번째 입력한 숫자가 두번째 입력한 숫자보다 큽니다')
# for i in range(2,10):
# for j in range(1,10):
# print(i,' X ',j,' = ',i*j)
# print('\n')
# for i in range(1,11):
# print('★'*i)
# def lpad(val,num,st):
# return st * (num-len(val)) + val
#
# for i in range(1,5):
# print(lpad('★',8-i,' ')*i)
# for j in range(3,0,-1):
# print(lpad('★',8-j,' ')*j)
# for i in range(11):
# if i < 6:
# print(' '*(20-i),'★'*i)
#
# elif i >= 6:
# print(' '*(20-i),'★'*(i-5),' '*(12-i),'★'*(i-5))
# for i in range(1,10):
# p = ''
# for j in range(2,10):
# p += (str(j)+' X '+str(i)+' = '+str(j*i)).ljust(16)
#
# print(p)
# s = 'some string12'
# number = sum(i.isdigit() for i in s)
# word = sum(i.isalpha() for i in s)
# space = sum(i.isspace() for i in s)
#
# print(number)
# print(word)
# print(space)
# text_file = open("d:\data\winter.txt","r")
# lines = text_file.readlines()
# total1 = 0
# total2 = 0
#
# for s in lines:
#
# number = sum(i.isdigit() for i in s)
# word = sum(i.isalpha() for i in s)
# space = sum(i.isspace() for i in s)
# cnt = len(s)
# total1 += cnt
# total2 += (number+word+space)
#
# print(total1-total2)
# print(num1,' 의',num2,'승은 ',res,' 입니다')
# ga = int(input('가로 숫자 입력! '))
# se = int(input('세로 숫자 입력! '))
#
# for i in range(se):
# res = ''.join('★' for i in range(ga))
# print(res)
# s = int(input('팩토리얼 숫자를 입력하시오! '))
# result = 1
# count = 0
#
# while count < s:
# result = result * s
# s = s - 1
#
# print(result)
# base = int(input('밑수 입력! '))
# exp = int(input('진수 입력! '))
# cnt = 0
#
# while exp >= base:
#
# exp = exp/base
# cnt = cnt + 1
#
# print(cnt)
|
import simplegui
# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
ball_pos = [WIDTH / 2, HEIGHT / 2]
vel = [-120.0 / 60.0, 25.0 / 60.0]
# define event handlers
def draw(canvas):
global BALL_RADIUS
BALL_RADIUS = 20
# Update ball position
ball_pos[0] += vel[0]
ball_pos[1] += vel[1]
# collide and reflect off of left hand side of canvas
if ((int(ball_pos[0]) <= BALL_RADIUS) or (ball_pos[0] >= WIDTH - BALL_RADIUS)):
vel[0] = - vel[0];
elif (ball_pos[1] <= BALL_RADIUS or
ball_pos[1] >= HEIGHT - BALL_RADIUS):
vel[1] = - vel[1]
# Draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
# create frame
frame = simplegui.create_frame("Ball physics", WIDTH, HEIGHT)
# register event handlers
frame.set_draw_handler(draw)
# start frame
frame.start()
|
# Mouseclick Handlers
# Tic-Tac-Toe
# This program allows two users to play tic-tac-toe using
# mouse input to the game.
import simplegui
# Global Variables
canvas_width = 300
canvas_height = 300
grid = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
turn = "X"
won = False
# Helper Functions
def switch_turn():
global turn, info
if turn == "X":
turn = "O"
else:
turn = "X"
info.set_text("Player turn: " + turn)
# Returns 'True' if a player has won, false otherwise
def check_win():
for a in range(0,3):
if grid[a][0] != " " and grid[a][0] == grid[a][1] == grid[a][2]:
return True
for b in range(0,3):
if grid[0][b] != " " and grid[0][b] == grid[1][b] == grid[2][b]:
return True
if grid[0][0] == grid[1][1] == grid[2][2] and grid[0][0] != " ":
return True
elif grid[0][2] == grid[1][1] == grid[2][0] and grid[0][2] != " ":
return True
else:
return False
# Event Handlers
def draw(canvas):
# Draws the grid lines
canvas.draw_line([0, canvas_height // 3], [canvas_width, canvas_height // 3], 1, "White")
canvas.draw_line([0, canvas_height // 3 * 2], [canvas_width, canvas_height // 3 * 2], 1, "White")
canvas.draw_line([canvas_width // 3, 0], [canvas_width // 3, canvas_height], 1, "White")
canvas.draw_line([canvas_width // 3 * 2, 0], [canvas_width // 3 * 2, canvas_height], 1, "White")
# Draws the player choices using loops
for r in range(0,3):
for c in range(0,3):
canvas.draw_text(grid[r][c], [c * canvas_width // 3 + 20, r * canvas_height // 3 + 80], 80, "Red")
def click(pos):
global won, info
if not won:
# Checks to see if the click was on a grid line
if pos[0] % (canvas_width // 3) != 0 and pos[1] % (canvas_height // 3) != 0:
r = pos[1] // (canvas_height // 3)
c = pos[0] // (canvas_width // 3)
# Checks to see if a square is already taken
if grid[r][c] == " ":
grid[r][c] = turn
if check_win():
won = True
info.set_text("Player " + turn + " wins!")
else:
switch_turn()
def reset():
global grid, turn, won, info
grid = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
turn = "X"
won = False
info.set_text("Player turn: " + turn)
# Frame
frame = simplegui.create_frame("Tic-Tac-Toe", canvas_width, canvas_height)
# Register Event Handlers
frame.set_draw_handler(draw)
frame.set_mouseclick_handler(click)
frame.add_button("Reset", reset)
info = frame.add_label("Player turn: " + turn)
# Start
frame.start() |
# Testing template for Particle class
import random
import simplegui
###################################################
# Student should add code for the Particle class here
WIDTH = 800
HEIGHT = 600
PARTICLE_RADIUS = 5
COLOR_LIST = ['Green', 'Red', 'Maroon',
'Aqua', 'White', 'Blue',
'Yellow', 'Navy', 'Brown']
DIRECTION_LIST = [[5, 0], [0, 5], [-5, 0], [0, -5]]
class Particle:
def __init__(self, position, color):
self.color = color
self.pos = list(position)
def move(self, velocity):
self.pos[0] += velocity[0]
self.pos[1] += velocity[1]
def draw(self, canvas):
canvas.draw_circle(self.pos, PARTICLE_RADIUS, 1, self.color[0], self.color[1])
def __str__(self):
return "The Particle is in position " + str(self.position)+" With the colors "+str(self.color)
###################################################
# Test code for the Particle class
def draw(canvas):
for p in Particles:
p.move(random.choice(DIRECTION_LIST))
for p in Particles:
p.draw(canvas)
Particles = []
for i in range(1000):
p = Particle([WIDTH/2, HEIGHT/2], [random.choice(COLOR_LIST), random.choice(COLOR_LIST),])
Particles.append(p)
frame = simplegui.create_frame('Balls Moving', WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.start()
##########e#########################################
# Output from test
#Particle with position = [20, 20] and color = Red
#<class '__main__.Particle'>
#Particle with position = [30, 40] and color = Red
#Particle with position = [15, 15] and color = Red
#
#Particle with position = [15, 30] and color = Green
#<class '__main__.Particle'>
#Particle with position = [15, 30] and color = Green
|
__author__ = 'darrell.skogman'
def addemup(a, b, c):
return a+b+c
def divideandadd(a,b,c):
return a/b+c
def main():
a = int(input("first number "))
b = int(input("second number "))
c = int(input("third number "))
print(addemup(a, b, c))
main()
|
#Importing OS and File Type
import os
import csv
#Creates Path to budget_data CSV File
#Had trouble opening 'budget_data.csv so implemented os.getcwd() to help open filepath
#https://www.tutorialspoint.com/python/os_getcwd.htm
print(os.getcwd())
budget_data = os.path.join('PyBank', 'Resources', 'budget_data.csv')
#Allows the File Path to be Read based on CSV Conditions
with open(budget_data, newline = "") as csvfile:
csvreader = csv.reader(csvfile, delimiter = ",")
#Reads the Header of budget_data CSV
csv_header = next(csvreader)
#Reads the First Row of budget_data CSV
row_one = next(csvreader)
#Setting Month Total, Profit Loss Total, Holder Count, and Adjust Count to Zero In Order To Track Addition Towards Total For Each
month_count = 0
profitloss_count = 0
holder_count = 0
adjust_count = 0
#Stores profit and date data
profit_list = []
date_list = []
#Totals the months, profitloss count, and adds to the holder count for the very first row before going through the other rows
month_count = month_count + 1
profitloss_count = profitloss_count + int(row_one[1])
holder_count = int(row_one[1])
#creates for loop reading each row in csv reader
for row in csvreader:
#Goes through the dates holder and tracks changes
date_list.append(row[0])
#Adjusts the profits holder by iterating through each row and then moving to next holder_count which assists with pushing through the rows
adjust_count = int(row[1]) - holder_count
profit_list.append(adjust_count)
holder_count = int(row[1])
#Calculates the total months exluding header and first row
month_count = month_count + 1
#Calculates them total profit loss count excluding header and first row
profitloss_count = profitloss_count + int(row[1])
#Finds the Greatest Profit Increase's Value and Date by indexing through profit list and returning the maximum value and date using 'max()' function
highest_increase = max(profit_list)
highest_index = profit_list.index(highest_increase)
highest_date = date_list[highest_index]
#Finds the Greatest Profit Decreases's Value and Date by indexing through profit list and returning the minimum value and date using 'min()' function
lowest_decrease = min(profit_list)
lowest_index = profit_list.index(lowest_decrease)
lowest_date = date_list[lowest_index]
#Formula that Calulates the Average Change in Profit by dividing the sum of all profits in created profit holder by the entire length of profit holder
average = sum(profit_list) / len(profit_list)
#Printing and Summarizing Data
print("Financial Analysis")
print("------------------")
print(f'Total Months: {str(month_count)}')
print(f'Total: ${str(profitloss_count)}')
#Round function that rounds the average change to 2 decimal places
print(f'Average Change: $ {str(round(average,2))}')
print(f'Greatest Increase in Profits: {highest_date} (${str(highest_increase)})')
print(f'Greatest Decrease in Profits: {lowest_date} (${str(lowest_decrease)})')
#Creates and exports an 'output' text file that is write only
export_txtfile = open("output.txt", "w")
#Creates the output text files lines 'l1, l2, ect...' based on Printing and Summarizing Data
l1 = "Financial Analysis"
l2 = "------------------"
l3 = str(f'Total Months: {str(month_count)}')
l4 = str(f'Total: ${str(profitloss_count)}')
#Round function that rounds the average change to 2 decimal places
l5 = str(f'Average Change: $ {str(round(average,2))}')
l6 = str(f'Greatest Increase in Profits: {highest_date} (${str(highest_increase)})')
l7 = str(f'Greatest Decrease in Profits: {lowest_date} (${str(lowest_decrease)})')
#Syntax that outputs each line of text file for all 7 lines
#https://stackoverflow.com/questions/21019942/write-multiple-lines-in-a-file-in-python/21020007
export_txtfile.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(l1,l2,l3,l4,l5,l6,l7)) |
import trek
import wander
while True:
print("Games")
print("-----")
print("0. Quit")
print("1. Trek")
print("2. Wander")
choice = input("What do you want to play?")
if choice == "0":
break
elif choice == "1":
trek.start()
elif choice == "2":
wander.start()
|
import re
class GameController:
"""Maintains the state of the game."""
def __init__(self, WIDTH, HEIGHT, PLAYER_NAME, PLAYER_COLOR,
file_name="scores.txt"):
self.WIDTH = WIDTH
self.HEIGHT = HEIGHT
self.PLAYER_NAME = PLAYER_NAME
assert PLAYER_COLOR in ["black", "white"], "Wrong color!"
self.PLAYER_COLOR = PLAYER_COLOR
self.FILE_NAME = file_name
self.is_black = True
self.is_skip = False
self.is_finished = False
self.black_wins = False
self.white_wins = False
self.draw = False
self.black_num = None
self.white_num = None
def __eq__(self, other):
return self.__dict__ == other.__dict__
def display(self):
"""Carries out necessary actions when game is in processing"""
if self.is_black:
fill(255, 0, 0)
textSize(20)
text("Turn: Black", 50, 50)
else:
fill(255, 0, 0)
textSize(20)
text("Turn: White", 50, 50)
if self.is_finished:
if self.black_wins:
fill(0, 255, 0)
textSize(50)
text("BLACK WINS!!!", self.WIDTH/2 - 140, self.HEIGHT/2)
text("Black: "+str(self.black_num),
self.WIDTH/2 - 100, self.HEIGHT/2 + 50)
text("White: "+str(self.white_num),
self.WIDTH/2 - 100, self.HEIGHT/2 + 100)
elif self.white_wins:
fill(0, 255, 0)
textSize(50)
text("WHITE WINS!!!", self.WIDTH/2 - 140, self.HEIGHT/2)
text("Black: "+str(self.black_num),
self.WIDTH/2 - 100, self.HEIGHT/2 + 50)
text("White: "+str(self.white_num),
self.WIDTH/2 - 100, self.HEIGHT/2 + 100)
elif self.draw:
fill(0, 255, 0)
textSize(50)
text("DRAW", self.WIDTH/2 - 100, self.HEIGHT/2)
text("Black: "+str(self.black_num),
self.WIDTH/2 - 100, self.HEIGHT/2 + 50)
text("White: "+str(self.white_num),
self.WIDTH/2 - 100, self.HEIGHT/2 + 100)
elif self.is_skip:
fill(0, 255, 0)
textSize(20)
text("Switch player since there is no valid step.",
self.WIDTH/4, self.HEIGHT/4)
def record_scores(self):
"""record player's score if player wins"""
# if ((self.PLAYER_COLOR == "black" and self.black_wins) or
# (self.PLAYER_COLOR == "white" and self.white_wins)):
with open(self.FILE_NAME, "r+") as scores:
record = scores.read()
if not record:
if self.PLAYER_COLOR == "black":
scores.write(self.PLAYER_NAME + " " +
str(self.black_num) + "\n")
else:
scores.write(self.PLAYER_NAME + " " +
str(self.white_num) + "\n")
else:
max_score = int(re.findall(r"^.* (\d*)\n", record)[0])
if self.PLAYER_COLOR == "black":
if self.black_num >= max_score:
scores.seek(0)
scores.write(self.PLAYER_NAME + " " +
str(self.black_num) + "\n" + record)
else:
scores.write(self.PLAYER_NAME + " " +
str(self.black_num) + "\n")
else:
if self.white_num >= max_score:
scores.seek(0)
scores.write(self.PLAYER_NAME + " " +
str(self.white_num) + "\n" + record)
else:
scores.write(self.PLAYER_NAME + " " +
str(self.white_num) + "\n")
scores.close()
|
"""A standard card deck with shuffling, sorting, and dealing features.
This module contains the CardDeck() class. It is made to represent a standard deck
of cards (4 suits, 13 cards per suit).The pull_card_from_deck() function returns the
final card from the deck, as if the cards were upside down and the top card was chosen.
Typical usage example:
card_deck = CardDeck(shuffled=false)
card_deck.shuffle_cards()
card_deck.sort_cards(sort_order = ['Clubs', 'Diamonds', 'Hearts', 'Spades'])
card_count = card_deck.get_card_count() # 52
top_card = card_deck.pull_card_from_deck()
card_count = card_deck.get_card_count() # 51
"""
import random
CARD_VALUE_STRINGS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
CARD_SUITS = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
class CardDeck():
"""Standard deck of cards and functions.
Class represents a standard deck of cards (4 suits, 13 values per suit).
User can initialize a CardDeck() either shuffled or unshuffled (default=unshuffled).
Attributes:
cards: An ordered list of the current cards in the deck.
"""
def __init__(self, shuffled=False):
"""Inits CardDeck object with a deck of cards."""
self.cards = []
for suit in CARD_SUITS:
for value in CARD_VALUE_STRINGS:
self.cards.append((suit, value))
if shuffled:
self.shuffle_cards()
def get_card_count(self):
"""Returns the amount of cards left in the deck."""
return len(self.cards)
def pull_card_from_deck(self):
"""Removes and returns the top card from the deck."""
try:
return self.cards.pop()
except IndexError as deck_empty:
raise IndexError("The deck is empty") from deck_empty
def shuffle_cards(self):
"""Shuffles the deck of cards using the random package."""
shuffled_cards = []
while self.cards:
random_number = random.randint(0, self.get_card_count() - 1)
random_card = self.cards.pop(random_number)
shuffled_cards.append(random_card)
self.cards = shuffled_cards.copy()
def sort_cards(self, sort_order=None):
"""Sorts cards based on suits (default or given), then by value (Ace high)."""
sort_order_suits = {key: i for i, key in enumerate(sort_order)}
sort_order_values = {key: i for i, key in enumerate(CARD_VALUE_STRINGS)}
self.cards.sort(key=lambda x: (sort_order_suits[x[0]], sort_order_values[x[1]]))
def __repr__(self):
"""Represents CardDeck object as 'Deck with n Cards'."""
card_count = self.get_card_count()
if card_count == 1:
plural = ''
else:
plural = 's'
return f'Deck with {card_count} Card{plural}'
|
"""
REVERSE OF A GIVEN NUMBER
"""
n=int(input(" enter the number to be reversed "))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number ",rev)
OUTPUT-
enter the number to be reversed 21
Reverse of the number 12
|
import numpy as np
import pandas as pd
from pandasql import sqldf
##1. Create an sqlalchemy engine using a sample from the data set
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=False)
#engine = create_engine('sqlite:///:memory:', echo=True) ## To Enable Logging
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
Session.configure(bind=engine)
session = Session()
url="https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data"
columns=['age','workclass','fnlwgt','education','education_num','marital_status','occupation','relationship','race','sex','capital_gain','capital_loss','hours_per_week','native_country','class']
adult_df=pd.read_csv(url,names=columns,header=None)
adult_df.to_sql('adult',con=engine,if_exists='replace')
#2. Write two basic update queries
print('Before updating records..... \n')
result1=engine.execute("SELECT * FROM adult where age=39 and sex=' Male' and capital_gain=2174").fetchall()
for line in result1:
print(line)
### Here first is updated by workclass as "Self-emp-not-inc" and second row is updated by race as "Black"
engine.execute("update adult set workclass='Self-emp-not-inc' where age=39 and sex=' Male' and fnlwgt= 77516")
engine.execute("update adult set race='Black' where age=39 and sex=' Male' and fnlwgt= 190466")
print('\nAfter updating 2 records[1st row updated by workclass][2ndst row updated by race]..... \n')
result1=engine.execute("SELECT * FROM adult where age=39 and sex=' Male' and capital_gain=2174").fetchall()
for line in result1:
print(line)
#3. Write two delete queries
engine.execute("delete from adult where age=39 and fnlwgt= 77516")
engine.execute("delete from adult where age=39 and fnlwgt= 190466")
print('\nAfter deleting above 2 records, no rows found..... \n')
result1=engine.execute("SELECT * FROM adult where age=39 and sex=' Male' and capital_gain=2174").fetchall()
for line in result1:
print(line)
#4. Write two filter queries
print('\nFirst Filtering records [age=40 race=White workclass=Private native_country=Mexico]..... \n')
result1=engine.execute("SELECT * FROM adult where age=40 and race=' White' and workclass=' Private' and native_country=' Mexico'").fetchall()
for line in result1:
print(line)
print('\nSecond Filtering records [age=50 race=White workclass=Private native_country=Cuba]..... \n')
result1=engine.execute("SELECT * FROM adult where age=50 and race=' White' and workclass=' Private' and native_country=' Cuba'").fetchall()
for line in result1:
print(line)
#5. Write two function queries
print('\nFirst function query [sum of capital_gain group by race]..... \n')
result1=engine.execute("SELECT race,sum(capital_gain) FROM adult group by race").fetchall()
for line in result1:
print(line)
print('\nSecond function query [max of hours_per_week and average age group by sex]..... \n')
result1=engine.execute("SELECT sex,max(hours_per_week),avg(age) FROM adult group by sex").fetchall()
for line in result1:
print(line) |
tool_quantity = int(input())
tools = input().split(" ")
[a, b] = input().split(" ")
money = int(a)
num = int(b)
for i in range(num):
[c, d] = input().split(" ")
purchase_tool = int(c) - 1
purchase_quantity = int(d)
total = int(tools[purchase_tool]) * int(d)
if total < money:
money -= total
print(money)
|
# 迭代
'''
Python的for循环抽象程度要高于c的for循环,因为Python的for
循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上。
list这种数据类型虽然有下标,但是有很多数据类型是没有下
标的,但是,只要是可迭代对象,无论有无下标,都可以迭代,
比如dict就可以迭代。
'''
'''
d = {'a' : 1, 'b' : 2, 'c' : 3}
for key in d:
print(key)
'''
# 如何判断一个对象是可迭代对象呢?
# 方法是通过collections模块的Iterable类型判断:
'''
from collections import Iterable
print(isinstance('abc',Iterable))
print(isinstance([1,2,3], Iterable))
'''
for i,value in enumerate(['a','b','c']):
print(i,value)
# 练习:使用迭代查找一个list中最小和最大值,并返回一个tuple
def findMinAndMax(arr):
min = max = None
if len(arr) == 0:
return min,max
for x in arr:
if min == None or min > x:
min = x
if max == None or max < x:
max = x
return min,max
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
|
# print(100 + 200 +300)
# print("hello world!")
# print("100 + 200 =",100 + 200)
# name = input()
# name
# name = input()
# print("hello,",name)
# name = input("please enter your name:")
# print("hello,",name)
print(1024 * 768)
|
def tail(iterable, n):
if n <= 0:
return []
items = []
for item in iterable:
if len(items) == n:
items.pop(0)
items.append(item)
return items
from collections import deque
def tail(iterable, n):
if n <= 0:
return []
return list(deque(iterable, maxlen=n))
|
import math
class Circle:
def __init__(self, r=1):
self.radius = r
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, r):
if r < 0:
raise ValueError('Radius cannot be negative')
self._radius = r
@property
def diameter(self):
return self.radius * 2
@diameter.setter
def diameter(self, d):
self.radius = d / 2
@property
def area(self):
return math.pi * self.radius * self.radius
def __repr__(self):
return f'Circle({self.radius})'
|
def extract_word(token):
start = 0
for idx, c in enumerate(token):
if c.isalnum():
start = idx
break
else:
return ''
end = 0
for idx, c in enumerate(reversed(token)):
if c.isalnum():
end = idx
break
else:
assert False
if end == 0:
end = None
else:
end = -end
return token[start:end]
def count_words(msg):
tokens = [extract_word(token).lower() for token in msg.split()]
d = {}
for token in tokens:
d[token] = d.get(token, 0) + 1
return d
# trey's solution
import re
from collections import Counter
def count_words(msg):
return Counter(re.findall(r"\b[\w'-]+\b", msg.lower()))
|
# Q. Rhezo and Prime Problems
# Check Prime No.
def checkPrime(num) :
if num > 2:
for i in range(2,num):
if (num%i) == 0:
break;
else:
return 1
else:
return 0
#Find Max Prime
def maxPrime(num):
count = 0
for i in range(num,0,-1):
if (checkPrime(i)):
num = i
break;
count += 1
return num
#Generate the maximum list
def generateList(N,num,points_a):
sumolist = []
max_list = []
rest_list = []
list1 = []
list2 = []
all_lists = []
for i in range(0,N-num+1):
all_lists.append(points_a[i:num+i])
for x in all_lists:
sumolist.append(sum(x))
ind = sumolist.index(max(sumolist))
max_list.append(all_lists[ind])
for i in max_list[0]:
points_a.remove(i)
print(max(sumolist))
list1 = points_a[:ind]
if len(list1)==0:
list2 = points_a
else:
points_a.remove(list1[0])
list2 = points_a
if len(list1)==0 and len(list2)==0:
return(max(sumolist))
elif len(list1)==0 and len(list2)!=0:
return(max(sumolist)+maximize(len(list2),list2))
elif len(list1)!=0 and len(list2)==0:
return(max(sumolist)+ maximize(len(list1),list1))
else:
return(max(sumolist)+ maximize(len(list1),list1)+maximize(len(list2),list2))
# Maximize function
def maximize(N,points_a):
prime = 0;
if (N <= 2) :
if(N==2):
return(sum(points_a))
return 0;
else:
if checkPrime(N):
return(sum(points_a))
else:
prime = maxPrime(N)
return generateList(N,prime,points_a)
N = int(input());
points = input();
points_a = [int(i) for i in points.split()];
print(maximize(N,points_a))
|
#take name input
name =input('What is your name ?')
print(name)
#take age input
age=input ('What is yout age?')
print(age)
#take hobbies
hobbies=[]
hobbies=input('What are your hobies?')
print(hobbies)
#format all the info
finalOut='Your name is {} at the age of {} your hobbies are {}'
finalOut=finalOut.format(name,age,hobbies)
#display output
print(finalOut)
|
from tkinter import*
import math
class Calc():
def __init__(self):
self.total = 0
self.current = ""
self.input_value = True
self.check_sum = False
self.op = ""
self.result = False
add_value = Calc()
root = Tk()
root.title("Project Casio")
root.resizable(width = False, height = False)
calc = Frame(root)
calc.grid()
# this represents the button/s in the calculator
txtDisplay = Entry(calc, font=("arial", 18, "bold"), bg="powder blue", bd=30, width = 28, justify = RIGHT)
txtDisplay.grid(row = 0, column = 0, columnspan = 4, pady = 1)
txtDisplay.insert(0, "0")
# ------------------------------ /Row 1/ --------------------------------
btnAllClear = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "AC", bg="orange").grid(row = 1, column = 0)
btnDelete = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "DEL", bg="orange").grid(row = 1, column = 1)
btnSqroot = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "√").grid(row = 1, column = 2)
btnAdd = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "+").grid(row = 1, column = 3)
# ------------------------------- /Row 2/ --------------------------------
btn7 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "7", bg="powder blue").grid(row = 2, column = 0)
btn8 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "8", bg="powder blue").grid(row = 2, column = 1)
btn9 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "9", bg="powder blue").grid(row = 2, column = 2)
btnSubtract = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "-").grid(row = 2, column = 3)
# ------------------------------- /Row 3/ --------------------------------
btn4 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "4", bg="powder blue").grid(row = 3, column = 0)
btn5 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "5", bg="powder blue").grid(row = 3, column = 1)
btn6 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "6", bg="powder blue").grid(row = 3, column = 2)
btnMultiply = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "x").grid(row = 3, column = 3)
# ------------------------------- /Row 4/ --------------------------------
btn1 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "1", bg="powder blue").grid(row = 4, column = 0)
btn2 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "2", bg="powder blue").grid(row = 4, column = 1)
btn3 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "3", bg="powder blue").grid(row = 4, column = 2)
btnDivide = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "÷").grid(row = 4, column = 3)
# ------------------------------- /Row 5/ --------------------------------
btn0 = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "0", bg="powder blue").grid(row = 5, column = 0)
btnDot = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = ".").grid(row = 5, column = 1)
btnPM = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "±").grid(row = 5, column = 2)
btnEquals = Button(calc, pady = 1, bd = 4, fg = "black", font=("arial", 18, "bold"), width = 6, height = 2,
text = "=").grid(row = 5, column = 3)
root.mainloop() |
#!/user/bin/python
# 5 test, 25 real
preambleCount = 25
allowedLowestIndex = 0
numbers = []
def isValid(value, amongNumbers):
#print(amongNumbers)
for first in amongNumbers:
for second in amongNumbers:
if first + second == value:
return True
return False
with open("../input.txt", 'r') as input:
for line in input.readlines():
numbers.append(int(line))
#print(numbers)
valueIndex = preambleCount
while valueIndex < len(numbers):
value = numbers[valueIndex]
#print("Doing value {}".format(value))
if isValid(value, numbers[valueIndex-preambleCount:valueIndex]) is False:
print(value)
break
else:
valueIndex += 1
|
#!/user/bin/python
rules = {}
class BagRule:
def __init__(self, id, contains):
self.id = id
self.contains = contains
def extractBagRule(line):
print(line)
splitted = line.split("contain")
bagID = splitted[0].split("bag")[0].strip()
rules = [x.strip() for x in splitted[1].split(",")]
containing_dict = {}
print(bagID)
print(rules)
if rules == ["no other bags."]:
print("!!!!!!!!")
else:
for rule in rules:
count = rule[0]
ruleBagID = rule[1:].split("bag")[0].strip()
print("Rule")
print(count)
print(ruleBagID)
containing_dict[ruleBagID] = int(count)
return BagRule(bagID, containing_dict)
def getBagCount(bagID, count):
print("Getting bag {} with count {}".format(bagID, count))
rule = rules[bagID]
result = count
if len(rule.contains) == 0:
return result
for (id, subcount) in rule.contains.items():
result += getBagCount(id, subcount*count)
return result
with open("../input.txt", 'r') as input:
for line in input.readlines():
bagRule = extractBagRule(line)
rules[bagRule.id] = bagRule
bags = getBagCount("shiny gold", 1)
bagsWithoutShinyGold = bags -1
print(bagsWithoutShinyGold)
|
#Try catch
try:
print(x)
except:
print("An exception occurred")
else:
print("Nothing went wrong")
finally:
print("The 'try except' is finished")
#RegEx
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
# [] A set of characters "[a-m]"
# \ Signals a special sequence (can also be used to escape special characters) "\d"
# . Any character (except newline character) "he..o"
# ^ Starts with "^hello"
# $ Ends with "world$"
# * Zero or more occurrences "aix*"
# + One or more occurrences "aix+"
# {} Exactly the specified number of occurrences "al{2}"
# | Either or
# \A Returns a match if the specified characters are at the beginning of the string "\AThe"
# \b Returns a match where the specified characters are at the beginning or at the end of a word r"\bain"r"ain\b"
# \B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word r"\Bain" r"ain\B"
# \d Returns a match where the string contains digits (numbers from 0-9) "\d"
# \D Returns a match where the string DOES NOT contain digits "\D"
# \s Returns a match where the string contains a white space character "\s"
# \S Returns a match where the string DOES NOT contain a white space character "\S"
# \w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w"
# \W Returns a match where the string DOES NOT contain any word characters "\W"
# \Z Returns a match if the specified characters are at the end of the string "Spain\Z"
# The findall() function returns a list containing all matches.
# Return an empty list if no match was found:
x = re.findall("ai", str)
# search, solo el primero
x = re.search("\s", str)
#x.span() returns a tuple containing the start-, and end positions of the match.
# x.start() x.end()
#.string returns the string passed into the function
#.group() returns the part of the string where there was a match
# separa en cadenas divididas por lo q le pasemos
x = re.split("\s", str)
#solo la primera vez q salga
x = re.split("\s", str, 1)
#substituye
x = re.sub("\s", "9", str) |
#!/usr/bin/python3
"""
Teste de desenvolvimento criado para a empresa Keeggo
Data: 2021-03-01
Autor: Marcos Thomaz da Silva
"""
import random
from excecoes import *
class Comportamento:
tipo = 'ComportamentoGeral'
def __init__(self, jogador):
self.__jogador = jogador
def pode_comprar(self, propriedade):
return self.saldo >= propriedade.valor_venda and \
self._pode_comprar(propriedade)
def _pode_comprar(self, propriedade):
raise EAbstractMethod()
@property
def saldo(self):
return self.__jogador.saldo
class ComportamentoImpulsivo(Comportamento):
tipo = 'Impulsivo'
def _pode_comprar(self, propriedade):
return True
class ComportamentoExigente(Comportamento):
tipo = 'Exigente'
def _pode_comprar(self, propriedade):
return propriedade.valor_aluguel > 50
class ComportamentoCauteloso(Comportamento):
tipo = 'Cauteloso'
def _pode_comprar(self, propriedade):
return self.saldo - propriedade.valor_venda > 80
class ComportamentoAleatorio(Comportamento):
tipo = 'Aleatório'
def _pode_comprar(self, propriedade):
return random.random() * 100 >= 50.0
|
import random
import string
import time
#greet the user
print("\nhello, Welcome to Passwords Generator!")
print("Let's generate some passwords ^^")
nOfPasswd = int(input('\nHow many passwords you want to generate? (Default 10): ') or "10")
print("")
#asking the user the length of the password.
length = int(input('\nEnter the length of password (default 16): ') or "16")
print("")
#defining some data
#we'll make use of string module for the same time
lower = string.ascii_lowercase
upper = string.ascii_uppercase
num = string.digits
symbols = string.punctuation
#combining and storing data
all = lower + upper + num + symbols
a = 0
while 1:
#we'll make use of random module to generate the password
temp = random.sample(all, length)
a += 1
password = "".join(temp)
#Holding 1 second
time.sleep(1)
#print the password
print(a, " ", password)
#repeat
#print the last message
if a == nOfPasswd:
print("\nThat's all. Thank You")
print("-Created by amaroo77-")
break
|
one = 'Learn'
two = 'Python'
def get_summ(one, two, delimiter='&'):
return (str(one) + str(delimiter) + str(two)).upper()
sum_string = get_summ(one, two)
print(sum_string) |
# -*- coding: utf-8 -*-
import pandas as pd
import sqlite3
'''#load csv file to create db with'''
df = pd.read_csv('https://raw.githubusercontent.com/iesous-kurios/'
'DS-Unit-3-Sprint-2-SQL-and-Databases/master/'
'module1-introduction-to-sql/buddymove_holidayiq.csv')
print(df.shape)
df.head()
df.isnull().sum()
"""#establish connection to new empty db to fill with csv file
"""
# Establish a connection to a new database
conn = sqlite3.connect('buddymove_holidayiq.sqlite3')
#Inserted the data into a new table called "test" in the database
df.to_sql(name = 'test', con = conn)
"""### Counting how many rows"""
# Create a cursor.
curs1 = conn.cursor()
# Write a query
query1 = 'SELECT COUNT(*) FROM test;'
# Execute the query
total_rows = curs1.execute(query1).fetchall()
# Print Answer
print(total_rows)
"""### How many users who reviewed at least 100 Nature in the category also reviewed at least 100 in the Shopping category?"""
print('How many users who reviewed at least 100 Nature in the category also reviewed at least 100 in the Shopping category?')
#Create a cursor.
curs2 = conn.cursor()
#Write a query.
query2 = """
SELECT COUNT(*)
FROM test
WHERE Nature >= 100 AND Shopping >= 100;
"""
#Execute the query.
users = curs2.execute(query2).fetchall()
print(users)
"""### (Stretch) What are the average number of reviews for each category?"""
#Create a cursor.
curs3 = conn.cursor()
#Write a query.
query3 = """
SELECT AVG(Sports), AVG(Religious), AVG(Nature), AVG(Theatre),
AVG(Shopping), AVG(Picnic)
FROM test;"""
#Execute the query()
avg_reviews_column = curs3.execute(query3).fetchall()
print(avg_reviews_column) |
import common
def main() :
dat = common.readFile('day9.dat')
print(find_bad_number(dat))
def check_number(prev, number):
i = 0
valid_number = False
while i < len(prev) - 1:
j = i + 1
while j < len(prev):
if (int(prev[i]) + int(prev[j])) == int(number) :
valid_number = True
j = j + 1
i = i + 1
return not valid_number
def find_bad_number(numbers):
found_bad_number = False
prev = numbers[0:25]
numbers_to_check = numbers[25:]
bad_number = 0
while not found_bad_number and len(numbers_to_check) > 0:
num_to_check = numbers_to_check[0]
found_bad_number = check_number(prev, num_to_check)
if found_bad_number:
bad_number = num_to_check
del prev[0]
prev.append(num_to_check)
del numbers_to_check[0]
return bad_number
if __name__ == '__main__':
main() |
from collections import namedtuple
Point = namedtuple('Point',['x','y'],verbose=True)
p=[1,2]
d = Point._make(p)
print(d)
print(d._asdict())
print(d._replace(x=3))
|
# encoding:utf-8
# @Time : 2019/5/13 9:27
# @Author : Jerry Chou
# @File : common.py
# @Function : 公共方法
def show_cards(cards):
"""
显示卡牌
:param cards:
:return:
"""
for i, card in enumerate(cards):
print("\t{0}-{1}({2})".format(i + 1, card.name, card.present_mana), end='')
if card.present_property != '':
print("[{0}]".format(card.present_property))
else:
print("")
def input_int(desc):
"""
整数输入
:param desc:
:return:
"""
while True:
try:
user_input = int(input(desc))
return user_input
except:
print('您输入的内容不规范,请重新输入!')
def choose_direct_num(direct_list, desc):
"""
选择指向性目标
:param direct_list:
:param desc:
:return:
"""
direct_num = input_int(desc)
if direct_num == 0:
return direct_num
if direct_num < 0 or direct_num > len(direct_list):
print("输入数字超出范围,请重新输入!")
return choose_direct_num(direct_list, desc)
if search_for_property(direct_list, 'AntiMagic', 1, True):
if direct_list[direct_num - 1].present_property.find('AntiMagic') != -1:
print("魔免的卡牌无法被选中!")
return choose_direct_num(direct_list, desc)
return direct_num
def choose_object_num(object_list, desc):
"""
选择目标
:param object_list:
:param desc:
:return:
"""
object_num = input_int(desc)
if object_num < 0 or object_num > len(object_list):
print("输入数字超出范围,请重新输入!")
return choose_object_num(object_list, desc)
else:
return object_num
def choose_attack_num(attack_list, desc):
"""
选择物理攻击目标
:param attack_list:
:param desc:
:return:
"""
attack_num = input_int(desc)
if attack_num == 0:
return attack_num
elif attack_num < 0 or attack_num > len(attack_list):
print("输入数字超出范围,请重新输入!")
return choose_attack_num(attack_list, desc)
if search_for_property(attack_list, 'Taunt', 1, False):
if attack_list[attack_num - 1].present_property.find('Taunt') == -1:
print("必须攻击具有嘲讽属性的卡牌!")
return choose_attack_num(attack_list, desc)
if search_for_property(attack_list, 'Stealth', 1, True):
if attack_list[attack_num - 1].present_property.find('Stealth') != -1:
print("潜行的卡牌无法被攻击!")
return choose_attack_num(attack_list, desc)
return attack_num
def search_for_damage(card_list, damage, calc, includeStealth):
"""
是否存在相应攻击力的卡牌
:param card_list:
:param calc: 1-等于 2-大于 3-小于 4-大于等于 5-小于等于
:param damage:
:param includeStealth: True 包含隐藏 False 不包含隐藏
:return:
"""
if calc == 1:
for card in card_list:
if includeStealth:
if card.present_damage == damage:
return True
else:
if card.present_damage == damage and card.present_property.find('Stealth') == -1:
return True
elif calc == 2:
for card in card_list:
if includeStealth:
if card.present_damage > damage:
return True
else:
if card.present_damage > damage and card.present_property.find('Stealth') == -1:
return True
elif calc == 3:
for card in card_list:
if includeStealth:
if card.present_damage < damage:
return True
else:
if card.present_damage < damage and card.present_property.find('Stealth') == -1:
return True
elif calc == 4:
for card in card_list:
if includeStealth:
if card.present_damage >= damage:
return True
else:
if card.present_damage >= damage and card.present_property.find('Stealth') == -1:
return True
elif calc == 5:
for card in card_list:
if includeStealth:
if card.present_damage <= damage:
return True
else:
if card.present_damage <= damage and card.present_property.find('Stealth') == -1:
return True
return False
def search_for_health(card_list, health, calc, includeStealth):
"""
是否存在相应生命值的卡牌
:param card_list:
:param calc: 1-等于 2-大于 3-小于 4-大于等于 5-小于等于
:param health:
:param includeStealth: True 包含隐藏 False 不包含隐藏
:return:
"""
if calc == 1:
for card in card_list:
if includeStealth:
if card.remain_health == health:
return True
else:
if card.remain_health == health and card.present_property.find('Stealth') == -1:
return True
elif calc == 2:
for card in card_list:
if includeStealth:
if card.remain_health > health:
return True
else:
if card.remain_health > health and card.present_property.find('Stealth') == -1:
return True
elif calc == 3:
for card in card_list:
if includeStealth:
if card.remain_health < health:
return True
else:
if card.remain_health < health and card.present_property.find('Stealth') == -1:
return True
elif calc == 4:
for card in card_list:
if includeStealth:
if card.remain_health >= health:
return True
else:
if card.remain_health >= health and card.present_property.find('Stealth') == -1:
return True
elif calc == 5:
for card in card_list:
if includeStealth:
if card.remain_health <= health:
return True
else:
if card.remain_health <= health and card.present_property.find('Stealth') == -1:
return True
return False
def search_for_id(card_list, card_id):
"""
从指定的列表中查询卡牌id是否存在
:param card_id:
:param card_list:
:return:
"""
index_list = []
for index, card in enumerate(card_list):
if card.id == card_id:
index_list.append(index)
return index_list
def search_for_race(card_list, card_race, calc):
"""
从指定的列表中查询卡牌种族
:param card_race:
:param card_list:
:param calc: 1-存在 2-全部都是
:return:
"""
if calc == 1:
for card in card_list:
if card.race == card_race:
return True
return False
elif calc == 2:
for card in card_list:
if card.race != card_race:
return False
return True
def search_for_property(card_list, card_property, calc, includeStealth):
"""
从指定的列表中查询卡牌属性
:param card_property:
:param card_list:
:param calc: 1-包含 2-不包含
:param includeStealth: True 包含隐藏 False 不包含隐藏
:return:
"""
if calc == 1:
for card in card_list:
if includeStealth:
if card.present_property.find(card_property) != -1:
return True
else:
if card.present_property.find(card_property) != -1 and card.present_property.find('Stealth') == -1:
return True
elif calc == 2:
if len(card_list) == 0:
return True
else:
for card in card_list:
if includeStealth:
if card.present_property.find(card_property) == -1:
return True
else:
if card.present_property.find(card_property) == -1 and card.present_property.find('Stealth') == -1:
return True
return False
def search_damage(card_list, damage):
"""
找到攻击力为damage的卡牌
:param card_list:
:param damage:
:return:
"""
search_result = []
for card in card_list:
if card.present_damage == damage:
search_result.append(card)
return search_result
def search_race(card_list, card_race):
"""
从指定的列表中查询卡牌种族
:param card_race:
:param card_list:
:return:
"""
search_result = []
for card in card_list:
if card.race == card_race:
search_result.append(card)
return search_result
def search_property(card_list, card_property, calc, includeStealth):
"""
从指定的列表中查询卡牌属性
:param card_property:
:param card_list:
:param calc: 1-包含 2-不包含
:param includeStealth: True 包含隐藏 False 不包含隐藏
:return:
"""
search_result = []
if calc == 1:
for card in card_list:
if includeStealth:
if card.present_property.find(card_property) != -1:
search_result.append(card)
else:
if card.present_property.find(card_property) != -1 and card.present_property.find('Stealth') == -1:
search_result.append(card)
elif calc == 2:
for card in card_list:
if includeStealth:
if card.present_property.find(card_property) == -1:
search_result.append(card)
else:
if card.present_property.find(card_property) == -1 and card.present_property.find('Stealth') == -1:
search_result.append(card)
return search_result
def search_color(card_list, card_color):
"""
从指定的列表中查询卡牌成色
:param card_color:
:param card_list:
:return:
"""
search_result = []
for card in card_list:
if card.color == card_color:
search_result.append(card)
return search_result
def search_type(card_list, card_type):
"""
从指定的列表中查询卡牌类型
:param card_type:
:param card_list:
:return:
"""
search_result = []
for card in card_list:
if card.type == card_type:
search_result.append(card)
return search_result
def search_hero(card_list, hero):
"""
从指定的列表中查询所属阵营
:param card_list:
:param hero:
:return:
"""
search_result = []
for card in card_list:
if card.hero == hero:
search_result.append(card)
return search_result
def search_occupation(card_list, card_occupation):
"""
从指定的列表中查询卡牌所属
:param card_occupation:
:param card_list:
:return:
"""
search_result = []
for card in card_list:
if card.occupation == card_occupation:
search_result.append(card)
return search_result
def search_occupation_type(card_list, card_occupation, card_type):
"""
从指定的列表中查询卡牌所属的卡牌类型
:param card_list:
:param card_occupation:
:param card_type:
:return:
"""
search_result = []
for card in card_list:
if card.occupation == card_occupation and card.type == card_type:
search_result.append(card)
return search_result
def smart_attack(my_card, card_list):
"""
智能攻击
:param my_card:
:param card_list:
:return:
"""
my_remain_health = my_card.remain_health + my_card.armor - card_list[0].present_damage
attack_card_remain_health = card_list[0].remain_health + card_list[0].armor - my_card.present_damage
attack_card = card_list[0]
if len(card_list) > 1:
for card in card_list[1:]:
my_health = my_card.remain_health + my_card.armor - card.present_damage
attack_health = card.remain_health + card.armor - my_card.present_damage
if not (my_health <= 0 and attack_health > 0) and (
(attack_health <= attack_card_remain_health and my_health >= my_remain_health) or (
attack_health <= attack_card_remain_health and 0 < my_health < my_remain_health) or (
attack_health <= 0 <= attack_card_remain_health) or (
attack_card_remain_health <= attack_health <= 0 and my_health >= my_remain_health) or (
attack_card_remain_health <= attack_health <= 0 and 0 < my_health < my_remain_health and card.present_damage >= attack_card.present_damage)):
my_remain_health = my_health
attack_card_remain_health = attack_health
attack_card = card
return attack_card
def all_smart_attack_one(card_list, attack_card):
"""
多打一
:param card_list:
:param attack_card:
:return:
"""
total_present_damage = 0
attack_list = []
smart_value_order(card_list, False)
if search_for_damage(card_list, attack_card.remain_health + attack_card.armor, 4, True):
smart_damage_order(card_list)
if (card_list[0].remain_health + card_list[0].armor > attack_card.present_damage and card_list[
0].value <= 5 * attack_card.value) or (
card_list[0].remain_health + card_list[0].armor <= attack_card.present_damage and card_list[
0].value <= 3 * attack_card.value):
return [card_list[0]]
else:
for card in card_list:
total_present_damage += card.present_damage
attack_list.append(card)
if total_present_damage >= attack_card.remain_health + attack_card.armor:
return attack_list
def all_smart_attack_all(attack_list, beaten_list):
"""
多打多
:param attack_list:
:param beaten_list:
:return: 击打双方
"""
smart_value_order(beaten_list, True)
for follower in beaten_list:
attack_follower_list = all_smart_attack_one(attack_list, follower)
if attack_follower_list is not None:
return attack_follower_list[0], follower
def smart_property_order(card_list, order):
"""
特殊属性排序,相同属性血量高的前置
:param order: True 特殊属性前置 False 特殊属性后置
:param card_list:
:return:
"""
length = len(card_list)
for i in range(length):
temp = card_list[i]
for j in range(i + 1, length):
if order:
if (card_list[i].present_property == '' and card_list[j].present_property != '') or (
card_list[i].present_property.find('Taunt') == -1 and card_list[
j].present_property.find(
'Taunt') != -1) or (
card_list[i].present_property == card_list[j].present_property and card_list[
i].remain_health <
card_list[j].remain_health):
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
else:
if (card_list[i].present_property != '' and card_list[j].present_property == '') or (
card_list[i].present_property.find('Taunt') != -1 and card_list[
j].present_property.find(
'Taunt') == -1):
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
def smart_damage_order(card_list):
"""
攻击从大到小排列,相同攻击力(血量多的、有突袭的前置)
:param card_list:
:return:
"""
length = len(card_list)
for i in range(length):
temp = card_list[i]
for j in range(i + 1, length):
if (card_list[i].present_damage < card_list[j].present_damage) or (
card_list[i].present_damage == card_list[j].present_damage and (card_list[i].remain_health <
card_list[
j].remain_health or
card_list[
j].present_property.find(
'Rush') != -1)):
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
def smart_mana_order(card_list):
"""
法力值从大到小排列
:param card_list:
:return:
"""
length = len(card_list)
for i in range(length):
temp = card_list[i]
for j in range(i + 1, length):
if card_list[i].mana < card_list[j].mana:
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
def smart_health_order(card_list):
"""
生命值从大到小排列,生命值相同,把有属性的对象排在前面
:param card_list:
:return:
"""
length = len(card_list)
for i in range(length):
temp = card_list[i]
for j in range(i + 1, length):
if (card_list[i].remain_health < card_list[j].remain_health) or (
card_list[i].remain_health == card_list[j].remain_health and card_list[
i].present_property == '' and card_list[j].present_property != ''):
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
def smart_value_order(card_list, order):
"""
根据卡牌价值排序
:param order: True 从大到小 False 从小到大
:param card_list:
:return:
"""
length = len(card_list)
for i in range(length):
temp = card_list[i]
for j in range(i + 1, length):
if order:
if card_list[i].value < card_list[j].value or (
card_list[i].value == card_list[j].value and card_list[i].present_damage < card_list[
j].present_damage):
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
else:
if card_list[i].value > card_list[j].value or (
card_list[i].value == card_list[j].value and card_list[i].present_damage > card_list[
j].present_damage):
card_list[i] = card_list[j]
card_list[j] = temp
temp = card_list[i]
def remove_duplicate(card_list):
"""
去重
:param card_list:
:return:
"""
li = []
for item in card_list:
for li_item in li:
if item.name == li_item.name:
break
else:
li.append(item)
return li
def cal_value(card):
"""
计算卡牌的价值
:param card:
:return:
"""
value = card.present_damage + card.remain_health * 0.5
if card.present_property.find('Special') != -1 or card.present_property.find(
'MyRoundBegin') != -1 or card.present_property.find(
'MyRoundEnd') != -1 or card.present_property.find('EveryRoundEnd') != -1:
value *= 5
if card.present_property.find('Halo') != -1 or card.present_property.find(
'Toxic') != -1 or card.present_property.find('WindAngry') != -1:
value *= 4
if card.present_property.find('BloodSucking') != -1 or card.present_property.find(
'DivineShield') != -1 or card.present_property.find('AntiMagic') != -1:
value *= 1.5
return value
|
a = int(input("Enter the number of steps: "))
b = input("Enter the symbol of steps: ")
c = input("Which way will the stairs go (left, right): ")
if c == "left":
# Left
for i in range(1, a+1):
print(b * i)
elif c == "right":
# Right
for i in range(1, a + 1):
print((" " * (a - i)), b * i)
else:
print("Your enter invalid, please enter again")
|
def posl(numbers):
tmp = 0
maxim = 0
a = [numbers]
while numbers != 0:
numbers = int(input("Enter your number: "))
a.append(numbers)
for i in range(1, len(a)):
if a[i] == a[i - 1]:
tmp += 1
if a[i] != a[i - 1]:
if tmp > maxim:
maxim = tmp
tmp = 0
print(maxim + 1)
posl(int(input('Enter your number: ')))
|
# Quine McCluskey
# Take in a logical expression
# Go through and count the number of variables
# num = 2^{varcount} - 1
# for i in range(num):
# if checkTrue(i):
# add to list
# make varcount number of tables
# loop through list values and put into tables sorting by number of 1s
# combine values in each adjacent group until nothing to combine left
# spit out remaining indices and convert to binary to find minimized expression
def checkTrue(input, index, variables):
# Takes in input and then for each variable inputs the value
# we have been given in index form and returns truth value
val = indexTovals(index)
return false
def indexTovals():
return None
def countVars(input, variables):
return 0
def McCluskey(input):
minterms = []
variables = []
varCount = countVars(input, variables)
num = pow(2, varCount) - 1
for i in range(num):
if checkTrue(input, i, variables):
minterms.append(i)
tables = [[] for i in range(varCount)]
# combining
|
import string
# def encrypt(text,shift):
# encrypted_text = list(range(len(text)))
# alphabet = string.ascii_lowercase
#
# first_half = alphabet[:shift]
# second_half = alphabet[shift:]
#
# shifted_alphabet = second_half+first_half
#
# for i,letter in enumerate(text.lower()):
# if letter in alphabet:
# original_index = alphabet.index(letter)
# new_letter = shifted_alphabet[original_index]
# encrypted_text[i] = new_letter
# else:
# encrypted_text[i] = letter
#
# return ''.join(encrypted_text)
#
# print(encrypt('get this message to the server', 13))
def decrypt(text, shift):
decrypted_text = list(range(len(text)))
alphabet = string.ascii_lowercase
first_half = alphabet[shift:]
second_half = alphabet[:shift]
shifted_alphabet = second_half+first_half
for i,letter in enumerate(text.lower()):
if letter in alphabet:
index = alphabet.index(letter)
original_letter = alphabet[index]
decrypted_text[i] = original_letter
else:
decrypted_text[i] = letter
return ''.join(decrypted_text)
print(decrypt('trg guvf zrffntr gb gur freire', 13)) |
import random
mystring = "Secret agents are super good at staying hidden."
# for word in mystring.split():
# first_letter = word.lower()[0]
#
# if first_letter =='s':
# print(word)
# for word in mystring.split():
# if len(word)% 2 == 0:
# print(word)
# word=[word[0] for word in mystring.split()]
# print(word)
# even=[n for n in range(0,11) if n%2==0]
# print(even)
# rangeex = list(range(0,11,2))
# print(rangeex)
# result = []
# for x in range(0,11):
# result.append(random.randint(0,100))
# print(result)
# result = [random.randint(0,100) for n in range(0,11)]
# print(result)
result = 3
while result %2 != 0:
num = int(input("enter a number"))
if num%2 !=0:
result = 3
else:
print("Thank you, that is an even number")
result=2 |
greetings = "Hi"
name = "Touhid"
message = greetings + " " + name
print(message)
age = 25
message = "Your age is: " + str(age)
print(message)
height = 5.10
message = "Your height is: " + str(height) + " feet."
print(message)
string_to_int = int("100")
string_to_float = float("100.01")
float_to_string = str(100.01)
float_to_int = int(100.01)
int_to_string = str(100)
print(float_to_int)
|
# This is a comment of python
# print is responsible for write/show something into console
print("This is Bismillah Program") # We can add comment in same line of code execution
"""
Example of Multiline comments
The sum method is responsible for addition of 2 number and return them
"""
def sum(first, second):
return first + second
print(sum(10, 20))
|
from tkinter import *
from tkinter import messagebox
#from gtts import gTTS
root=Tk()
root.title("Tic Tac Toe")
global bclick
bclick=True
def close():
exit()
def reset():
button1["text"]=""
button2["text"]=""
button3["text"]=""
button4["text"]=""
button5["text"]=""
button6["text"]=""
button7["text"]=""
button8["text"]=""
button9["text"]=""
def winMethod():
if (button1["text"]=="X" and button2["text"]=="X" and button3["text"]=="X" or
button1["text"]=="X" and button5["text"]=="X" and button9["text"]=="X" or
button1["text"]=="X" and button4["text"]=="X" and button7["text"]=="X" or
button4["text"]=="X" and button5["text"]=="X" and button6["text"]=="X" or
button7["text"]=="X" and button8["text"]=="X" and button9["text"]=="X" or
button3["text"]=="X" and button5["text"]=="X" and button7["text"]=="X" or
button2["text"]=="X" and button5["text"]=="X" and button8["text"]=="X" or
button3["text"]=="X" and button6["text"]=="X" and button9["text"]=="X"
):
messagebox.showinfo( "Winning Message", "X is WINNER")
reset()
if (button1["text"]=="O" and button2["text"]=="O" and button3["text"]=="O" or
button1["text"]=="O" and button5["text"]=="O" and button9["text"]=="O" or
button1["text"]=="O" and button4["text"]=="O" and button7["text"]=="O" or
button4["text"]=="O" and button5["text"]=="O" and button6["text"]=="O" or
button7["text"]=="O" and button8["text"]=="O" and button9["text"]=="O" or
button3["text"]=="O" and button5["text"]=="O" and button7["text"]=="O" or
button2["text"]=="O" and button5["text"]=="O" and button8["text"]=="O" or
button3["text"]=="O" and button6["text"]=="O" and button9["text"]=="O"
):
messagebox.showinfo( "Winning Message", "O is WINNER")
reset()
def tictactoe(buttons):
global bclick
if buttons["text"]=="" and bclick==True:
buttons["text"]="X"
bclick=False
winMethod()
elif buttons["text"]=="" and bclick==False:
buttons["text"]="O"
bclick=True
winMethod()
button1=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button1))
button1.grid(row=1,column=0)
button2=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button2))
button2.grid(row=1,column=1)
button3=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button3))
button3.grid(row=1,column=2)
button4=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button4))
button4.grid(row=2,column=0)
button5=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button5))
button5.grid(row=2,column=1)
button6=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button6))
button6.grid(row=2,column=2)
button7=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button7))
button7.grid(row=3,column=0)
button8=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button8))
button8.grid(row=3,column=1)
button9=Button(root,text="",font=('Arial 30 bold'),height=1,width=2,command=lambda :tictactoe(button9))
button9.grid(row=3,column=2)
button10=Button(root,text="Reset Game ",font=('Arial 9 bold'),height=1,width=6,command=reset)
button10.grid(row=4,column=0,columnspan=3,sticky=S+N+E+W)
button11=Button(root,text="Exit Game ",font=('Arial 9 bold'),height=1,width=6)
button11.grid(row=5,column=0,columnspan=3,sticky=S+N+E+W)
root.resizable(0,0) # Dsabling WIndow Resize
root.mainloop()
|
'''
Daniel McNulty II
Last Modified: 08/15/2018
The Monty Hall Problem
This code:
a) Creates and initializes five processes for never switching door simulations.
b) Executes all five processes. Give each process 1/5 of the total simulations (2,000,000 each).
c) Combines the five returned results lists and takes the average, to get the overall result.
d) All of the above is timed (starting from b).
e) Steps a through d are repeated for always switching door simulations.
'''
# Import the MontyHallGame class from the game module in the Monty_Hall_Problem_Simulation package
from Monty_Hall_Problem_Simulation.game import MontyHallGame
# Import the AlwaysSwitchPlayer and NeverSwitchPlayer classes from the player module in the
# Monty_Hall_Problem_Simulation package
from Monty_Hall_Problem_Simulation.player import AlwaysSwitchPlayer, NeverSwitchPlayer
# Import the Timer class from the timer module
from timer import Timer
# Import the logging module
import logging
# Import the multiprocessing module
import multiprocessing
'''
monty_hall_sim Function:
Takes in the number of trials to perform and the name of the player type to perform them on. Returns a generator with
the results of all the trials.
'''
def monty_hall_sim(num_trial, player_type='AlwaysSwitchPlayer'):
# If the user inputs 'NeverSwitchPlayer' for the player_type, then set the variable player equal to a
# NeverSwitchPlayer object.
if player_type == 'NeverSwitchPlayer':
player = NeverSwitchPlayer('Never Switch Player')
# If the user does not input 'NeverSwitchPlayer' for the player_type, then set the variable player equal to a
# AlwaysSwitchPlayer object.
else:
player = AlwaysSwitchPlayer('Always Switch Player')
# Use a list comprehension to return a list with num_trial amount of simulation results from the MontyHallGame class
# play_game function with the above created player variable as its input.
return [MontyHallGame().play_game(player) for trial in range(num_trial)]
'''
do_work Function:
Takes in 2 queues, in_queue and out_queue. in_queue should contain tuples with (Function_Name, (Function_Args,)), since
the do_work function takes the function associated with the input_queue tuple Function_Name and passes the *args tuple
(Function_Args,) into it. Then it puts the result of the output from Function_Name(*(Function_Args,)) into the out_queue
using the result and the queue put function within map.
'''
def do_work(in_queue, out_queue):
# Unpack the tuple returned by in_queue.get() and store the contents in f and args.
f, args = in_queue.get()
# Call the function referred to by f with input parameter being the unpacked args tuple from above. Store
# the result in variable ret
ret = f(*args)
# Use store the result ret in the output queue out_queue
out_queue.put(ret)
'''
Main Program:
a) Creates and initializes five processes for never switching door simulations.
b) Executes all five processes. Give each process 1/5 of the total simulations (2,000,000 each).
c) Combines the five returned results lists and takes the average, to get the overall result.
d) All of the above is timed (starting from b).
e) Steps a through d are repeated for always switching door simulations.
'''
def main():
# Let users know the following output is for Exercise Monty_Hall_Main_Codes.1
print('\nThe Monty Hall Problem')
# Get the Logger from the logging package using getLogger() and use setLevel to set logging.ERROR to the lowest
# level of logging that will work. This was to keep the WARN log from timer off the screen when timing in part E,
# since we know that that part takes a significant amount of time.
logging.getLogger().setLevel(logging.ERROR)
# SETTING THE TOTAL SIMULATIONS AND NUMBER OF PROCESSES TO RUN =====================================================
# Set the total amount of simulations, total_sims, to 10,000,000, the total number of processes, num_processes, to
# 5, and the amount of simulations to be allotted to each process, process_sims, to the quotient of
# total_sims/num_processes
total_sims = 10000000
num_processes = 5
process_sims = int(total_sims/num_processes)
# NEVER SWITCH PLAYER SIMULATIONS ==================================================================================
print('\n========================================================================================================'
'\nNever Switch Doors Strategy Simulation:')
# Initialize an input queue, never_switch_input_queue, and output queue, never_switch_output_queue, using
# multiprocessing.Queue()
never_switch_input_queue = multiprocessing.Queue()
never_switch_output_queue = multiprocessing.Queue()
# Put num_processes amount of tuples with (monty_hall_sim, (process_sims, 'NeverSwitchPlayer)) into the input
# queue always_switch_input_queue
for i in range(num_processes):
never_switch_input_queue.put((monty_hall_sim, (process_sims, 'NeverSwitchPlayer')))
# Create a generator of num_processes processes, with target function do_work and args
# (never_switch_input_queue, never_switch_output_queue)
never_procs = (multiprocessing.Process(target=do_work, args=(never_switch_input_queue, never_switch_output_queue))
for i in range(num_processes))
# Use a with statement to start a timer called 'Never Switch Timer'
with Timer(timer_name='Never Switch Timer'):
# Use a for loop to start all the above made processes using start()
for proc in never_procs:
proc.start()
# Initialize an empty list and store it in variable never_switch_res
never_switch_res = []
# Initialize a while loop that will continuously iterate until the never_switch_res list is equal in size to
# the total_sims
while len(never_switch_res) != total_sims:
# Get the next list in the queue never_switch_output_queue using get() and add it to the list
# never_switch_res using extend.
never_switch_res.extend(never_switch_output_queue.get())
# Count the number of times True appears in the never_switch_res list and cast the result to a float. Then
# divide that by the length of the never_switch_res list cast to a float in order to calculate the percentage of
# times always switching doors resulted in the player winning the game. This percentage should be the
# approximate probability of winning when not switching doors. Store this result in the variable
# never_switch_success.
never_switch_success = float(never_switch_res.count(True))/float(len(never_switch_res))
# Print the length of never_switch_res to confirm that it has the proper number of simulations in it and the print
# the success average of not switching doors, never_switch_success, found above.
print('\tLength of Never Switch Result List: {alw_sw_len}'.format(alw_sw_len=len(never_switch_res)))
print('\tThe success average of not switching doors was: {alw_sw_prob}'.format(alw_sw_prob=never_switch_success))
# ALWAYS SWITCH PLAYER SIMULATIONS =================================================================================
print('\n========================================================================================================'
'\nAlways Switch Doors Strategy Simulation:')
# Initialize an input queue, always_switch_input_queue, and output queue, always_switch_output_queue, using
# multiprocessing.Queue()
always_switch_input_queue = multiprocessing.Queue()
always_switch_output_queue = multiprocessing.Queue()
# Put num_processes amount of tuples with (monty_hall_sim, (process_sims, 'AlwaysSwitchPlayer)) into the input
# queue always_switch_input_queue
for i in range(num_processes):
always_switch_input_queue.put((monty_hall_sim, (process_sims, 'AlwaysSwitchPlayer')))
# Create a generator of num_processes processes, with target function do_work and args
# (always_switch_input_queue, always_switch_output_queue)
procs = (multiprocessing.Process(target=do_work, args=(always_switch_input_queue, always_switch_output_queue))
for i in range(num_processes))
# Use a with statement to start a timer called 'Always Switch Timer'
with Timer(timer_name='Always Switch Timer'):
# Use a for loop to start all the above made processes using start()
for proc in procs:
proc.start()
# Initialize an empty list and store it in variable always_switch_res
always_switch_res = []
# Initialize a while loop that will continuously iterate until the always_switch_res list is equal in size to
# the total_sims
while len(always_switch_res) != total_sims:
# Get the next list in the queue always_switch_output_queue using get() and ADD it to the list
# always_switch_res using extend.
always_switch_res.extend(always_switch_output_queue.get())
# Count the number of times True appears in the always_switch_res list and cast the result to a float. Then
# divide that by the length of the always_switch_res list cast to a float in order to calculate the percentage
# of times always switching doors resulted in the player winning the game. This percentage should be the
# approximate probability of winning when switching doors. Store this result in the variable
# always_switch_success.
always_switch_success = float(always_switch_res.count(True))/float(len(always_switch_res))
# Print the length of always_switch_res to confirm that it has the proper number of simulations in it and the print
# the success average of switching doors, always_switch_success, found above.
print('\tLength of Always Switch Result List: {alw_sw_len}'.format(alw_sw_len=len(always_switch_res)))
print('\tThe success average of switching doors was: {alw_sw_prob}'.format(alw_sw_prob=always_switch_success))
########################################################################################################################
if __name__ == '__main__':
main()
|
"""
Get all text from csv files and extract the vocabulary
The csv files have the following columns
['img_id', 'sent_id', 'split', 'asin', 'folder', 'sentence']
"""
import pandas as pd
import collections
# Read in csv file and write vocabulary
with_zappos = 'no_zappos'
# with_zappos = 'with_ngrams' # only_zappos is not needed because it already exists from zappos
fname = '../../../../data/fashion53k/csv/fashion53k_{}.csv'.format(with_zappos)
sentences_df = pd.read_csv(fname)
# print sentences_df[0:10]
sentences_df.columns = ['img_id', 'sent_id', 'split', 'asin', 'folder', 'sentence']
# print sentences_df.columns
text = ''
for item in sentences_df['sentence']:
text += item + ' '
# print text
data = text.split()
counter = collections.Counter(data)
count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
top_count_pairs = [pair for pair in count_pairs if pair[1] > 5] # keep words that occur more than 5 fimes
vocabulary_words, _ = list(zip(*top_count_pairs))
fname = '../../../../data/fashion53k/vocab/vocab_{}.txt'.format(with_zappos)
fout = open(fname, 'wb')
for item in vocabulary_words:
print>>fout, item
fout.close()
# print "vocabulary size", len(vocabulary_words), with_zappos
#
# print vocabulary_words
# csvfile = open('eggs.csv', 'rb')
# csvreader = csv.reader(csvfile)
#
# for row in csvreader:
# content = list(row[i] for i in included_cols)
# print content
import collections
|
"""
Kingsheep Agent Template
This template is provided for the course 'Practical Artificial Intelligence' of the University of Zürich.
Please edit the following things before you upload your agent:
- change the name of your file to '[uzhshortname]_A1.py', where [uzhshortname] needs to be your uzh shortname
- change the name of the class to a name of your choosing
- change the def 'get_class_name()' to return the new name of your class
- change the init of your class:
- self.name can be an (anonymous) name of your choosing
- self.uzh_shortname needs to be your UZH shortname
The results and rankings of the agents will be published on OLAT using your 'name', not 'uzh_shortname',
so they are anonymous (and your 'name' is expected to be funny, no pressure).
"""
import random
from collections import deque
from config import *
from operator import add
import copy
MOVE_COORDS = {(0, +1), (0, -1), (+1, 0), (-1,0)}
def bfs(obstacles, start, end_coords):
"""
Returns a dictionary with tuples (x, y) as keys indicating coordinates, and
a list of tuples (x, y) as values indicating the path from the given start
to the key's cordinate considering the given obstacles.
"""
seen = set([start])
queue = deque([[start]])
end_coords = set(end_coords)
paths = {}
while queue and end_coords:
path = queue.popleft()
current = path[-1]
# Found an objective, yield objective and path
if current in end_coords:
end_coords.remove(current)
paths[current] = path
# Try each direction
for coord in [tuple(map(add, current, i)) for i in MOVE_COORDS]:
if not (0 <= coord[0] < FIELD_HEIGHT and 0 <= coord[1] < FIELD_WIDTH):
continue
if coord in seen or coord in obstacles:
continue
queue.append(path + [coord])
seen.add(coord)
return paths
def get_class_name():
return 'Joe'
class Joe():
"""Example class for a Kingsheep player"""
def __init__(self):
self.name = "masern_at_IFI"
self.uzh_shortname = "joabau"
def get_sheep_model(self):
return None
def get_wolf_model(self):
return None
def get_player_position(self, figure, field):
x = [x for x in field if figure in x][0]
return (field.index(x), x.index(figure))
# defs for sheep
def food_present(self, field):
food_present = False
for line in field:
for item in line:
if item == CELL_RHUBARB or item == CELL_GRASS:
food_present = True
break
return food_present
def closest_goal(self, player_number, field):
possible_goals = []
if player_number == 1:
sheep_position = self.get_player_position(CELL_SHEEP_1, field)
else:
sheep_position = self.get_player_position(CELL_SHEEP_2, field)
# make list of possible goals
y_position = 0
for line in field:
x_position = 0
for item in line:
if item == CELL_RHUBARB or item == CELL_GRASS:
possible_goals.append((y_position, x_position))
x_position += 1
y_position += 1
# determine closest item and return
distance = 1000
for possible_goal in possible_goals:
if (abs(possible_goal[0] - sheep_position[0]) + abs(possible_goal[1] - sheep_position[1])) < distance:
distance = abs(possible_goal[0] - sheep_position[0]) + abs(possible_goal[1] - sheep_position[1])
final_goal = (possible_goal)
return final_goal
def gather_closest_goal(self, closest_goal, field, figure):
figure_position = self.get_player_position(figure, field)
distance_x = figure_position[1] - closest_goal[1]
distance_y = figure_position[0] - closest_goal[0]
if distance_x == 0:
# print('item right above/below me')
if distance_y > 0:
if self.valid_move(figure, figure_position[0] - 1, figure_position[1], field):
return MOVE_UP
else:
return MOVE_RIGHT
else:
if self.valid_move(figure, figure_position[0] + 1, figure_position[1], field):
return MOVE_DOWN
else:
return MOVE_RIGHT
elif distance_y == 0:
# print('item right beside me')
if distance_x > 0:
if self.valid_move(figure, figure_position[0], figure_position[1] - 1, field):
return MOVE_LEFT
else:
return MOVE_UP
else:
if self.valid_move(figure, figure_position[0], figure_position[1] + 1, field):
return MOVE_RIGHT
else:
return MOVE_UP
else:
# go left or up
if distance_x > 0 and distance_y > 0:
if self.valid_move(figure, figure_position[0], figure_position[1] - 1, field):
return MOVE_LEFT
else:
return MOVE_UP
# go left or down
elif distance_x > 0 and distance_y < 0:
if self.valid_move(figure, figure_position[0], figure_position[1] - 1, field):
return MOVE_LEFT
else:
return MOVE_DOWN
# go right or up
elif distance_x < 0 and distance_y > 0:
if self.valid_move(figure, figure_position[0], figure_position[1] + 1, field):
return MOVE_RIGHT
else:
return MOVE_UP
# go right or down
elif distance_x < 0 and distance_y < 0:
if self.valid_move(figure, figure_position[0], figure_position[1] + 1, field):
return MOVE_RIGHT
else:
return MOVE_DOWN
else:
print('fail')
return MOVE_NONE
def wolf_close(self, player_number, field):
if player_number == 1:
sheep_position = self.get_player_position(CELL_SHEEP_1, field)
wolf_position = self.get_player_position(CELL_WOLF_2, field)
else:
sheep_position = self.get_player_position(CELL_SHEEP_2, field)
wolf_position = self.get_player_position(CELL_WOLF_1, field)
if (abs(sheep_position[0] - wolf_position[0]) <= 2 and abs(sheep_position[1] - wolf_position[1]) <= 2):
# print('wolf is close')
return True
return False
def valid_move(self, figure, x_new, y_new, field):
# Neither the sheep nor the wolf, can step on a square outside the map. Imagine the map is surrounded by fences.
if x_new > FIELD_HEIGHT - 1:
return False
elif x_new < 0:
return False
elif y_new > FIELD_WIDTH - 1:
return False
elif y_new < 0:
return False
# Neither the sheep nor the wolf, can enter a square with a fence on.
if field[x_new][y_new] == CELL_FENCE:
return False
# Wolfs can not step on squares occupied by the opponents wolf (wolfs block each other).
# Wolfs can not step on squares occupied by the sheep of the same player .
if figure == CELL_WOLF_1:
if field[x_new][y_new] == CELL_WOLF_2:
return False
elif field[x_new][y_new] == CELL_SHEEP_1:
return False
elif figure == CELL_WOLF_2:
if field[x_new][y_new] == CELL_WOLF_1:
return False
elif field[x_new][y_new] == CELL_SHEEP_2:
return False
# Sheep can not step on squares occupied by the wolf of the same player.
# Sheep can not step on squares occupied by the opposite sheep.
if figure == CELL_SHEEP_1:
if field[x_new][y_new] == CELL_SHEEP_2 or \
field[x_new][y_new] == CELL_WOLF_1:
return False
elif figure == CELL_SHEEP_2:
if field[x_new][y_new] == CELL_SHEEP_1 or \
field[x_new][y_new] == CELL_WOLF_2:
return False
return True
def run_from_wolf(self, player_number, field):
if player_number == 1:
sheep_position = self.get_player_position(CELL_SHEEP_1, field)
wolf_position = self.get_player_position(CELL_WOLF_2, field)
sheep = CELL_SHEEP_1
else:
sheep_position = self.get_player_position(CELL_SHEEP_2, field)
wolf_position = self.get_player_position(CELL_WOLF_1, field)
sheep = CELL_SHEEP_2
distance_x = sheep_position[1] - wolf_position[1]
abs_distance_x = abs(sheep_position[1] - wolf_position[1])
distance_y = sheep_position[0] - wolf_position[0]
abs_distance_y = abs(sheep_position[0] - wolf_position[0])
# print('player_number %i' %player_number)
# print('running from wolf')
# if the wolf is close vertically
if abs_distance_y == 1 and distance_x == 0:
# print('wolf is close vertically')
# if it's above the sheep, move down if possible
if distance_y > 0:
if self.valid_move(sheep, sheep_position[0] + 1, sheep_position[1], field):
return MOVE_DOWN
else: # it's below the sheep, move up if possible
if self.valid_move(sheep, sheep_position[0] - 1, sheep_position[1], field):
return MOVE_UP
# if this is not possible, flee to the right or left
if self.valid_move(sheep, sheep_position[0], sheep_position[1] + 1, field):
return MOVE_RIGHT
elif self.valid_move(sheep, sheep_position[0], sheep_position[1] - 1, field):
return MOVE_LEFT
else: # nowhere to go
return MOVE_NONE
# else if the wolf is close horizontally
elif abs_distance_x == 1 and distance_y == 0:
# print('wolf is close horizontally')
# if it's to the left, move to the right if possible
if distance_x > 0:
if self.valid_move(sheep, sheep_position[0], sheep_position[1] - 1, field):
return MOVE_RIGHT
else: # it's to the right, move left if possible
if self.valid_move(sheep, sheep_position[0], sheep_position[1] + 1, field):
return MOVE_RIGHT
# if this is not possible, flee up or down
if self.valid_move(sheep, sheep_position[0] - 1, sheep_position[1], field):
return MOVE_UP
elif self.valid_move(sheep, sheep_position[0] + 1, sheep_position[1], field):
return MOVE_DOWN
else: # nowhere to go
return MOVE_NONE
elif abs_distance_x == 1 and abs_distance_y == 1:
# print('wolf is in my surroundings')
# wolf is left and up
if distance_x > 0 and distance_y > 0:
# move right or down
if self.valid_move(sheep, sheep_position[0], sheep_position[1] + 1, field):
return MOVE_RIGHT
else:
return MOVE_DOWN
# wolf is left and down
if distance_x > 0 and distance_y < 0:
# move right or up
if self.valid_move(sheep, sheep_position[0], sheep_position[1] + 1, field):
return MOVE_RIGHT
else:
return MOVE_UP
# wolf is right and up
if distance_x < 0 and distance_y > 0:
# move left or down
if self.valid_move(sheep, sheep_position[0], sheep_position[1] - 1, field):
return MOVE_LEFT
else:
return MOVE_DOWN
# wolf is right and down
if distance_x < 0 and distance_y < 0:
# move left and up
if self.valid_move(sheep, sheep_position[0], sheep_position[1] - 1, field):
return MOVE_LEFT
else:
return MOVE_UP
else: # this method was wrongly called
return MOVE_NONE
def move_sheep(self, player_number, field, sheep_model):
enemyPercentage = 0.9
if player_number == 1:
opponent_number = 2
else:
opponent_number = 1
if player_number == 1:
mySheep = CELL_SHEEP_1
opponentSheep = CELL_SHEEP_2
myWolf = CELL_WOLF_1
opponentWolf = CELL_WOLF_2
else:
mySheep = CELL_SHEEP_2
opponentSheep = CELL_SHEEP_1
myWolf = CELL_WOLF_2
opponentWolf = CELL_WOLF_1
sheep_position = self.get_player_position(mySheep, field)
wolf_position = self.get_player_position(myWolf, field)
i_am_sheep = 1
# MOVE NONE
highest_score = self.super_score(field, field, player_number, 1) - 0.1
highest_score -= self.super_score(field, field, opponent_number, 0) * enemyPercentage
direction = MOVE_NONE
# MOVE DOWN FIELD
if self.valid_move(mySheep, sheep_position[0] + 1, sheep_position[1], field):
sheep_position_new = [sheep_position[0] + 1, sheep_position[1]]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = mySheep
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_down = self.super_score(field, new_field, player_number, 1)
score_down -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_down > highest_score:
highest_score = score_down
direction = MOVE_DOWN
# MOVE UP FIELD
if self.valid_move(mySheep, sheep_position[0] - 1, sheep_position[1], field):
sheep_position_new = [sheep_position[0] - 1, sheep_position[1]]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = mySheep
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_up = self.super_score(field, new_field, player_number, 1)
score_up -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_up > highest_score:
highest_score = score_up
direction = MOVE_UP
# MOVE LEFT FIELD
if self.valid_move(mySheep, sheep_position[0], sheep_position[1] - 1, field):
sheep_position_new = [sheep_position[0], sheep_position[1] - 1]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = mySheep
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_left = self.super_score(field, new_field, player_number, 1)
score_left -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_left > highest_score:
highest_score = score_left
direction = MOVE_LEFT
# MOVE RIGHT FIELD
if self.valid_move(mySheep, sheep_position[0], sheep_position[1] + 1, field):
sheep_position_new = [sheep_position[0], sheep_position[1] + 1]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = mySheep
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_right = self.super_score(field, new_field, player_number, 1)
score_right -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_right > highest_score:
highest_score = score_right
direction = MOVE_RIGHT
return direction
# my evaluation function
def super_score(self, field, new_field, player_number, i_am_sheep):
overall_score = 0.0
if player_number == 1:
mySheep = CELL_SHEEP_1
mySheep_dead = CELL_SHEEP_1_d
opponentSheep = CELL_SHEEP_2
opponentSheep_dead = CELL_SHEEP_2_d
myWolf = CELL_WOLF_1
opponentWolf = CELL_WOLF_2
else:
mySheep = CELL_SHEEP_2
mySheep_dead = CELL_SHEEP_2_d
opponentSheep = CELL_SHEEP_1
opponentSheep_dead = CELL_SHEEP_1_d
myWolf = CELL_WOLF_2
opponentWolf = CELL_WOLF_1
if i_am_sheep == 1:
try:
my_sheep_position = self.get_player_position(mySheep, new_field)
except:
my_sheep_position = self.get_player_position(mySheep_dead, new_field)
my_wolf_position = self.get_player_position(myWolf, new_field)
try:
opponent_sheep_position = self.get_player_position(opponentSheep, field)
except:
opponent_sheep_position = self.get_player_position(opponentSheep_dead, field)
opponent_wolf_position = self.get_player_position(opponentWolf, field)
else:
try:
my_sheep_position = self.get_player_position(mySheep, field)
except:
my_sheep_position = self.get_player_position(mySheep_dead, field)
my_wolf_position = self.get_player_position(myWolf, field)
try:
opponent_sheep_position = self.get_player_position(opponentSheep, new_field)
except:
opponent_sheep_position = self.get_player_position(opponentSheep_dead, new_field)
opponent_wolf_position = self.get_player_position(opponentWolf, new_field)
if my_sheep_position == opponent_wolf_position:
return -300.0
if my_wolf_position == opponent_sheep_position:
return 300.0
if self.valid_move(mySheep, my_sheep_position[0], my_sheep_position[1] - 1, new_field):
if (my_sheep_position[0], my_sheep_position[1] - 1) == opponent_wolf_position:
overall_score -= 30
if self.valid_move(mySheep, my_sheep_position[0], my_sheep_position[1] + 1, new_field):
if (my_sheep_position[0], my_sheep_position[1] + 1) == opponent_wolf_position:
overall_score -= 30
if self.valid_move(mySheep, my_sheep_position[0] - 1, my_sheep_position[1], new_field):
if (my_sheep_position[0] - 1, my_sheep_position[1]) == opponent_wolf_position:
overall_score -= 30
if self.valid_move(mySheep, my_sheep_position[0] + 1, my_sheep_position[1], new_field):
if (my_sheep_position[0] + 1, my_sheep_position[1]) == opponent_wolf_position:
overall_score -= 30
# if i_am_sheep and field[my_sheep_position[0]][my_sheep_position[1]] == CELL_RHUBARB:
if field[my_sheep_position[0]][my_sheep_position[1]] == CELL_RHUBARB:
overall_score += 15.0
elif field[my_sheep_position[0]][my_sheep_position[1]] == CELL_GRASS:
overall_score += 4.0
my_sheep_obstacles = []
my_sheep_coords = []
my_sheep_coords_ohnegras = []
my_sheep_coords_nofood = []
my_sheep_obstacles_nofood = []
my_wolf_obstacles = []
my_wolf_coords = []
# make list of possible goals
y_position = 0
for line in new_field:
x_position = 0
for item in line:
# my wolfe's obstacles and coords
if item in {CELL_FENCE, mySheep, opponentWolf}:
my_wolf_obstacles.append((y_position, x_position))
if item == opponentSheep:
my_wolf_coords.append((y_position, x_position))
# my sheep's obstacles and coords With food
# my sheep's obstacles
if item in {CELL_FENCE, myWolf, opponentSheep, opponentWolf}:
my_sheep_obstacles.append((y_position, x_position))
# my sheep's coords
if item == CELL_RHUBARB or item == CELL_GRASS:
my_sheep_coords.append((y_position, x_position))
my_sheep_coords_ohnegras.append((y_position, x_position))
# my sheep's obstacles and coords IF NO FOOD AVAILABLE
# my sheep's obstacles
if item in {CELL_FENCE, myWolf}:
my_sheep_obstacles_nofood.append((y_position, x_position))
if item == opponentWolf or item == opponentSheep:
my_sheep_coords_nofood.append((y_position, x_position))
x_position += 1
y_position += 1
sheep_paths = bfs(my_sheep_obstacles, my_sheep_position, my_sheep_coords)
sheep_paths_nofood = bfs(my_sheep_obstacles_nofood, my_sheep_position, my_sheep_coords_nofood)
wolf_paths = bfs(my_wolf_obstacles, my_wolf_position, my_wolf_coords)
value = 0.0
# S H E E P !!!
if my_sheep_coords_ohnegras:
for current_pair in sheep_paths.items():
if new_field[current_pair[0][0]][current_pair[0][1]] == CELL_GRASS:
value = 1.0
elif new_field[current_pair[0][0]][current_pair[0][1]] == CELL_RHUBARB:
value = 5.0
elif new_field[current_pair[0][0]][current_pair[0][1]] == opponentWolf:
value = -50
else:
value = 0.0001
path_length = len(current_pair[1])
score = value / path_length
overall_score += score
else:
for current_pair in sheep_paths_nofood.items():
if new_field[current_pair[0][0]][current_pair[0][1]] == CELL_GRASS:
value = 1.0
elif new_field[current_pair[0][0]][current_pair[0][1]] == CELL_RHUBARB:
value = 5.0
elif new_field[current_pair[0][0]][current_pair[0][1]] == opponentWolf:
value = -20
elif new_field[current_pair[0][0]][current_pair[0][1]] == opponentSheep:
value = 10
else:
value = 0.0001
path_length = len(current_pair[1])
score = value / path_length
overall_score += score
middle_x = 0
middle_y = 0
middle_y = abs(15-my_sheep_position[0])
middle_x = abs(19-my_sheep_position[1])
overall_score = overall_score / ((middle_y)*1.5 + (middle_x)*1.9 + 1)
# W O L F !!!
if i_am_sheep == 1:
for current_pair in wolf_paths.items():
if new_field[current_pair[0][0]][current_pair[0][1]] == opponentSheep:
value = 100.0
else:
value = 0.001
path_length = len(current_pair[1])
score = value / path_length
overall_score += score
if i_am_sheep == 0 and not my_sheep_coords_ohnegras:
for current_pair in wolf_paths.items():
if new_field[current_pair[0][0]][current_pair[0][1]] == opponentSheep:
value = 50.0
else:
value = 0.001
path_length = len(current_pair[1])
score = value / path_length
overall_score += score
return overall_score
# defs for wolf
def move_wolf(self, player_number, field, wolf_model):
if player_number == 1:
opponent_number = 2
else:
opponent_number = 1
if player_number == 1:
mySheep = CELL_SHEEP_1
opponentSheep = CELL_SHEEP_2
myWolf = CELL_WOLF_1
opponentWolf = CELL_WOLF_2
else:
mySheep = CELL_SHEEP_2
opponentSheep = CELL_SHEEP_1
myWolf = CELL_WOLF_2
opponentWolf = CELL_WOLF_1
#sheep position is ACTUALLY THE W O L F POSITION !!!!
sheep_position = self.get_player_position(myWolf, field)
enemyPercentage = 0.9
i_am_sheep = 0
# MOVE NONE
highest_score = self.super_score(field, field, player_number, 1) - 0.2
highest_score -= self.super_score(field, field, opponent_number, 0) * enemyPercentage
direction = MOVE_NONE
# MOVE DOWN FIELD
if self.valid_move(myWolf, sheep_position[0] + 1, sheep_position[1], field):
sheep_position_new = [sheep_position[0] + 1, sheep_position[1]]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = myWolf
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_down = self.super_score(field, new_field, player_number, 1)
score_down -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_down > highest_score:
highest_score = score_down
direction = MOVE_DOWN
# MOVE UP FIELD
if self.valid_move(myWolf, sheep_position[0] - 1, sheep_position[1], field):
sheep_position_new = [sheep_position[0] - 1, sheep_position[1]]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = myWolf
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_up = self.super_score(field, new_field, player_number, 1)
score_up -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_up > highest_score:
highest_score = score_up
direction = MOVE_UP
# MOVE LEFT FIELD
if self.valid_move(myWolf, sheep_position[0], sheep_position[1] - 1, field):
sheep_position_new = [sheep_position[0], sheep_position[1] - 1]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = myWolf
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_left = self.super_score(field, new_field, player_number, 1)
score_left -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_left > highest_score:
highest_score = score_left
direction = MOVE_LEFT
# MOVE RIGHT FIELD
if self.valid_move(myWolf, sheep_position[0], sheep_position[1] + 1, field):
sheep_position_new = [sheep_position[0], sheep_position[1] + 1]
sheep_position_old = [sheep_position[0], sheep_position[1]]
new_field = copy.deepcopy(field)
new_field[sheep_position_new[0]][sheep_position_new[1]] = myWolf
new_field[sheep_position_old[0]][sheep_position_old[1]] = "."
score_right = self.super_score(field, new_field, player_number, 1)
score_right -= self.super_score(field, new_field, opponent_number, 0) * enemyPercentage
if score_right > highest_score:
highest_score = score_right
direction = MOVE_RIGHT
return direction
|
# Iterating multiple lists at the same time:
# Zip method will work based on the size of the lists and it considers the list which has smaller size.
# For example, list2 has smaller size and hence zip method will consider list2 size.
# So zip iterates till '4534' in list2 and same length will be considered for list1 .So zip iterates till '2' in list1.
list1 = [1, 42213, 2, 42223, 6, 1, 1]
list2 = [43, 564, 4534]
for l1,l2 in zip(list1,list2):
if l1 > l2:
print(l1)
else:
print(l2)
|
list1 = [] # Empty list
print(list1)
list1 = ["BMW", "AUDI", "FERRARI"]
print(list1)
# by Index
print(list1[0])
print(list1[1])
print(list1[2])
# replacing the values in the list
list1[1] = "HONDA"
print(list1[1])
print(list1)
# type casting range to list.
print(list(range(0,10))); |
# length of list
list1 = ["BMW", "AUDI", "FERRARI"]
print(len(list1))
# adding data to list
list1.append("HONDA")
list1.append("BUGAATI")
list1.insert(2, "LAMBI")
print(list1)
# finding the index of a element List
x = list1.index("LAMBI")
print(x)
# removing the elements from the list
list1.pop() # By default it removes the last element
print(list1)
list1.remove("BMW") # it removes the specific element/s
print(list1)
# Slicing of lists
slicing = list1[0:2]
print(slicing)
slicing = list1[0:3]
print(slicing)
slicing = list1[0:4:1]
print(slicing)
slicing = list1[::-1] # Reversing the list
print(slicing)
# sorting
print("Sorting:")
print(list1)
list1.sort()
print(list1)
# find out number of '2' in the list
list2 = [1, 3, 2, 4, 6, 2, 4, 3, 5, 6, 7, 9, 2, 43, 5, 11, 34, 2]
print(list2.count(2)) # Answer should be 4 as it has 4 times '2' has occured in list2
|
# in Python, there are only two types of Inheritance. Multiple Inheritance and Multilevel Inheritance.
class SuperClass(object):
def __init__(self):
print("From superclass constructor")
def start(self):
print("invoke Driving")
def drive(self):
print("Start Driving from super class")
def stop(self):
print("invoke Stop")
class subclass(SuperClass):
def __init__(self):
print("from subclass constructor")
SuperClass.__init__(self)
obj = subclass()
obj.drive()
obj.start()
obj.stop() |
from game.guess import Guess
from game.hint import Hint
from game.number import Number
from game.player import Player
from game.turn import Turn
import random
class Director:
"""A code template for a person who directs the game. The responsibility of
this class of objects is to keep track of the score and control the
sequence of play.
Attributes:
keep_playing (boolean): Whether or not the player wants to keep playing.
score (number): The total number of points earned.
thrower (Thrower): An instance of the class of objects known as Thrower.
"""
def __init__(self):
"""The class constructor.
Args:
self (Director): an instance of Director.
"""
self.number = Number()
self.guess = Guess()
self.turn = Turn()
self.player = Player('')
self.name_list = []
self.guess_list = ['-', '-', '-', '-']
self.hint = Hint()
self.symbols = []
self.keep_playing = True
self.keep_names = []
self.player_guesses = []
self.get_playerGuess = ''
def start_game(self):
"""Starts the game loop to control the sequence of play.
Args:
self (Director): an instance of Director.
"""
self.player.get_name(self.name_list)
while self.keep_playing:
self.get_inputs()
self.do_outputs()
self.do_updates(self.player_guesses)
def get_inputs(self):
"""Gets the inputs at the beginning of each round of play. In this case,
that means throwing the dice.
Args:
self (Director): An instance of Director.
"""
self.guess.get_playerGuess(self.guess_list)
def do_updates(self, player_guesses):
"""Updates the important game information for each round of play. In
this case, that means updating the score.
Args:
self (Director): An instance of Director.
"""
self.hint.check_hint(self.guess_list)
def do_outputs(self):
"""Outputs the important game information for each round of play. In
this case, that means the dice that were rolled and the score.
Args:
self (Director): An instance of Director.
"""
self.guess_list = self.player_guesses
print(f'Player {self.name_list[0]}: {self.guess_list}, {self.hint.symbols}')
print(f'Player {self.name_list[1]}: {self.guess_list}, {self.hint.symbols}') |
letter = 'ThiS is String with Upper and lower case Letters'
split_letter = list(letter.lower())
letters = {}
for chu in split_letter:
letters[chu] = 0
for i in range(len(split_letter)):
letters[split_letter[i]]+=1
for key in sorted(letters):
print(key,letters[key])
|
numbers=[1,6,8,1,2,1,5,6]
print('numbers =',numbers)
find=int(input('nhap 1 so muon tim: '))
print(find,'appears',numbers.count(find),'times in my list')
|
weight=int(input('nhap so can nang cua ban(kg): '))
he=int(input('nhap chieu cao (cm): '))
hei=he/100
bmi=weight/(hei**2)
print('chi so BMI cua ban la: ',bmi)
if bmi<16:
print('Severely underweight')
elif bmi<18.5:
print('underweight')
elif bmi<25:
print('normal')
elif bmi<30:
print('overweight')
else:
print('obese')
|
numbers=[1,6,8,1,2,1,5,6]
print('numbers =',numbers)
find=int(input('nhap 1 so muon tim: '))
count=0
for i in range(len(numbers)):
if numbers[i]==find:
count+=1
print(find,'appears',count,'times in my list')
|
import sys
import csv
info = sys.stdin.readlines()
info1 = csv.DictReader(info)
for row in info1:
column=row.get('YEAR')
if column =="2016":
print 1, "|",row['YEAR'],"|",row['Naics'],"|" ,row['Cip_name'],"|",row['Cip_code'],"|",row['Num_ppl'],"|",row['Avg_wage']
|
from os import stat
import plotly.figure_factory as ff
import statistics
import pandas as pd
import random
import csv
import plotly.graph_objects as go
df=pd.read_csv("Temp.csv")
data=df["temp"].tolist()
def random_set_of_mean(counter):
dataset=[]
for i in range(0,counter):
random_index=random.randint(0,len(data)-1)
value=data[random_index]
dataset.append(value)
mean=statistics.mean(dataset)
return mean
def show_fig(meanList):
df=meanList
fig=ff.create_distplot([df],["temp"],show_hist=False)
fig.show()
def setup():
meanList=[]
for i in range (0,1000):
set_of_means=random_set_of_mean(100)
meanList.append(set_of_means)
show_fig(meanList)
setup()
def standardDeviation():
meanList=[]
for i in range (0,1000):
set_of_means=random_set_of_mean(100)
meanList.append(set_of_means)
STDeviation=statistics.stdev(meanList)
print(STDeviation)
standardDeviation()
|
# Identify gender from first names
# Adapted from https://www.nltk.org/book/ch06.html
game_of_thrones = {
'male': [
'Eddard', 'Robb',' Jon', 'Bran', 'Jaime', 'Joffrey',
'Tyrion', 'Theon', 'Varys', 'Viserys'
],
'female': [
'Catelyn', 'Sansa', 'Arya', 'Cersei', 'Daenerys', 'Melisandre',
'Margaery', 'Brienne', 'Gilly', 'Missandei'
]
}
japanese = {
'male': [
'Haruto', 'Yuto', 'Sota', 'Yuki', 'Hayato', 'Haruki',
'Ryusei', 'Koki', 'Sora', 'Sosuke'
],
'female': [
'Himari', 'Hina', 'Yua', 'Sakura', 'Ichika', 'Akari',
'Sara', 'Saeko', 'Aiko', 'Atsuko'
]
}
import random
import nltk
from nltk.corpus import names
def gender_features(name):
name = name.lower()
features = {
'first_letter': name[0],
'last_letter': name[-1],
'length': len(name),
'first_two_letters': name[:2],
'last_two_letters': name[-2:]
}
for letter in 'abcdefghijklmnopqrstuvwxyz':
features['has_({})'.format(letter)] = letter in name
return features
def report(clf, train_set, val_set):
print('Train Set Accuracy:', nltk.classify.accuracy(clf, train_set))
print('Validation Set Accuracy:', nltk.classify.accuracy(clf, val_set))
print(clf.show_most_informative_features(3))
for index, names in enumerate([game_of_thrones, japanese], start=1):
true_males = 0
for name in names['male']:
if clf.classify(gender_features(name)) == 'male':
true_males += 1
true_females = 0
for name in names['female']:
if clf.classify(gender_features(name)) == 'female':
true_females += 1
print('Gender classification of Set {}:'.format(index))
print('Males: {} out of 10 were correctly classified'.format(true_males))
print('Females: {} out of 10 were correctly classified'.format(true_females))
def inspect_errors(val_names):
errors = []
for (name, tag) in val_names:
guess = clf.classify(gender_features(name))
if guess != tag:
errors.append( (tag, guess, name) )
return errors
male_names = [(name, 'male') for name in names.words('male.txt')]
female_names = [(name, 'female') for name in names.words('female.txt')]
labeled_names = male_names + female_names
random.shuffle(labeled_names)
train_names, val_names, test_names = labeled_names[500:], labeled_names[500:1500], labeled_names[:500]
train_set = [(gender_features(n), gender) for (n, gender) in train_names]
val_set = [(gender_features(n), gender) for (n, gender) in val_names]
test_set = [(gender_features(n), gender) for (n, gender) in test_names]
# 1. Naive Bayes + last letter
# Test Set Accuracy: 0.79
# Gender classification of Game of Thrones characters:
# Males: 8 out of 10 were correctly classified
# Females: 8 out of 10 were correctly classified
# 2. Naive Bayes + last letter + length and extra features
# Gender classification of Game of Thrones characters:
# Males: 9 out of 10 were correctly classified
# Females: 9 out of 10 were correctly classified
# 3. Naive Bayes#2 + prefixes/suffixes
clf = nltk.NaiveBayesClassifier.train(train_set)
report(clf, train_set, val_set)
""" Results
Train Set Accuracy: 0.817
Validation Set Accuracy: 0.816
Most Informative Features
last_two_letters = 'na' female : male = 101.5 : 1.0
last_two_letters = 'la' female : male = 77.0 : 1.0
last_two_letters = 'ia' female : male = 39.2 : 1.0
Gender classification of Set 1:
Males: 7 out of 10 were correctly classified
Females: 10 out of 10 were correctly classified
Gender classification of Set 2:
Males: 5 out of 10 were correctly classified
Females: 8 out of 10 were correctly classified
Observations: The classifier did well with names of female characters of Game of Thrones but did poorly with male Japanese names.
"""
|
import pygame
import time
'''
LANDSCAPES = {".":(True, "graphics/tiles/grass.png"), \
",":(True, "graphics/tiles/grass.png"), \
"G":(True, "graphics/tiles/grass.png"), \
"M":(False, "graphics/tiles/mountain.png"), \
"W":(False, "graphics/tiles/water.png")}
'''
class Tile:
'''
Represents a single tile or square in the game map.
Params:
x: x-coordinate of tile
y: y-coordinate of tile
landscape: type of terrain
Attributes:
unit: unit currently in tile if any
visited: used in pathfinding algorithm to check if tile has been visited in search
previous: used in pathfinding algorithm to store previous tile in found path
pathable: can a unit walk through the tile
img: image of landscape shown on playing field
Methods:
addUnit(): add unit to tile and make it unpathable
click(): checks if tile has been clicked by player
'''
def __init__(self, x, y, landscape, mapsyntax):
self.x = x
self.y = y
LANDSCAPES = {}
try:
for line in mapsyntax:
if line[1][1] != "True" and line[1][1] != "False":
raise IndexError
pathable = True if line[1][1] == "True" else False
LANDSCAPES[line[0]] = (pathable, line[1][0])
except IndexError:
print("Illegal map syntax!")
with open("log.txt", "w") as out:
out.write("Illegal map syntax!")
quit()
self.startpos = None
if landscape == ".":
self.startpos = 1
elif landscape == ",":
self.startpos = 2
self.unit = None
self.visited = False
self.previous = None
try:
self.pathable = LANDSCAPES[landscape][0]
self.img = pygame.image.load( LANDSCAPES[landscape][1] ).convert()
except KeyError:
print("Map keys not found!")
with open("log.txt", "w") as out:
out.write("Map keys not found!")
quit()
except pygame.error:
print("Invalid tile image!")
with open("log.txt", "w") as out:
out.write("Invalid tile image!")
quit()
def addUnit(self, unit):
self.pathable = False
self.unit = unit
def click(self, screen, currentx, currenty, size):
mousePos = pygame.mouse.get_pos()
clicked = pygame.mouse.get_pressed()
if (self.x-currentx)*size+size > mousePos[0] >= (self.x-currentx)*size and (self.y-currenty)*size+size > mousePos[1] >= (self.y-currenty)*size:
pygame.draw.rect(screen, (0,0,0), ((self.x-currentx)*size,(self.y-currenty)*size,size,size), 2)
if clicked[0] == 1:
time.sleep(0.1)
pygame.event.poll()
clicked = pygame.mouse.get_pressed()
if clicked[0] == 0:
return 1, self
elif clicked[2] == 1:
time.sleep(0.1)
pygame.event.poll()
clicked = pygame.mouse.get_pressed()
if clicked[2] == 0:
return 2, self
return 0, None
|
import animal as animal
from animal import *
# ----------------------------------------------
class Beast(Animal):
def __init__(self):
super().__init__()
self.type = 1
def read_str_array(self, strArray, i):
# должно быт как минимум три непрочитанных значения в массиве
if i >= len(strArray) - 2:
return 0
self.name = strArray[i]
self.weight = int(strArray[i + 1])
self.type = int(strArray[i + 2])
i += 3
return i
def print(self):
animal_type = ""
if self.type == 1:
animal_type = "Carnivore"
elif self.type == 2:
animal_type = "Herbivore"
elif self.type == 3:
animal_type = "Omnivore"
print("Beast: name = ", self.name, " weight = ", self.weight, "type = ", animal_type,
", special_number = ", self.special_number())
def write(self, ostream):
animal_type = ""
if self.type == 1:
animal_type = "Carnivore"
elif self.type == 2:
animal_type = "Herbivore"
elif self.type == 3:
animal_type = "Omnivore"
ostream.write("Beast: name = {} weigh = {} type = {}, special_number = {}"
.format(self.name, self.weight, animal_type, self.special_number()))
|
def findMax(a,b,c):
if a>b:
bigt=a
else:
big=b
if c>big:
big=c
return big
a = int(input("첫번째숫자입력:"))
b = int(input("두번째숫자입력:"))
c = int(input("세번째숫자입력:"))
biggest = findMax(a,b,c)
print(a,b,c,"중가장큰수는",biggest,"입니다.")
|
print("Celsius\t | Fahrenheit")
for celsius in range(0, 101, 10):
fahrenheit = (celsius * 9/5) + 32
print(celsius,'\t','|' ,fahrenheit)
|
nombre = input('mi nombre es:')
print('que tal buenos dias', nombre ) |
import random
import copy
class NQueen(object):
#generates the board randomly for random restarts
def GenerateRamdomBoard(self, a, n):
i = 0
while( i < n):
a[i] =random.randint(0,n-1) + 0
i += 1
def FillBoard(self, store, n):
i = 0
while i < n:
store.append(i)
i += 1
return
# This method calculates all the diagonal conflicts for a particular position of the queen
def DiagonalConflict(self, a, n):
conflicts = 0
d = 0
i = 0
while i < n:
j = 0
while j < n:
if i != j:
d = abs(i - j)
if (a[i] == a[j] + d) or (a[i] == a[j] - d):
conflicts += 1
j += 1
i += 1
return conflicts
# This method calculates all the row conflicts for a queen placed in a particular cell.
def RowConflict(self, a, n):
conflicts = 0
i = 0
while i < n:
j = 0
while j < n:
if i != j:
if a[i] == a[j]:
conflicts += 1
j += 1
i += 1
return conflicts
# This method returns total number of conflicts for a particular queen position
def ConflictSum(self, a, n):
conflicts = 0
conflicts = self.RowConflict(a, n) + self.DiagonalConflict(a, n)
return conflicts
def CheckSolution(self, a, n):
if self.ConflictSum(a, n) == 0:
return True
return False
def FindMinConflict(self, b, n, iterations):
store = []
self.FillBoard(store, n)
restartsSum = 0
movesSum = 0
optimalMoves = 0
row = 0
maxSteps = iterations
# The maximum steps that can be allowed to find a solution with this algorithm
while not self.CheckSolution(b, n):
# Loops until it finds a solution,
randomSelection = random.randint(0,len(store)-1) + 0
# Randomly selects a column from the available
currentValue = b[store[randomSelection]]
# This stores the current queue position in the randomly selected column
randomValue = store[randomSelection]
currentMin = self.FindColumnCollisions(b, n, randomValue)
# Sets the minimum variable to the current queue conflicts
min_compare = currentMin
while(not store):
store.remove(randomSelection)
i = 0
while i < n:
if currentValue != i:
b[randomValue] = i
col = self.FindColumnCollisions(b, n, randomValue)
# Calculates the conflicts of the queen at particular position
if col < currentMin:
currentMin = col
row = i
i += 1
if min_compare == currentMin:
# When there is no queen with minimum conflicts than the current position
if maxSteps != 0:
# Checks if the maximum steps is reached
if len(store) >= 0:
# checks whether there are columns available in the Array List
b[randomValue] = currentValue
# restores the queen back to the previous position
maxSteps -= 1
else:
self.FillBoard(store, n)
else:
# If the max steps is reached then, the board is regenerated and initiated the max steps variable
restartsSum += 1
optimalMoves = 0
self.GenerateRamdomBoard(b, n)
self.FillBoard(store, n)
maxSteps = iterations
else:
# When we find the the position in the column with minimum conflicts
movesSum += 1
optimalMoves += 1
b[randomValue] = row
min_compare = currentMin
store.clear()
maxSteps -= 1
self.FillBoard(store, n)
print()
i = 0
while i < n:
j = 0
while j < n:
if j == b[i]:
print(" Q ", end="")
else:
print(" x ", end="")
j += 1
print()
i += 1
print("Total number of Random Restarts: ",restartsSum)
print("Total number of Moves: ", movesSum)
print("Number of Moves in the solution set: ", optimalMoves)
# Below function returns the conflicts of a queen in a particular column of the board
def FindColumnCollisions(self, b, n, index):
conflicts = 0
t = 0
i = 0
while i < n:
if i != index:
t = abs(index - i)
if b[i] == b[index]:
conflicts += 1
elif b[index] == b[i] + t or b[index] == b[i] - t:
conflicts += 1
i += 1
return conflicts
print("Please select one from the below options:")
print("1. Sideways Hill Climbing With Random Restart ")
print("2.exit ")
choice = int(input("enter your choice"))
if choice == 1:
n = int(input("Please enter the value of n(no. of queens):"))
a = [None] * n
b = [None] * n
queens = NQueen()
queens.GenerateRamdomBoard(a, n)
b = copy.deepcopy(a)
iterations = 0
print()
print(" $$$$$$$ Sideways Hill Climbing With Random Restart $$$$$$$$ ")
iterations= int(input("Please enter the number of steps for iteration:"))
queens.FindMinConflict(b, n, iterations)
if choice == 2:
exit()
|
import csv
import random
# Open the existing CSV file
with open("whatever.csv", "r") as file:
reader = csv.reader(file)
# Store the rows in a list
rows = list(reader)
# Select 500 random rows
selected_rows = random.sample(rows, 500)
# Open a new file to save the selected rows
with open("new.csv", "w", newline='') as new_file:
writer = csv.writer(new_file)
# Write the selected rows to the new file
writer.writerows(selected_rows)
|
from typing import List
from functools import reduce
import numpy as np
from fast_fourier_transform import fft, ifft
def evaluate_polynomial(polynomial: List[float], value: float) -> int:
total = 0
for power, coefficient in enumerate(polynomial):
total += coefficient * (value ** power)
return total
def format_polynomial(polynomial: List[float]) -> str:
polynomial_string = ""
for power, coefficient in enumerate(polynomial):
coefficient = int(round(coefficient, 1))
if coefficient == 1 and power != 0:
coefficient = ""
if power == 0:
polynomial_string += f"{coefficient}"
elif power == 1:
polynomial_string += f"{coefficient}x"
else:
polynomial_string += f"{coefficient}x^{power}"
if power != len(polynomial) - 1:
polynomial_string += " + "
return polynomial_string
def matrix_method(p1: List[float], p2: List[float]) -> List[float]:
"""
Take two polynomials of degree n each.
Evaluate pointwise multiplication x for values -n..n.
Generate (2n + 1)(2n + 1) Vandermonde matrix A of degree n:
- Rows involve some fixed value in -n..n exponentiated up by
increasing powers in 0..(2n + 1).
- Columns involve some fixed power in 0..(2n + 1) exponentiating
increasing bases in -n..n.
Let c by the coefficient vector of the resulting polynomial.
Then Ac = x => (A^-1)x = c, which is the desired result.
Note: in real applications, the matrix and matrix would not be
generated during runtime, instead precalculated and stored.
"""
def generate_vandermonde_matrix(degree: int) -> np.array:
matrix = [[i ** j for j in range(0, 2 * degree + 1)]
for i in range(-degree, degree + 1)]
return np.array(matrix)
pointwise_multiplication = []
degree = len(p1) - 1
for i in range(-degree, degree + 1):
pointwise_multiplication.append(
evaluate_polynomial(p1, i) * evaluate_polynomial(p2, i))
vandermonde_matrix = generate_vandermonde_matrix(degree)
print(f"Vandermonde matrix: \n{vandermonde_matrix}\n")
print(f"Polynomial values: \n{np.array(pointwise_multiplication)}\n")
return np.linalg.inv(vandermonde_matrix).dot(pointwise_multiplication)
def fft_method(p1: List[float], p2: List[float]) -> List[float]:
"""
Pad the two polynomials with 0s equal to the degree of the other polynomial.
Fast Fourier transform both polynomials.
Pointwise multiply.
Inverse Fast Fourier transform to extract coefficients from pointwise multiplication.
"""
p1_fft, p2_fft = fft(p1 + [0] * len(p2)), fft(p2 + [0] * len(p1))
pointwise_mutltiplication = []
for point1, point2 in zip(p1_fft, p2_fft):
pointwise_mutltiplication.append(point1 * point2)
return [round(z.real, 2) for z in ifft(pointwise_mutltiplication)]
if __name__ == "__main__":
test_cases = [
([1, 2, 3, 4], [1, 1, 1, 1]),
([3, 2, 1, 3], [7, 8, 9, 10])
]
for test_case in test_cases:
polynomial1, polynomial2 = test_case
print(f"\nPolynomial 1: {format_polynomial(polynomial1)}")
print(f"Polynomial 2: {format_polynomial(polynomial2)}\n")
print(f"""Resulting polynomial (matrix method): \n"""
f"""{format_polynomial(matrix_method(polynomial1, polynomial2))}""")
print(f"""Resulting polynomial (fft method): \n"""
f"""{format_polynomial(fft_method(polynomial1, polynomial2))}""") |
from typing import List
"""
The sequence of values A[1], A[2], . . . , A[n] is unimodal:
For some index p between 1 and n, the values in the array entries increase
up to position p in A and then decrease the remainder of the way until position n.
Find the index of the peak entry in O(log(n)) time.
"""
def peak_finder(array: List[int]):
def _binary_search(array: List[int], low: int, high: int) -> int:
if low >= high:
return None
else:
mid = (low + high) // 2
if array[mid - 1] < array[mid] > array[mid + 1]:
return mid
elif array[mid - 1] < array[mid] < array[mid + 1]:
return _binary_search(array, mid + 1, high)
else:
return _binary_search(array, low, mid)
return _binary_search(array, 0, len(array) - 1)
if __name__ == "__main__":
test_cases = [
([1, 2, 3, 2, 1], 2),
([1], None),
([1, 2], None),
([1, 2, 1], 1),
([1, 2, 3, 4, 5, 6, 7, 8], None),
([1, 2, 3, 4, 5, 6, 7, 8, 7], 7),
([1, 2, 0, 0, 0, 0, 0, 0], 1),
([], None)
]
for test_case in test_cases:
array, peak = test_case
assert peak_finder(array) == peak |
# -*- coding: utf-8 -*-
import os
from time import sleep
from traceback import print_exc
from distributors.RandomDistributor import RandomDistributor
from strategies.RandomStrategy import RandomStrategy
from constants import STATE, FIELD, MOVE, BOARD_SIZE, DEFAULT_SHIPS
from Board import Board
#TODO: board size, ship count
class Game:
"""TODO: description"""
def __init__(self, distributor=RandomDistributor, strategy=RandomStrategy,
width=BOARD_SIZE, height=BOARD_SIZE, start_ships=DEFAULT_SHIPS):
self.board = Board(width, height, start_ships)
self.state = STATE.STARTING
self.width = width
self.height = height
self.dist = distributor()
self.player = strategy()
self.moves = []
# number of invalid moves
self.strikes = 0
self.destroyed = 0
self.on_turn = False
def prepare(self):
self.state = STATE.STARTING
self.board.reset()
del self.moves[:]
self.dist.set_ships(self.board)
self.player.set_callbacks(self.evaluate, self.get_field_info, self.get_board_info)
self.player.init()
self.destroyed = 0
def play(self, animate=False, step=False):
# not all available ships were placed onto board
if self.board.free_ships:
self.state = STATE.INVALID
return
if animate:
os.system("clear")
self.state = STATE.PLAYING
while True:
self.on_turn = True
if animate:
print "\033[0;0H" # clean board and 5 additional lines
n = self.__str__().count("\n")
for line in range(n + 7):
print " " * 80
# jump back to cursor under board
print "\033[%d;0H" % (n + 2)
try:
self.player.get_move()
except:
self.state = STATE.INVALID
print_exc()
return
if animate:
# set cursor to line 0
print "\033[0;0H"
print self
if step:
raw_input()
else:
sleep(0.25)
if self.destroyed == len(self.board.start_ships):
self.state = STATE.WON
return
def turn_count(self):
return len(self.moves)
def illegal_move(self):
if self.strikes > 5:
self.state = STATE.INVALID
raise Exception("Player disqualified")
self.strikes += 1
return MOVE.ILLEGAL, FIELD.UNKNOWN
def evaluate(self, x, y):
""" return Move, Field """
if not self.on_turn:
return self.illegal_move()
try:
field = self.board.get_field(x, y)
if (x, y) in self.moves:
return MOVE.OLD, field
self.moves.append((x, y))
self.on_turn = False
if field == FIELD.EMPTY:
self.board.set_field(x, y, FIELD.MISS)
return MOVE.OK, FIELD.MISS
elif field == FIELD.SHIP:
self.board.set_field(x, y, FIELD.HIT)
if self.board.is_destroyed(x, y):
self.destroyed += 1
return MOVE.OK, FIELD.DESTROYED
else:
return MOVE.OK, FIELD.HIT
else: # should not happen
return MOVE.OLD, field
except:
print_exc()
return self.illegal_move()
def get_field_info(self, x, y):
""" can be used by strategy to get info for a field, hides information for undetected fields"""
field = self.board.get_field(x, y)
if field in (FIELD.HIT, FIELD.DESTROYED, FIELD.MISS):
return field
else:
return FIELD.UNKNOWN
def get_board_info(self):
return self.width, self.height, self.board.start_ships
def animate(self):
os.system("clear")
self.board.reset()
for move in self.moves:
self.on_turn = True
self.evaluate(*move)
# set cursor to line 0
print "\033[0;0H"
print self
sleep(0.5)
def get_name(self):
return "%s vs. %s" % (self.dist.__class__.__name__, self.player.__class__.__name__)
def get_game_info(self):
return "Board: %sx%s | Ships: %s | Sum: %s" % (
self.width, self.height, self.board.start_ships, sum(self.board.start_ships))
def __str__(self):
s = "\t%s\n\t%s" % (self.get_name(), self.get_game_info())
s += "\n" + self.board.__str__()
s += "\n\tturns: %s | state: %s" % (self.turn_count(), STATE.name(self.state))
return s
|
# -*- coding: utf-8 -*-
from random import choice
from game.constants import DIR
from AbstractDistributor import AbstractDistributor
class RandomDistributor(AbstractDistributor):
"""
This distributor simply puts boats on random positions.
Thus it delivers a basic framework for ship deployment
and a testing ground for solvers that don't use specific
knowledge about their oponents.
"""
def set_ships(self, board):
directions = [DIR.UP, DIR.DOWN, DIR.LEFT, DIR.RIGHT]
positions = [(x, y) for x in xrange(board.width) for y in xrange(board.height)]
#don't try more often then each direction from each position
max_tries = range(4 * board.width * board.height)
for s in board.start_ships:
for i in max_tries:
x, y = choice(positions)
dire = choice(directions)
if board.add_ship(s, x, y, dire):
break
|
import tkinter as tk
from tkinter import messagebox, simpledialog
class UserInterface:
USER_CHOICE = """
Enter:
-'a' to add a new restaurant
-'l' to list all restaurants
-'r' tp mark a restaurant as visited
-'d' to delete a restaurant
-'q' to quit
Your choice:"""
def user_interface(self):
user_input = simpledialog.askstring('Welcome', 'Good Day old sport! \n' + {UserInterface.USER_CHOICE})
while user_input != 'q':
if user_input == 'a':
UserInterface.prompt_add_restaurant()
elif user_input == 'l':
UserInterface.list_restaurants()
elif user_input == 'r':
UserInterface.prompt_visited()
elif user_input == 'd':
UserInterface.prompt_delete()
else:
messagebox.showinfo('Error', "Command Error: Try Again \n " + {UserInterface.USER_CHOICE})
def prompt_add_restaurant(self):
name = simpledialog.askstring('Add', 'Enter the name of a new restaurant: ')
address = simpledialog.askstring('Add', f'Enter the address {name}: ')
restaurants.add_restaurant(name, address)
def list_restaurants(self):
global restaurants
restaurants = restaurants.get_all_restaurants()
for restaurant in restaurants:
return restaurant
def prompt_visited(self):
name = simpledialog.askstring('Visited', 'Enter a restaurant you have been to: ')
restaurants.mark_if_visited(name)
def prompt_delete(self):
name = simpledialog.askstring('Delete', 'Enter a restaurant you want to delete: ')
address = restaurants.get_one_restaurants(name)
if name is True:
restaurants.delete_restaurant(name, address)
else:
print("Generic Error Message about Errors!!!")
for restaurant in restaurants:
return restaurant
root = tk.Tk()
root.mainloop()
'''
Long term would be to change these commands into switch cases and getters to refactor for UserInterface
ie. def add(): return restaurant.add_restaurant
def requested_user_action(): switch = { 1: add, 2:....} func = switch.get(arg, " something ") return func
which would later lower the lines writen out. Possible to abstract out in the long run?
'''
|
#var = 1
# for infinite loop constructs
#while var == 1:
#num = input("enter your number: ")
#print("you entered the number is: ", num)
#print("good bye")
#Else statement in whileloop
count = 0
while count < int(input("enter the number")):
print(count, " is less then 5")
count += 1
else:
print(count, " is not less then 5") |
#!/usr/bin/python
def count_words(text, words):
count = 0
for word in words:
if word in text:
count+=1
print "word ", word
print "count is ", count
return count
assert count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3, "Example"
assert count_words("Bananas, give me bananas!!!", {"banana", "bananas"}) == 2, "BANANAS!"
assert count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.",
{"sum", "hamlet", "infinity", "anything"}) == 1, "Weird text"
|
#!/usr/bin/python
def checkio(str_number, radix):
answer = 0
powers_list = [radix**y for y in range(0,10)]
for i in range(0,len(str_number)):
if str_number[len(str_number)-i-1].isalpha():
if (ord(str_number[len(str_number)-i-1]) - 55) >= powers_list[1] : return -1
sum =((ord(str_number[len(str_number)-i-1]) - 55) * powers_list[i])
else:
if int(str_number[len(str_number)-i-1]) >= powers_list[1]: return -1
sum = int(str_number[len(str_number)-i-1]) * powers_list[i]
answer += sum
if answer == 0: return -1
return answer
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("AF", 16) == 175, "Hex"
assert checkio("101", 2) == 5, "Bin"
assert checkio("101", 5) == 26, "5 base"
assert checkio("Z", 36) == 35, "Z base"
assert checkio("AB", 10) == -1, "B > A > 10"
assert checkio("909", 9) == -1, "last one"
|
list1 = ['a','e','i','o','u','A','E','O','U','I']
def Translat_Word(word):
s = ''
i = 0
for i in word:
if i not in list1 and i.isalpha():
s = s + i +"o"+ i
else:
s = s + i
print s
if __name__ == "__main__":
word = raw_input("\nEnter word\n")
Translat_Word(word)
|
#Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.)
def FindLength(list1):
c=0
for i in list1:
c+=1
return c
if __name__ == "__main__":
list1 = raw_input("Enter String")
l=FindLength(list1)
print "Length of given string",l
|
def reverseFun(a,l,h):
while(l < h):
a[l],a[h] = a[h],a[l]
l+=1
h-=1
def rightRotation(arr,n,k):
print(arr)
reverseFun(arr,0,n-1)
reverseFun(arr,0,k-1)
reverseFun(arr,k,n-1)
print(arr)
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arrlen = len(arr)
k=3
rightRotation(arr,arrlen,k) |
def minReplacement(s1):
if len(s1)>26:
print("IMPOSSIBLE")
else:
char_freq = [0]*26
for i in range(len(s1)):
char_freq[int(chr(s1[i])-chr(a))]
count = 0
for i in range(len(s1)):
if char_freq[int(chr(s1[i])-chr(a))] > 1:
for i in range(len(s1))
if __name__ == "__main__":
string = "xxxxyyyy"
minReplacement(string)
|
def Reverse_Function(string):
#first logic
list2 = []
s = ''
for i in range(len(string)-1,-1,-1):
val = string[i]
list2.append(val)
list2 = ''.join(list2)
print list2
#2 logic
str = ''
for s in string:
str = s + str
print str
#3 logic
if (len(string)) == 0:
return s
else:
return string[1:]+string[0]
if __name__ == "__main__":
string = "arati"
s = ''
print Reverse_Function(string)
|
def countFreq(str1):
dict ={}
for i in str1:
key = dict.keys()
if i in key :
dict[i]+=1
else:
dict[i] = 1
print(dict)
str1 = "arati"
countFreq(str1) |
def Find_Max_Number(list1):
Store_Max = 0
for Ele in list1:
if Store_Max < Ele:
Store_Max = Ele
return Store_Max
if __name__ == "__main__":
list1 = []
L = int(raw_input("Enter Length"))
print "Enter ele"
for i in range(L):
ele = raw_input()
list1.append(ele)
M = Find_Max_Number(list1)
print "Largest Element From Given List",M
|
from tests.unit.unit_base_test import UnitBaseTest
from models.item import ItemModel
class ItemTest(UnitBaseTest):
def test_create_item(self):
item = ItemModel('test', 11.11, 1)
self.assertEqual(item.name, 'test',
"The name of the item after creation does not equal the constructor argument.")
self.assertEqual(item.price, 11.11,
"The price of the item after creation does not equal the constructor argument.")
self.assertEqual(item.store_id, 1)
self.assertIsNone(item.store)
def test_item_json(self):
item = ItemModel('test', 11.11, 1)
expected = {
'name': 'test',
'price': 11.11
}
self.assertEqual(
item.json(),
expected,
"The JSON export of the item is incorrect. Received {}, expected {}.".format(item.json(), expected))
|
from survey import AnonymousSurvey
# 定义一个问题,创建关于这个问题的调查对象
question = "你最喜欢做什么事?"
my_survey = AnonymousSurvey(question)
# 显示问题并存储答案
my_survey.show_question()
print("任何时候按下\"q\"退出程序。")
while True:
response = input("最喜欢做:")
if response == "q":
break
my_survey.store_response(response)
# 显示调查结果:
print("谢谢参与!")
my_survey.show_results()
|
#Diffie Hellman
q = 311 # q and root values are our base prime
g = 2# our base root
a = 9 # a and b values are our randomly generated key values
b = 3
def diffieHellman(q,g,a,b):
# Sender Sends Receiver A = g^a mod p
keyA = (g**a)%q # 353 to the power of random value 1 modulus prime
print("Shared sender key generated here:",keyA)
keyB = (g**b) % q # same as key a
print("Shared receiver key generated here:",keyB)
#calculated shared secret: B^a mod p
keyAshared = (keyB ** a) % q #we use reciever key with sender random val
print(" Sender created diffie hellman key:", keyAshared)
keyBshared = (keyA **b) % q # opposite of keyashared
print(" Receiver created diffie hellman key:", keyBshared)
print("")
#this shows that both values are same - which is what we want
print("This means our shared private key is:",keyBshared)
return keyBshared
#stores our diffie hellman value in a variable we can use for next step
diffieKey =diffieHellman(q,g,a,b)
|
import random
def print_board(board):
print(board[7] + '|' + board[8] + '|' + board[9])
print('-+-+-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-+-+-')
print(board[1] + '|' + board[2] + '|' + board[3])
def player_symbol():
letter = ' '
while not (letter == 'X' or letter == 'O'):
print('Do you want to play as X or O?')
letter = input().upper()
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
def turn_move(board, letter, move):
board[move] = letter
def is_winner(board, letter):
if board[7] == letter and board[8] == letter and board[9] == letter:
return True
if board[4] == letter and board[5] == letter and board[6] == letter:
return True
if board[1] == letter and board[2] == letter and board[3] == letter:
return True
if board[1] == letter and board[4] == letter and board[7] == letter:
return True
if board[2] == letter and board[5] == letter and board[8] == letter:
return True
if board[3] == letter and board[6] == letter and board[9] == letter:
return True
if board[1] == letter and board[5] == letter and board[9] == letter:
return True
if board[7] == letter and board[5] == letter and board[3] == letter:
return True
def free_space(board, move):
if board[move] == ' ':
return True
def player_move(board):
move = ' '
while move not in ['1', '2', '3', '4', '5', '6', '7', '8', '9'] or not free_space(board, int(move)):
print('Your move is... (1-9)')
move = input()
return int(move)
def random_move(board, movesList):
possibleMv = []
for i in movesList:
if free_space(board, i):
possibleMv.append(i)
if len(possibleMv) != 0:
return random.choice(possibleMv)
else:
return None
def copy_board(board):
cpyBrd = []
for i in board:
cpyBrd.append(i)
return cpyBrd
def computer_move(board, compLetter):
if compLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'
for i in range(1, 10): # If A.I can win
copy = copy_board(board)
if free_space(copy, i):
turn_move(copy, compLetter, i)
if is_winner(copy, compLetter):
return i
for i in range(1, 10): # If player can win
copy = copy_board(board)
if free_space(copy, i):
turn_move(copy, playerLetter, i)
if is_winner(copy, playerLetter):
return i
move = random_move(board, [1, 3, 7, 9])
if move is not None:
return move
elif free_space(board, 5):
return 5
else:
return random_move(board, [2, 4, 6, 8])
def full_board(board):
for i in range(1, 10):
if free_space(board, i):
return False
return True
def reset_game():
inp = input('Do you want to play again? (y or n)\n')
if inp.lower() == 'y':
return True
else:
return False
def game():
print('Welcome Human :)')
while True:
board = [' '] * 10
playerSymbol, compSymbol = player_symbol()
turn = 'Human'
gameOn = True
print(f'The {turn} will go first!')
while gameOn:
if turn == 'Human':
print_board(board)
move = player_move(board)
turn_move(board, playerSymbol, move)
if is_winner(board, playerSymbol):
print_board(board)
print('Oh, I see... You have won.. Human')
gameOn = False
else:
if full_board(board):
print_board(board)
print('Is a tie.. You are not that bad')
gameOn = False
else:
turn = 'Computer'
else:
move = computer_move(board, compSymbol)
turn_move(board, compSymbol, move)
if is_winner(board, compSymbol):
print_board(board)
print('Hahaa you lose Human... Pathetic')
gameOn = False
else:
if full_board(board):
print_board(board)
print('Is a tie.. You are not that bad')
gameOn = False
else:
turn = 'Human'
if not reset_game():
break
if __name__ == '__main__':
game()
|
def break_loop():
for i in range(1, 5):
if(i == 2):
return (i)
print(5)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.