text
stringlengths
37
1.41M
#!/usr/bin/env python3 # parsing a date (what day were you born on?) from datetime import datetime line = input("Enter your date of birth (DD/MM/YYYY): ") birthday = datetime.strptime(line, "%d/%m/%Y") print("You were born on a {0:%A}".format(birthday))
# Quick Sort is another sorting algorithm which follows divide and conquer approach. # It requires to chose a pivot, then place all elements smaller than the pivot on the left of the pivot and all elements larger on the right # Then the array is partitioned in the pivot position and the left and right arrays followthe same procedure until the base case is reached. # After each pass the pivot element occupies its correct position in the array. # Time Complexity in Best and Average cases is O(nlog N) whereas in worst case it jumps up to O(n^2). Space complexity is O(log n) # In this implementation, we will take the last element as pivot. count = 0 def partition(array, left, right): smaller_index = left - 1 pivot = array[right] for i in range(left, right): global count count += 1 if array[i] < pivot: smaller_index += 1 array[smaller_index], array[i] = array[i], array[smaller_index] array[smaller_index+1], array[right] = array[right], array[smaller_index+1] print(array) return (smaller_index+1) def quick_sort(array, left, right): if left < right: partitioning_index = partition(array, left, right) print(partitioning_index) quick_sort(array,left,partitioning_index-1) quick_sort(array,partitioning_index+1,right) array = [5,9,3,10,45,2,0] quick_sort(array, 0, (len(array)-1)) print(array) print(f'Number of comparisons = {count}') ''' [0, 9, 3, 10, 45, 2, 5] 0 [0, 3, 2, 5, 45, 9, 10] 3 [0, 2, 3, 5, 45, 9, 10] 1 [0, 2, 3, 5, 9, 10, 45] 5 [0, 2, 3, 5, 9, 10, 45] #Number of comparisons = 14 ''' sorted_array = [5,6,7,8,9] quick_sort(sorted_array, 0, len(sorted_array)-1) print(sorted_array) print(f'Number of comparisons = {count}') ''' [5, 6, 7, 8, 9] 4 [5, 6, 7, 8, 9] 3 [5, 6, 7, 8, 9] 2 [5, 6, 7, 8, 9] 1 [5, 6, 7, 8, 9] Number of comparisons = 10 ''' reverse_sorted_array = [9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10] quick_sort(reverse_sorted_array, 0, len(reverse_sorted_array) - 1) print(reverse_sorted_array) print(f'Number of comparisons = {count}') ''' [-10, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 9] 0 [-10, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 9] 19 [-10, -9, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, 8, 9] 1 [-10, -9, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, 8, 9] 18 [-10, -9, -8, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, 7, 8, 9] 2 [-10, -9, -8, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, 7, 8, 9] 17 [-10, -9, -8, -7, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, 6, 7, 8, 9] 3 [-10, -9, -8, -7, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, 6, 7, 8, 9] 16 [-10, -9, -8, -7, -6, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 5, 6, 7, 8, 9] 4 [-10, -9, -8, -7, -6, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, 5, 6, 7, 8, 9] 15 [-10, -9, -8, -7, -6, -5, 3, 2, 1, 0, -1, -2, -3, -4, 4, 5, 6, 7, 8, 9] 5 [-10, -9, -8, -7, -6, -5, 3, 2, 1, 0, -1, -2, -3, -4, 4, 5, 6, 7, 8, 9] 14 [-10, -9, -8, -7, -6, -5, -4, 2, 1, 0, -1, -2, -3, 3, 4, 5, 6, 7, 8, 9] 6 [-10, -9, -8, -7, -6, -5, -4, 2, 1, 0, -1, -2, -3, 3, 4, 5, 6, 7, 8, 9] 13 [-10, -9, -8, -7, -6, -5, -4, -3, 1, 0, -1, -2, 2, 3, 4, 5, 6, 7, 8, 9] 7 [-10, -9, -8, -7, -6, -5, -4, -3, 1, 0, -1, -2, 2, 3, 4, 5, 6, 7, 8, 9] 12 [-10, -9, -8, -7, -6, -5, -4, -3, -2, 0, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9] 8 [-10, -9, -8, -7, -6, -5, -4, -3, -2, 0, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9] 11 [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 9 [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Number of comparisons = 190 ''' #If the same algorithm is implemented with the pivot element = array[(right-left)//2], i.e., the middle element of the array, #then the number of comparisons for the reverse_sorted_array drops down to 91 #Number of comparisons for the sorted array = 6 and #Number of comparisons for the first unsorted array = 11
""" Data and data formatting """ import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('data.csv') print(data[:10]) # Function to help us plot def plot_points(data): X = np.array(data[['gre', 'gpa', 'rank']]) y = np.array(data['admit']) admitted = X[np.argwhere(y == 1)] rejected = X[np.argwhere(y == 0)] plt.scatter([s[0][0] for s in rejected], [s[0][1] for s in rejected], s=25, color='red', edgecolor='k') plt.scatter([s[0][0] for s in admitted], [s[0][1] for s in admitted], s=25, color='cyan', edgecolor='k') plt.xlabel('Test (GRE)') plt.ylabel('Grades (GPA)') # Plotting the points plot_points(data) plt.show() # Data cleanup # # You might think there will be three input units, but we actually need to transform the data first. The rank feature # is categorical, the numbers don't encode any sort of relative values. Rank 2 is not twice as much as rank 1, # rank 3 is not 1.5 more than rank 2. Instead, we need to use dummy variables to encode rank, splitting the data into # four new columns encoded with ones or zeros. Rows with rank 1 have one in the rank 1 dummy column, and zeros in all # other columns. Rows with rank 2 have one in the rank 2 dummy column, and zeros in all other columns. And so on. # # We'll also need to standardize the GRE and GPA data, which means to scale the values such that they have zero mean # and a standard deviation of 1. This is necessary because the sigmoid function squashes really small and really # large inputs. The gradient of really small and large inputs is zero, which means that the gradient descent step # will go to zero too. Since the GRE and GPA values are fairly large, we have to be really careful about how we # initialize the weights or the gradient descent steps will die off and the network won't train. Instead, # if we standardize the data, we can initialize the weights easily and everyone is happy. # Separating the ranks data_rank1 = data[data["rank"] == 1] data_rank2 = data[data["rank"] == 2] data_rank3 = data[data["rank"] == 3] data_rank4 = data[data["rank"] == 4] # Plotting the graphs plot_points(data_rank1) plt.title("Rank 1") plt.show() plot_points(data_rank2) plt.title("Rank 2") plt.show() plot_points(data_rank3) plt.title("Rank 3") plt.show() plot_points(data_rank4) plt.title("Rank 4") plt.show() # This looks more promising, as it seems that the lower the rank, the higher the acceptance rate. Let's use the rank # as one of our inputs. In order to do this, we should one-hot encode it. # Use the get_dummies function in Pandas in order to one-hot encode the data. # Make dummy variables for rank one_hot_data = pd.concat([data, pd.get_dummies(data['rank'], prefix='rank')], axis=1) # Drop the previous rank column one_hot_data = one_hot_data.drop('rank', axis=1) # Print the first 10 rows of our data print(one_hot_data[:10]) # Scaling the data # # The next step is to scale the data. We notice that the range for grades is 1.0-4.0, whereas the range for test # scores is roughly 200-800, which is much larger. This means our data is skewed, and that makes it hard for a neural # network to handle. Let's fit our two features into a range of 0-1, by dividing the grades by 4.0, and the test # score by 800. # Making a copy of our data processed_data = one_hot_data[:] # Scale the columns / Standarize features # processed_data['gre'] = processed_data['gre'] / 800 # processed_data['gpa'] = processed_data['gpa'] / 4 for field in ['gre', 'gpa']: mean, std = processed_data[field].mean(), processed_data[field].std() processed_data.loc[:, field] = (processed_data[field] - mean) / std # Printing the first 10 rows of our processed data print(processed_data[:10]) """ Creating training and testing data sets """ # Split off random 10% of the data for testing np.random.seed(21) sample = np.random.choice(processed_data.index, size=int(len(processed_data)*0.9), replace=False) train_data, test_data = processed_data.iloc[sample], processed_data.drop(sample) print("Number of training samples is", len(train_data)) print("Number of testing samples is", len(test_data)) print(train_data[:10]) print(test_data[:10]) # Split into features and targets features = train_data.drop('admit', axis=1) targets = train_data['admit'] features_test = test_data.drop('admit', axis=1) targets_test = test_data['admit'] print(targets[:10]) print(features[:10])
import re for line in range(int(input())): string = '' string = re.sub(r'(?<= )&&(?= )','and',input()) string = re.sub(r'(?<= )\|\|(?= )','or',string) print (string)
class Bike(object): def __init__(self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print self.price print self.max_speed print self.miles return self def ride(self): self.miles += 10 print "Riding" return self def reverse(self): if self.miles >= 5: self.miles -= 5 print "Reversing" return self new_bike1 = Bike("$250","25 mph") new_bike2 = Bike("$300","30 mph") new_bike3 = Bike("$350","35 mph") new_bike1.ride() new_bike1.ride() new_bike1.ride() new_bike1.reverse() new_bike1.displayInfo() new_bike2.ride() new_bike2.ride() new_bike2.reverse() new_bike2.reverse() new_bike2.displayInfo() new_bike3.reverse() new_bike3.reverse() new_bike3.reverse() new_bike3.displayInfo()
def coinTosses(): countH = 0 countT = 0 for i in range (1,5001,1): import random hot = random.randrange(1,101) if hot % 2 == 0: countH += 1 print ("Attempt # " + str(i) + " Throwing a coin... It's a head! ... Got " + str(countH) + " head(s) so far and " + str(countT) + " tails(s) so far") if hot % 2 == 1: countT += 1 print ("Attempt #" + str(i) + " Throwing a coin... It's a tail! ... Got " + str(countH) + " head(s) so far and " + str(countT) + " tails(s) so far") coinTosses()
#!/usr/bin/env python3 import sys vowelCount = { "e": 0, "a": 0, "i": 0, "o": 0, "u": 0, } text = sys.stdin.read() i = 0 while i < len(text): if text[i].lower() in vowelCount: vowelCount[text[i].lower()] += 1 i += 1 tups = [] for a, b in vowelCount.items(): tup = a, b tups.append(tup) tups.sort(key=lambda x: x[1], reverse=True) blen = len(str(tups[0][1])) for a, b in tups: print("{} : {:>{:d}d}".format(a, b, blen))
#!/usr/bin/env python3 from re import findall date = r'\b\d+[/-]\d+[/-]\d+\b' phone = r'\b\d{2}[-\s]\d{7}\b' email = r'\b(?:\w+\.)*\w+\@\w+\.\w+(?:\.\w+)*\b' ldate = r'\b\d{2}[\s/-]\w{3}[\s/-]\d{2}\b' if __name__ == "__main__": with open("test.txt") as f: s = f.read() print(findall(date, s)) print(findall(phone, s)) print(findall(email, s)) print(findall(ldate, s))
#!/usr/bin/env python3 def minimum(l): if len(l) == 0: raise ValueError('Cannot find the minimum of an empty list.') elif len(l) == 1: return l[0] else: minNumber = minimum(l[1:]) mymin = l[0] if minNumber < mymin: mymin = minNumber return mymin
def collatz_seq(n): global step step+=1 if n==1 or n==2: return str(1) elif n%2: return str(3*n+1)+','+collatz_seq(3*n+1) else: return str(n//2)+','+collatz_seq(n/2) n=raw_input('Enter number: ') step=0 print collatz_seq(int(n)) print 'Number of step: ',step
import sys def table(n): for i in range(1,13): print('{0:2} X {1:2} = {2:^}'.format(n,i,i*int(n))) def main(): for x in range(1,len(sys.argv)): print('Table of {}'.format(sys.argv[x])) print('{}'.format('-'*12)) table(sys.argv[x]) print('{}'.format('='*12)) if __name__=='__main__': main()
import random from random import randint def generate_file(N=50, M=30, file_name='data/list_to_open.txt'): random.seed(2390) file = open(file_name, 'w') n = N * randint(1, 20) file.write("N = " + str(N) + "\n") file.write("M = " + str(M) + "\n") for i in range(n): file.write(str(randint(1, N)) + ",") file.write(str(randint(1, N))) if __name__ == '__main__': print("Введите N и M") #N = int(input()) #M = int(input()) generate_file()
import gym import pygame import numpy as np from math import sqrt ENV_WIDTH = 750 ENV_HEIGHT = 750 class Agent: def __init__(self, name, board): """ This is the agent of the digitized environment. The agent is supposed to try riding around the environment and minimize the amount of collisions while riding. First however, the agent has to train in the environment, and learn to minimize the collisions and go from point A to point B smoothly. Args: name (str): This is the name for the agent and can be anything as long as it's a string. This is just for convenience when visualizing the progress of the agent after training. """ self.board = board self.width = 50 self.height = 25 self.rewards = [] self.reward_sum = sum(self.rewards) self.collisions = [] # Data to see correlation between directions and distance measures self.direction_history = [] self.distances = [] self.agent_position = {'x': 10, 'y': 600} self.corners = [[self.agent_position['x'] + self.width, self.agent_position['y'], '1s'], [ self.agent_position['x'] + self.width, self.agent_position['y'] + self.height, '11']] self.line_pos = [self.show_distances(p) for p in self.corners] self.angle = 90 def show_distances(self, pos): sums = [] for obstacle in Obstacle.instances: # print(obstacle.name, [obstacle.x, obstacle.y]) new_pos = pos[:] while 0 < new_pos[0] < ENV_WIDTH and 0 < new_pos[1] < ENV_HEIGHT and not (new_pos[0] in range(int(obstacle.x), int(obstacle.x + obstacle.width)) and new_pos[1] in range(int(obstacle.y), int(obstacle.y + obstacle.height))): operation = new_pos[2] for i, j in enumerate(operation): if j == '1': new_pos[i] += 1 elif j == 's': new_pos[i] -= 1 sums.append(new_pos) s = self.return_distances(self.corners, sums) return sums[s.index(min(s))] def check_collision(self): distances = self.return_distances(self.corners, self.line_pos) left = distances[0] right = distances[1] collisionDetected = False for obstacle in Obstacle.instances: if (self.agent_position['x'] in range(int(obstacle.x), int(obstacle.x + obstacle.width)) and self.agent_position['y'] in range(int(obstacle.y), int(obstacle.y + obstacle.height))) or self.agent_position['x'] < 0 or self.agent_position['y'] < 0 or self.agent_position['x'] > 750 or self.agent_position['y'] > 750: print("** COLLISION DETECTED **") self.collisions.append({ 'didCollide': True, 'distanceFromObject': left if left < 2 and right > 2 else right if right < 2 and left > 2 else min(left, right), 'nameOfCollision': obstacle.name, 'width': obstacle.width, 'height': obstacle.height }) collisionDetected = True return collisionDetected def return_distances(self, corners, end_line_pos): return sqrt(abs(end_line_pos[0][0] - corners[0][0])**2 + abs(end_line_pos[0][1] - corners[0][1])), sqrt(abs(end_line_pos[1][0] - corners[1][0])**2 + abs(end_line_pos[1][1] - corners[1][1])**2) class Obstacle: instances = [] def __init__(self, x, y, width, height, color, name): """ This is the obstacle class. This class is here so that it's easier to create obstacles of the environment and position them given the size and position attributes as opposed to just hard-coding and drawing them in pygame. In the future, I plan to allow the user to make a couple modifications by a simple sequence of clicks. Args: width (int): Specifies the width of the object height (int): Specifies the height of the object color (tuple): Color in RGB tuple format name (str): Name of the obstacle - may make this optional but this is convenient for data visualization after training """ self.__class__.instances.append(self) self.x = x self.y = y self.width = width self.height = height self.color = color self.name = name class Iota(gym.Env): metadata = {'render.modes': ['console']} def __init__(self, model): """ This is the environment. This environment is a custom Gym environment. A standard gym environment has threee methods: render, reset, and step. The render method is to update the environment with new positions of objects. Step is to update the agent's position given the action it predicted. Finally, reset is a method that is called when the agent reaches the terminal state. In other words, it resets the agent's position to it's default position and then restarts the training process. The only terminal state of the agent is when the agent collides with another object or at the environment's endpoints. """ self.action_space = gym.spaces.Discrete(4) self.observation_space = gym.spaces.Box( low=0, high=750, shape=(2,), dtype=np.float32) pygame.init() pygame.display.set_caption("Iota Environment") self.board = pygame.display.set_mode((ENV_WIDTH, ENV_HEIGHT)) self.bed = Obstacle(0, ENV_HEIGHT / 2 - 250 / 2, 400, 250, (255, 255, 255), "Bed") self.table = Obstacle(0, 0, 450, 200, (255, 255, 255), "Table") self.agent = Agent("Iota", self.board) hasFinished = False obs = self.reset() while not hasFinished: for event in pygame.event.get(): if event.type == pygame.QUIT: hasFinished = True action, states = model.predict(obs) print(action) obs, rewards, dones, info = self.step(action) print(obs, self.agent.angle) self.render() def render(self, mode='human', close=False): self.board.fill((0, 0, 0)) pygame.draw.rect(self.board, self.bed.color, [ self.bed.x, self.bed.y, self.bed.width, self.bed.height]) pygame.draw.rect(self.board, self.table.color, [ self.table.x, self.table.y, self.table.width, self.table.height]) pygame.draw.rect(self.board, (255, 255, 255), [ self.agent.agent_position["x"], self.agent.agent_position["y"], self.agent.width, self.agent.height]) for i, pos in enumerate(self.agent.line_pos): pygame.draw.line(self.board, (255, 255, 255), (self.agent.corners[i][0], self.agent.corners[i][1]), (pos[0], pos[1])) pygame.display.update() def reset(self): self.agent.agent_position['x'] = 10 self.agent.agent_position['y'] = ENV_HEIGHT / 3 + self.bed.height + 100 self.corners = [[self.agent.agent_position['x'] + self.agent.width, self.agent.agent_position['y'], '1s'], [ self.agent.agent_position['x'] + self.agent.width, self.agent.agent_position['y'] + self.agent.height, '11']] self.line_pos = [self.agent.show_distances(p) for p in self.corners] dist1, dist2 = self.agent.return_distances(self.corners, self.line_pos) self.render() return np.array([dist1, dist2]) def step(self, action): # print(action) """ array[4] = [0, 0, 0, 0] array[0] = forward array[1] = left array[2] = reverse array[3] = right """ distances = self.agent.return_distances(self.agent.corners, self.agent.line_pos) left = distances[0] right = distances[1] self.agent.distances.append({ 'left': left, 'right': right }) reward = 0 if action == 1: self.agent.angle -= 90 if self.agent.angle < 0: self.agent.angle = 0 self.agent.direction_history.append('left') self.reset_raycasts(self.agent.angle) self.render() if left > right: reward += 5 else: reward -= 5 elif action == 2: self.agent.angle += 90 if self.agent.angle >= 360: self.agent.angle = 0 self.reset_raycasts(self.agent.angle) self.render() self.agent.direction_history.append('right') if left < right: reward += 5 else: reward -= 5 elif action == 0: self.agent.direction_history.append('forward') if self.agent.angle >= 360: self.agent.angle == 0 if self.agent.angle == 0 or self.agent.angle == 360: self.agent.agent_position['y'] -= 10 self.reset_raycasts(self.agent.angle) elif self.agent.angle == 90: self.agent.agent_position['x'] += 10 self.reset_raycasts(self.agent.angle) elif self.agent.angle == 180: self.agent.agent_position['y'] += 10 self.reset_raycasts(self.agent.angle) elif self.agent.angle == 270: self.agent.agent_position['x'] -= 10 self.reset_raycasts(self.agent.angle) if left + right >= 50: reward += 5 self.render() elif action == 3: self.agent.direction_history.append('reverse') if self.agent.angle == 0: self.agent.agent_position['y'] += 10 self.reset_raycasts(self.agent.angle) self.render() elif self.agent.angle == 90: self.agent.agent_position['x'] -= 10 self.reset_raycasts(self.agent.angle) self.render() elif self.agent.angle == 180: self.agent.agent_position['y'] -= 10 self.reset_raycasts(self.agent.angle) self.render() elif self.agent.angle == 270: self.agent.agent_position['x'] += 10 self.reset_raycasts(self.agent.angle) self.render() if left + right <= 50: reward += 5 else: reward -= 5 if "forward" not in self.agent.direction_history[len(self.agent.direction_history)-6:len(self.agent.direction_history)-1]: reward -= 10 info = {} if self.agent.check_collision(): reward -= 10 self.reset() self.agent.rewards.append({ 'leftDistance': left, 'rightDistance': right, 'reward': reward, }) self.render() print(f"REWARD: {reward}") # self.render() # print(self.agent.direction_history[-1]) self.agent.rewards.append(reward) return np.array([left, right]), reward, False, info def reset_raycasts(self, angle_of_agent): if angle_of_agent == 0 or angle_of_agent == 360: if self.agent.width > self.agent.height: self.agent.width, self.agent.height = self.agent.height, self.agent.width self.agent.corners = [[self.agent.agent_position['x'], self.agent.agent_position['y'], 'ss'], [ self.agent.agent_position['x'] + self.agent.width, self.agent.agent_position['y'], '1s']] self.agent.line_pos = [self.agent.show_distances(p) for p in self.agent.corners] self.render() elif angle_of_agent == 90: if self.agent.width < self.agent.height: self.agent.width, self.agent.height = self.agent.height, self.agent.width self.agent.corners = [[self.agent.agent_position['x'] + self.agent.width, self.agent.agent_position['y'], '1s'], [ self.agent.agent_position['x'] + self.agent.width, self.agent.agent_position['y'] + self.agent.height, '11']] self.agent.line_pos = [self.agent.show_distances(p) for p in self.agent.corners] self.render() elif angle_of_agent == 180: if self.agent.width > self.agent.height: self.agent.width, self.agent.height = self.agent.height, self.agent.width self.agent.corners = [[self.agent.agent_position['x'], self.agent.agent_position['y'] + self.agent.height, 's1'], [ self.agent.agent_position['x'] + self.agent.width, self.agent.agent_position['y'] + self.agent.height, '11']] self.agent.line_pos = [self.agent.show_distances(p) for p in self.agent.corners] self.render() elif angle_of_agent == 270: if self.agent.width < self.agent.height: self.agent.width, self.agent.height = self.agent.height, self.agent.width self.agent.corners = [[self.agent.agent_position['x'], self.agent.agent_position['y'], 'ss'], [ self.agent.agent_position['x'], self.agent.agent_position['y'] + self.agent.height, 's1']] self.agent.line_pos = [self.agent.show_distances( p) for p in self.agent.corners] self.render()
def twostring(a,b): firstlet=a[0]+b[0] middlelet=a[int(len(a) / 2):int(len(a) / 2) + 1] + b[int(len(b) / 2):int(len(b) / 2) + 1] lastlet=a[-1]+b[-1] final=firstlet+middlelet+lastlet print(final) twostring("america","japan")
def greatestnum(a,b,c): if a>b and a>c: greatest=a elif a<b and b>c: greatest=b else: greatest=c print(f"greatest number of {a},{b} and {c} is {greatest}") greatestnum(1000,9888,870)
l1=["harry","soham","sachin","rahul"] # i=0 # while i<len(l1): # print("Happy birthday") # i=i+1 for name in l1: if name[0]=="s" or name[0]=="S": print("Happy birthday") else :print(l1)
dict1={ "Hello":"harsh", "fruit":"mango", 23:"harsh", "list":[12,45,67,54], "tuple":(45,67,34,56), "dictionary":{ "hello":1, "hi":2, } } print(dict1) print(dict1["fruit"]) print(type(dict1)) print(dict1["dictionary"]["hello"])
set3={2,4,5,(2,3,4),'hi',True} print(set) print(type(set)) set1={} print(set1) print(type(set1)) set2=set() print(set2) print(type(set2))
def diagonaldiff(a,b): d1=0 d2=0 for i in range(0,b) : for j in range(0,b): if i == j : d1 +=a[i][j] if i==b-j-1: d2+=a[i][j] print(d1-d2) a=3 b=[[11, 2, 4], [4 , 5, 6], [10, 8, -12]] diagonaldiff(a,b)
Dict1={ "Key 1":"value 1", "key 2":"value 2", 2:[3,4,6,8], "tuple":(23,56,46,88), } print(list(Dict1.keys())) print(list(Dict1.values())) print(list(Dict1.items())) Dict1.__setitem__("key3","value4") print(Dict1) # Dict2={ # "Key 1":"value1", # "key5":"value7", # "kay6":"value8" # } # Dict1.update(Dict2) # print(Dict1) # print(Dict1.get("Key 1")) # print(Dict1["key 1"])
a="once upon a time there was a man who used do farming in his land" print(len(a)) print(a.capitalize()) print(a.find("time")) print(a.startswith("once")) print(a.endswith("land")) print(a.replace("man","woman")) print(a.count("once"))
import math # This method is Iterative way to find a element is Sorted array # Algo : Binary Search # prerequisite Array must be sorted. def bin_search(arr,l,r,x): while(l <= r): mid = int(math.floor(l + (r - l)/2)); if (arr[mid] == x): return mid elif (arr[mid] > x): r = mid-1 else: l = mid+1 return -1 arr = [2, 3, 4, 10, 40, 50, 53, 56, 69, 70] x = 10 ########### Function call ############ # # @param arr : array with integers elements # @param x : Element to find in array result = bin_search(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index %d" %result) else: print ("Element is not present in array")
import random import time combinations = [ [1,2,3],[4,5,6],[7,8,9], [1,4,7],[2,5,8],[3,6,9], [1,5,9],[3,5,7] ] positions = [i for i in range(1,10)] positions_occupied =[] def gameBoard(): print( f""" {positions[0]} | {positions[1]} | {positions[2]} ---------------- {positions[3]} | {positions[4]} | {positions[5]} ---------------- {positions[6]} | {positions[7]} | {positions[8]} """ ) def userMove(choice): pos = int(input("Enter Your Position")) positions[pos-1]=choice gameBoard() positions_occupied.append(pos) msg = checkWinner(pos,choice) return msg def cpu_move(cpu_ch): cpu_pos = random.randint(1,9) print(f"cpu positions : {cpu_pos}") if cpu_pos in positions_occupied: cpu_move(cpu_ch)#recursive function else: positions[cpu_pos-1]=cpu_ch gameBoard() positions_occupied.append(cpu_pos) msg = checkWinner(cpu_pos,cpu_ch) return msg def checkWinner(pos,choice): for i in range(len(combinations)): if pos in combinations[i]: index = combinations[i].index(pos) combinations[i][index]=choice for i in range(len(combinations)): if combinations[i][0] == choice and combinations[i][1] == choice and combinations[i][2] == choice: return "winner" gameBoard() ch = input("Enter your Choice : X | 0 ->") if ch=='X': cpu_ch=0 else: cpu_ch='X' Game=True while Game: ''' print("combinations:",combinations) print("occupied :",positions_occupied) print("positions :",positions) ''' msg=userMove(ch) if msg=="winner": print("User Wins") break print("CPU TURN.....") time.sleep(5) msg = cpu_move(cpu_ch) print(msg) if msg=="winner": print("CPU Wins") break
from collections import defaultdict salaries_and_tenures = [ (83000, 8.7), (88000, 8.1), (48000, 0.7), (76000, 6), (69000, 6.5), (76000, 7.5), (60000, 2.5), (83000, 10), (48000, 1.9), (63000, 4.2), ] salary_by_tenure = defaultdict(list) for salary, tenure in salaries_and_tenures: salary_by_tenure[tenure].append(salary) average_salary_by_tenure = { tenure: sum(salaries) / len(salaries) for tenure, salaries in salary_by_tenure.items() } print(average_salary_by_tenure) def tenure_bucket(tenure): if tenure < 2: return 'less than two' elif tenure < 5: return 'between two and five' else: return 'more than five' salaries_by_tenure_bucket = defaultdict(list) for salary, tenure in salaries_and_tenures: bucket = tenure_bucket(tenure) salaries_by_tenure_bucket[bucket].append(salary) average_salary_by_bucket = { tenure_bucket: sum(salaries) / len(salaries) for tenure_bucket, salaries in salaries_by_tenure_bucket.items() } print(average_salary_by_bucket)
"""ユークリッドの互除法""" def swap(a, b): return b, a def gcd(a, b): X = max(a, b) Y = min(a, b) step = 0 while(Y != 0): X %= Y X, Y = swap(X, Y) step += 1 return X, step def main(): while(True): X, Y = map(int, input().split()) if X == 0 and Y == 0: break else: maximum_divisor, step = gcd(X, Y) print(maximum_divisor, step) if __name__ == '__main__': main()
import numpy as np #Generally we want to iterate through our data in a random order def in_random_order(theta): """Generates elements of data in random order""" indexes = [i for i,_ in enumerate(data)] # creates a list of indices random.shuffle(indexes) # shuffles them for i in indexes: yield data[i] # return data in that order def minimize_stochastic(target_fn, gradient_fn, x, y, theta_0, alpha_0=0.01): data = zip(x,y) theta = theta_0 alpha = alpha_0 min_theta, min_value = None, float('inf') iterations_with_no_improvements = 0 # if we ever get to 100 iterations with no improvements - stop while iterations_with_no_improvements < 100: value = sum(target_fn(x_i, y_i, theta) for x_i, y_i in data) if value < min_value: # if we've found a new minimum, remember it and go back to original step size min_theta, min_value = theta, value iterations_with_no_improvements = 0 alpha=alpha_0 else: # otherwise we aren't improving -> shrink step size iterations_with_no_improvements += 1 alpha*0.9 # and take a step for each data point for x_i, y_i in_random_order(data): gradient_i = gradient_fn(x_i, y_i, theta) theta = vector_subtract(theta, np.multiply(alpha, gradient_i)) return min_theta # If we want to maximize a function instead, we can instead minimize its negative (negative gradient): def negate(f): """return a function that for any input x returns -f(x)""" return lambda *args, **kwargs: -f(*args, **kwargs) def negate_all(f): """the same when f returns a list of numbers""" return lambda *args, **kwargs: [-y for y in f(*args,**kwargs)] def maximize_stochastic(target_fn, gradient_fn, x, y, theta_0, alpha_0=0.01): return minimize_stochastic(negate(target_fn), negate_all(gradient_fn) x, y, theta_0, alpha_0)
# Basic decision tree function import math import random from collections import defaultdict from functools import partial # Entropy is a notion of "how much information" # It is used to represent the uncertainty of data def entropy(class_probabilities): """given a list of class probabilities, compute the entropy""" return sum(-p*math.log(p,2) for p in class_probabilities if p) # ignore 0 probabilities # determine probabilities of each lebel def class_probabilities(labels): total_count=len(labels) return [count/total_count for count in Counter(labels).values()] def data_entropy(labeled_data): labels=[label for _, label in labeled_data] probabilities = class_probabilities(labels) return entropy(probabilities) # Determine the resulting entropy from partitions def partition_entropy(subsets): """ Find the entropy from this partition of data into subsets; subsets is a list of lists of labeled data""" total_count = sum(len(subset) for subset in subsets) return sum(data_entropy(subset)*len(subset)/total_count for subset in subsets) #using example given, start by writing a function that does the partitioning def partition_by(inputs,attribute): """each input is a pair (attribute_dict, label) Returns a dict: attribute_value -> inputs""" groups = defaultdict(list) for input in inputs: key = input[0][attribute] # get the value of the specified attribute groups[key].append(input) # then add this input to the correct list return groups def partition_entropy_by(inputs, attribute): """ computes the entropy corresponding to the given partition""" partitions = partition_by(inputs, attribute) return partition_entropy(partitions.values()) #We can classify an input: def classify(tree,input): """ classify the input using the given decision tree""" # if this is a leaf nose, return its value if tree in [True, False]: return tree # Otherwise this tree consists of an attribute to split on and a dictionary # keys are values of that attribute and whose values of are subtrees to # consider next attribute, subtree_dict = tree subtree_key = input.get(attribute) # None if input is missing attribute if subtree_key not in subtree_dict: # if no subtree for key subtree_key = None # we'll use the None subtree subtree = subtree_dict[subtree_key] # choose the appropriate subtree return classify(subtree,input) # and use it to classify the input # Build the tree representation from our training data def build_tree_id3(inputs, split_candidates=None): # if this is our first pass, all keys of the first input are split candidates if split_candidates is None: split_candidates = inputs[0][0].keys() # count Trues and Falses in the inputs num_inputs = len(inputs) num_trues = len([label for item, label in inputs if label]) num_falses = num_inputs-num_trues if num_trues == 0: return False # no Trues? return "false" leaf if num_falses == 0: return True # no Falses? return "true" leaf if not split_candidates: # if no split candidates left return num_trues >= num_falses # return the majority leaf # otherwise, split on the best attribute best_attribute = min(split_candidates, key = partial(partition_entropy_by, inputs)) partitions = partition_by(inputs, best_attribute) nnum_candidates = [a for a in split_candidates if a != best_attribute] # recursively build the subtrees subtrees = {attribute_value: built_tree_id3(subset, new_candidates) for attribute_value, subset in partitions.items()} subtrees[None] = num_trues > num_falses # default case return (best_attribute,subtrees) """ Since decision trees have a tendecncy to overfit (as they easily fit to their training data, we can use "random forests" to build multiple decision trees and let them vote on how to classify inputs""" def forest_classify(trees,input): votes = [classify(tree,input) for tree in trees] vote_counts = Counter(votes) return vote_counts.most_common(1)[0][0] """ Since the above mentioned tree building process is deterministic, we can bootstrap our data to achieve different trees""" def bootstrap_sample(data): """ Randomly samples len(data) elements w/ replacement""" return [random.choice(data) for _ in data] """ We can introduce a second source of randomness ("ensemble learning") by changing how we choose the "best-attribute" to split on. Instead of looking at all the remaining attributes, first choose a random subset of them, then split on whicever of those is the best""" # if there is already enough split candidates, look at all of them if len(split_candidates)<=self.num_split_candidates: sampled_split_candidates = split_candidates # otherwise pick a random sample else: sampled_split_candidates = random.sample(split_candidates, self.num_split_candidates) # now choose best attribute only from those candidates best_attribute = min(sampled_split_candidates, key=partial(partition_entropy_by, inputs)) partitions = partition_by(inputs, best_attribute)
#creating a dictionary d = {'day1':'Sunday', 'day2':'Monday', 'day3':'Tuesday','day4':'Wednesday', 'day5':'Thursday','day6':'Friday'} print("Printing the dictionary:",end = "\n") print(d,end = "\n") #Adding an element to the dictionary d['day7'] = 'Saturday' print("After adding an element to dictioanry:",end = "\n") print(d,end = "\n") #deleting the third element from the dictionary del d['day3'] print("after deleting the third element:",end = "\n") print(d,end = "\n") #deleting the entire dictionary del d print(d)
# コメント。 #から初めて1行が認識される。 # 変数宣言。型はない。初期化するなら任意の値も a = 'Hello world' print(a) # Hello world a = 1 print(a) # 1 # 関数宣言。 def 関数名 (引数) :で定義。 def addNumber(num1, num2) : return num1 + num2 # 呼び出しは名称と引数を合わせるだけ print(addNumber(1 ,2)) # 3 # class宣言もできる。 """ DocString。ダブルクォートで囲った範囲に適応される。 このクラスは共通処理を提供しています。 """ class BasicUtil : # コンストラクタ。インスタンス生成時に呼び出される。 def __init__(self , num) : self.num = num # デストラクタ。インスタンス破棄時に呼び出される。 def __del__(self) : self.num = 0 print('インスタンスを破棄しました。') # 引数のうち1つめはselfという名称を指定する。 def concatStr(self, target, param) : return self.num + target + param def concatNum(self, target, param) : return target + param # クラス内メソッドはインスタンス生成を行って呼び出す。 util = BasicUtil(10) print(util.concatNum(20,30)) # インスタンスの破棄 del util # クラスの継承も可能 class utilTest(BasicUtil) : def __init__(self, num) : self.num = num # スーパークラスのメソッド呼び出し。 @classmethod def concatNumTest(cls) : print(super().concatNum(15, 10, 20)) test = utilTest(15) print(test.concatNumTest())
""" Vytvoř program na prodej vstupenek do letního kina. Ceny vstupenek jsou v tabulce níže. Datum Cena 1. 7. 2021 - 10. 8. 2021 250 Kč 11. 8. 2021 - 31. 8. 2021 180 Kč Mimo tato data je středisko zavřené. Tvůj program se nejprve zeptá uživatele na datum a počet osob, pro které uživatel chce vstupenky koupit. Uživatel zadá datum ve středoevropském formátu. Převeď řetězec zadaný uživatelem na datum pomocí funkce datetime.strptime(). Pokud by uživatel zadal příjezd mimo otevírací dobu, vypiš, že letní kino je v té době uzavřené. Pokud je letní kino otevřené, spočítej a vypiš cenu za ubytování. Data lze porovnávat pomocí známých operátorů <, >, <=, >=, ==, !=. Tyto operátory můžeš použít v podmínce if. Níže vidíš příklad porovnání dvou dat. Program vypíše text "První datum je dřívější než druhé datum.". from datetime import datetime prvni_udalost = datetime(2021, 7, 1) druha_udalost = datetime(2021, 7, 3) if prvni_datum < druhe_datum: print("Druhá událost se stala po první události") """ from datetime import datetime, timedelta sezona1_start = datetime(2021, 7, 1) sezona1_end = datetime(2021, 8, 10) sezona2_start = datetime(2021, 8, 11) sezona2_end = datetime(2021, 8, 31) prijezd = datetime.strptime(input("Zadejte datum příjezdu DD.MM.YYYY: "), "%d.%m.%Y") osoby = int(input("Zadejte počet osob: ")) if prijezd > sezona1_start: if prijezd < sezona2_end: if prijezd < sezona1_end: print(f"Cena je: {osoby*250} Kč.") elif prijezd > sezona1_end: print(f"Cena je: {osoby*180} Kč.") else: print("Letní kino je v této době uzavřené.") #print(prijezd) #print(f"{sezona_start_1.day}/{sezona_start_1.month}/{sezona_start_1.year}")
def is_valid_file_name(): '''()->str or None''' file_name = None try: file_name = input("Enter the name of the file: ").strip() f = open(file_name) f.close() except FileNotFoundError: print("There is no file with that name. Try again.") file_name = None return file_name def get_file_name(): file_name = None while file_name == None: file_name = is_valid_file_name() return file_name def clean_word(word): """ (str)->str Returns a new string which is lowercase version of the given word with special characters and digits removed """ clean = '' excluding = '!.?:,"-_\()[]{}%123456789'+"'" for wrd in word: if wrd not in excluding: clean += wrd return clean.lower().strip() def test_letters(w1, w2): """ (str,str)->bool Given two strings w1 and w2 representing two words, the function returns True if w1 and w2 have exactlly the same letters, and False otherwise """ w1 = list(w1) w2 = list(w2) if sorted(w1) == sorted(w2): return True else: return False def create_clean_sorted_nodupicates_list(s): """ (str)->list of str Given a string s representing a text, the function returns the list of words with the following properties: - each word in the list is cleaned-up (no special characters nor numbers) - there are no duplicated words in the list, and - the list is sorted lexicographicaly (you can use python's .sort() list method or sorted() function.) """ new = [] s = clean_word(s).split() for word in s: if word not in new: new.append(word) new.sort() return new def word_anagrams(word, wordbook): """ (str, list of str) -> list of str - a string (representing a word) - wordbook is a list of words (with no words duplicated) This function should call test_letters function. The function returs a (lexicographicaly sorted) list of anagrams of the given word in wordbook """ anagrams = [] for i in wordbook: if test_letters(i, word): anagrams.append(i) if word in anagrams: anagrams.remove(word) return sorted(anagrams) def count_anagrams(l, wordbook): """(list of str, list of str) -> list of int - l is a list of words (with no words duplicated) - wordbook is another list of words (with no words duplicated) The function returns a list of integers where i-th integer in the list represents the number of anagrams in wordbook of the i-th word in l. Whenever a word in l is the same as a word in wordbook, that is not counted. """ counted = [] for i in l: x = len(word_anagrams(i, wordbook)) counted.append(x) return counted def k_anagram(l, anagcount, k): """(list of str, list of int, int) -> list of str - l is a list of words (with no words duplicated) - anagcount is a list of integers where i-th integer in the list represents the number of anagrams in wordbook of the i-th word in l. The function returns a (lexicographicaly sorted) list of all the words in l that have exactlly k anagrams (in wordbook as recorded in anagcount) """ kanagram = [] for i in range(0, len(anagcount)): if k == anagcount[i]: kanagram.append(l[i]) return kanagram def max_anagram(l, anagcount): """ (list of str, list of int) -> list of str - l is a list of words (with no words duplicated) - anagcount is a list of integers where i-th integer in the list represents the number of anagrams in wordbook of the i-th word in l. The function returns a (lexicographicaly sorted) list of all the words in l with maximum number of anagrams (in wordbook as recorded in anagcount) """ i = 0 big = anagcount[0] while i <= len(anagcount) - 1: if big >= anagcount[i]: i += 1 else: big = anagcount[i] i += 1 maxed = k_anagram(l, anagcount, big) return maxed def zero_anagram(l, anagcount): """ (list of str, list of int) -> list of str - l is a list of words (with no words duplicated) - anagcount is a list of integers where i-th integer in the list represents the number of anagrams in wordbook of the i-th word in l. The function returns a (lexicographicaly sorted) list of all the words in l with no anagrams (in wordbook as recorded in anagcount) """ zerod = k_anagram(l, anagcount, 0) return zerod ############################## # main ############################## wordbook = open("english_wordbook.txt").read().lower().split() list(set(wordbook)).sort() print("Would you like to:") print("1. Analize anagrams in a text -- given in a file") print("2. Get small help for Scrabble game") print("Enter any character other than 1 or 2 to exit: ") choice = input() if choice == '1': file_name = get_file_name() rawtx = open(file_name).read() l = create_clean_sorted_nodupicates_list(rawtx) anagcount = count_anagrams(l, wordbook) maxed = max_anagram(l, anagcount) print("\nOf all the words in your file, the following words have the most anagrams:") print(maxed) print("\nHere are their anagrams:") for z in range(0, len(maxed)): print("Anagrams of", maxed[z], "are: ", word_anagrams(maxed[z], wordbook)) print("\nHere are the words from your file that have no anagrams:") print(zero_anagram(l, anagcount)) print("\nSay you are interested if there is a word in your file that has exactly k anagrams.") k = int(input("Enter a positive integer: ")) print("Here is a word (words) in your file with exactly", k, "anagrams:") print(k_anagram(l, anagcount, k)) elif choice == '2': c = input("Enter the letters that you have, one after another with no space:\n").lower() flag = True while flag: if " " not in c: flag = False else: print("Error: You entered space(s).") c = input("Enter the letters that you have, one after another with no space:\n").lower() y = int(input("Would you like help forming a word with\n1. all these letters\n2. all but one of these letters?\n")) if y == 1: d = word_anagrams(c, wordbook) if len(d) == 0: print("There is no word comprised of exactly these letters.") else: if c in wordbook: d.append(c) d.sort() print("Here are all the words that are comprised of exactly these letters:\n", d) else: print("Here are all the words that are comprised of exactly these letters:\n", d) elif y == 2: print("The letters you gave us are: ", c) count = 0 while count <= len(c) - 1: new = '' for s in range(0, len(c)): if s != count: new += c[s] print("Without the letter in position", count + 1, "we have letters:", new) j = word_anagrams(new, wordbook) if new in wordbook: j.append(new) j.sort() if len(j) == 0: print("There is no word comprised of letters:", new) else: print("Here are the words that are comprised of the letters:", new, "\n", j) count += 1 else: print("Good bye")
from expel_1 import FilePathTokenizer import argparse tokens = FilePathTokenizer() parser = argparse.ArgumentParser(description='File Path Tokenizer') parser.add_argument("-f", "--filepaths", nargs='+', type=str, help="Expects any number of file paths, example command line: $ python example.py -f 'filepath1 filepath2 filepath3' ") parser.add_argument("-i", "--input", help="expects a file path to a file containing file paths") parser.add_argument("-s", "--stdin", nargs='+', type=str, help="expects file paths on stdin") args = parser.parse_args() # this function is my solution to running arguments with the backwards slash character on the command line- def argsplit(string_args): split_args = string_args[0].split() if not split_args: print("Filepaths cannot be an empty string") else: return(split_args) # Main routine if args.filepaths: print(args.filepaths) filepath_list = argsplit(args.filepaths) print(tokens.tokenize_file_paths(filepath_list)) elif args.input: print(tokens.tokenize_fd(args.input)) elif args.stdin: print(args.stdin) filepath_list = argsplit(args.stdin) print(tokens.tokenize_file_paths(filepath_list)) else: print('no args')
def raizes (a,b,c): delta = (b*b)-(4*a*c) if delta >= 0: raiz1 = (-b+(delta**0.5))/(2*a) raiz2 = (-b-(delta**0.5))/(2*a) print ('Raíz 1: ', raiz1) print ('Raíz 2: ', raiz2) retorno = 0 else: re_raiz = (-b)/(2*a) im_raiz=((-delta)**0.5)/(2*a) print('Raíz 1: ',re_raiz,' + ',im_raiz,'i') print('Raíz 2: ',re_raiz,' - ',im_raiz,'i') retorno = 1 return retorno def main(): a = int(input('Digite o valor de a: ')) b = int(input('Digite o valor de b: ')) c = int(input('Digite o valor de c: ')) retorno = raizes(a,b,c) print(retorno) main()
""" This is an example of using Bayesian A/B testing """ import pymc as pm # these two quantities are unknown to us. true_p_A = 0.05 true_p_B = 0.04 # notice the unequal sample sizes -- no problem in Bayesian analysis. N_A = 1500 N_B = 1000 # generate data observations_A = pm.rbernoulli(true_p_A, N_A) observations_B = pm.rbernoulli(true_p_B, N_B) # set up the pymc model. Again assume Uniform priors for p_A and p_B p_A = pm.Uniform("p_A", 0, 1) p_B = pm.Uniform("p_B", 0, 1) # define the deterministic delta function. This is our unknown of interest. @pm.deterministic def delta(p_A=p_A, p_B=p_B): return p_A - p_B # set of observations, in this case we have two observation datasets. obs_A = pm.Bernoulli("obs_A", p_A, value=observations_A, observed=True) obs_B = pm.Bernoulli("obs_B", p_B, value=observations_B, observed=True) # to be explained in chapter 3. mcmc = pm.MCMC([p_A, p_B, delta, obs_A, obs_B]) mcmc.sample(20000, 1000)
from abc import ABC, abstractmethod class Engine: pass class ObservableEngine(Engine): """ Heir of Engine class""" def __init__(self): self.__subscribers = set() def subscribe(self, subscriber): self.__subscribers.add(subscriber) def unsubscribe(self,subscriber): self.__subscribers.remove(subscriber) def notify(self, message): for subscriber in self.__subscribers: subscriber.update(message) class AbstractObserver(ABC): """ Class for realizing ShortNotificationPrinter class and FullNotificationPrinter class. """ @abstractmethod def update(self): pass class ShortNotificationPrinter(AbstractObserver): """ This Class can to save set names achievement which it get. """ def __init__(self): self.achievements = set() def update(self, message): self.achievements.add(message['title']) class FullNotificationPrinter(AbstractObserver): """ This Class can to save list achievement in order in which it to get them of Engin class. """ def __init__(self): self.achievements = list() def update(self, message): if message not in self.achievements: self.achievements.append(message) def main(): mess = {"title": "Покоритель", "text": "Дается при выполнении всех заданий в игре"} short_not = ShortNotificationPrinter() full_not = FullNotificationPrinter() obser = ObservableEngine() obser.subscribe(short_not) obser.subscribe(full_not) obser.notify(mess) print(short_not.achievements, full_not.achievements, sep='\n') if __name__ == '__main__': main()
#tuple is immutable data structue. They are enclosed in parantheses t1 = ('apple', 100, 120.35, 'hello') t2 = (1458, 'as', 'tuple') l1 = [100, 200, 300] t3 = () # empty tuple t4 = (50,) # even if have only one object in tuple we need to use comma # accessing tuple print t1[0] print t1[:2] print t1[2:] #tuple is immutabble so cannot update or change the values of the tuple. we can create new tuple from them # t1[0] = "100" this is not allowed for tuple #removing indivdual object is not possible with tuple so we have to delete entire tuple # len,concat (+), multiple(*), iteration, in print len(t1) #returns len of the object in tuple t3 = t1 + t2 # returns new tuple concat two tuple print t3 print t2 *3 # multiple for i in t1: print i if i in t2: print "Yes" else: print "no" # cmp, len, min, max, tuple, print cmp(t1,t2) print len(t2) print max(t1) print min(t1) print tuple(l1)
hrs = input("Enter Hours:") hrs = float(hrs) rph = input("Rates per hour: ") rph = float(rph) if (hrs <= 40): pay = hrs*rph print(pay) else: extrahour = (hrs - 40) pay = (40 * rph) + (extrahour * 1.5 * rph) print(pay)
from sys import argv script, filename = argv # opens the file that you enter txt = open(filename) # replace filename with the name you enter and print print(f"Here's your file {filename}: ") # reads the opened file and then prints the content print(txt.read()) # asks you to enter the filename again print("Type the filename again:") # the name of file you entered is saved as file_again file_again = input(">") # opens up the file you just entered and the content is saved as txt_again txt_again = open(file_again) # reads the opened file and prints print(txt_again.read())
class Solution(object): """ Encapsulates cryptic crossword solutions Attributes: score: an indication of how likely the solution is to be correct notes: newline separated notes on the derivation of the solution solution: the word believed to be a solution """ def __init__(self, soln, score, clue_type, indicator=""): """ :param solver.IndicatorType clue_type: solver that gave this clue. :param str indicator: The word that indicates the solver type if there was one. :param str soln: The word of the solution :param float score: The solution's score """ self.score = score note = 'Clue type ' + str(clue_type) if indicator: note += ' indicated by ' + indicator self.notes = [note] self.solution = soln def add_note(self, note): """ Add a note to a solution :param str note: the note to be added """ self.notes.append(note) def __str__(self): ret = self.solution ret += "\nScore: " + str(self.score) + "\n" ret += "\n".join(self.notes) return ret def __cmp__(self, other): return cmp(self.score, other.score)
def removeLeading0(string): split_string = string.split(".") string = ".".join(str(int(s)) for s in split_string) return string ip="192.128.018.011" print("IP =",ip) print("with the function:",removeLeading0(ip)) ip="127.0.0.1" print("IP =",ip) print("with the function:",removeLeading0(ip))
x=2 print('eval(\'x+2\') = ',eval('x+2')) print('eval(\'pow(x,10)\')) = ',eval('pow(x,10)'))
import re exp = input("Enter a regular expression: ") count = 0 file = open("mbox.txt") for line in file: x = re.findall(exp,line) if x != []: count+=1 print("mbox.txt had",count,"lines that matched",exp)
def strip_char(string,chs): return "".join(c for c in string if c not in chs) string = "Danny is not a dog." print("string =",string) strip_string = "aotg" print("the striped characters:",strip_string) print("with the function:",strip_char(string,strip_string))
import re def text_match(text): string = "ab+" if re.search(string,text): return "Found a match!" else: return "Not matched!" print(text_match("ab")) print(text_match("abbc")) print(text_match("ac"))
n = int(raw_input()) on = [] for i in range(n): name, check = raw_input().split(" ") if check == 'enter': on.append(name) else: on.remove(name) on.sort(reverse=True) for nm in on: print nm
import numpy as np import math class Windowing: """ The window function splits a possibly infinitely long sample stream in chunks of data. The length of a chunk is windowSize. """ def __init__(self, windowSize=4096, stepSize = 2048, windowFunc = np.hamming): """ Create a new instance with the given windowSize and stepSize. @param windowSize: specifies the size of the window to generate @param stepSize: specifies the step size of this windowing function. Each iteration the window is moved by stepSize steps. The stepSize could be used let the windows overlap. @param windowFunc: The windowing function to generate this window. It accepts the size of the window as first parameter. """ self.windowSize = windowSize self.stepSize = stepSize self.windowFunc = windowFunc(self.windowSize) def apply(self,y_in): """ Apply the windowing function to the array y_in. @return: A new array with the content of the window in the x direction and all windows in the y direction. @example: Assume an y_in of [1111222233334444] and a window size of 4 and a step size of 4 Then the output will be [1111, 2222, 3333, 4444] """ numberOfSteps = int(math.floor((len(y_in) - self.windowSize)/self.stepSize)) #print "Number of steps: %f" % numberOfSteps out = np.ndarray((numberOfSteps,self.windowSize),dtype = y_in.dtype) for i in xrange(numberOfSteps): offset = i * self.stepSize out[i] = y_in[offset : offset + self.windowSize] #* self.windowFunc return out
#3) Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário. Calcule o total em segundos. print("Programa para calcular segundos") dias = int(input("Digite a quantidade de dias: ")) horas = int(input("Digite a quantidade de horas: ")) minutos = int(input("Digite a quantidade de minutos: ")) segundos = int(input("Digite a quantidade de segundos: ")) #variavel criada para tranformar os dias em horas aux_hora = dias * 24 #variavel criada para tranformar as horas em minutos aux_minutos = (aux_hora + horas) * 60 #variavel criada para tranformar os minutos em segundos aux_segundos = (aux_minutos * 60) + segundos print("Somando {} dias, {}horas, {} minutos, {} segundos. Da o total de {} segundos".format(dias,horas,minutos,segundos,aux_segundos))
'''3. João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você faça um programa que leia a variável peso (peso de peixes) e verifique se há excesso. Se houver, gravar na variável excesso e na variável multa o valor da multa que João deverá pagar. Caso contrário mostrar tais variáveis com o conteúdo ZERO.''' print("Programa Papo-de-Pescador") peso = float(input("Peso de Peixe: ")) if peso > 50: excesso = peso - 50 multa = excesso * 4 print("Peso do Peixe: {}KG" .format(peso)) print("Quanto excedeu: {}KG" .format(excesso)) print("Multa a pagar: R${}" .format(multa))
#4. Faça um Programa que leia três números e mostre o maior deles. print("Digite 3 número e mostraremos o maior deles") num1 = float(input("Digite o 1º Numero: ")) num2 = float(input("Digite o 2º Numero: ")) num3 = float(input("Digite o 3º Numero: ")) if num1 > num2 and num1 > num3: maior = num1 elif num2 > num3: maior = num2 else: maior = num3 print("O maior Número digitado foi {}" .format(maior))
'''Seja o mesmo texto acima “splitado”. Calcule quantas palavras possuem uma das letras “python” e que tenham mais de 4 caracteres. Não se esqueça de transformar maiúsculas para minúsculas e de remover antes os caracteres especiais.''' def tem_python(palavra): for letra in palavra: if letra in 'python': return True return False print('programa split') frase = """The Python Software Foundation and the global Python community welcome and encourage participation by everyone. Our community is based on mutual respect, tolerance, and encouragement, and we are working to help each other live up to these principles. We want our community to be more diverse: whoever you are, and whatever your background, we welcome you.""" newFrase = frase.lower() newFrase = frase.replace('.', '') newFrase = frase.replace(',', '') newFrase = frase.replace(':', '') newFrase = frase.split() palavras = 0 for palavra in newFrase: if len(palavra) > 4 and tem_python(palavra) == True: palavras += 1 print(f'Palavras: {palavras}')
""" Given a string, find the length of the longest substring without repeating characters. """ def lengthOfLongestSubstring(s): if s is "": return 0 longest_substring = 1 temporal_substring = "" for i in range(len(s)): if s[i] in temporal_substring: temporal_substring = temporal_substring.replace(temporal_substring[0], "") if longest_substring < len(temporal_substring): longest_substring = len(temporal_substring) temporal_substring += s[i] if len(temporal_substring) > longest_substring: return len(temporal_substring) else: return longest_substring
class Sudoku: def __init__(self, data): self.data = data def is_valid(self): if not self.data: return False length = len(self.data) if length**.5 != int(length**.5): return False for i in self.data: if len(i) != length: return False columns = [[] for i in range(length)] squares = [] for i in range(length): for j in range(length): columns[i].append(self.data[j][i]) square = int(length**.5) for i in range(square): # 1 for j in range(square): # 0 temp = j*square new = [] for m in range(square): new.extend(self.data[i*square+m][temp:temp+square]) squares.append(new) for i in range(length): # 4 for j, item in enumerate(self.data[i]): if item < 1 or item > length: return False index = (i // square)*square + (j // square) if (self.data[i].count(item) != 1 or columns[j].count(item) != 1 or squares[index].count(item) != 1): return False return True if __name__ == "__main__": board = [ [7, 8, 4, 1, 5, 9, 3, 2, 6], [5, 3, 9, 6, 7, 2, 8, 4, 1], [6, 1, 2, 4, 3, 8, 7, 5, 9], [9, 2, 8, 7, 1, 5, 4, 6, 3], [3, 5, 7, 8, 4, 6, 1, 9, 2], [4, 6, 1, 9, 2, 3, 5, 8, 7], [8, 7, 6, 3, 9, 4, 2, 1, 5], [2, 4, 3, 5, 6, 1, 9, 7, 8], [1, 9, 5, 2, 8, 7, 6, 3, 4] ] board2 = [ [1, 4, 2, 3], [3, 2, 4, 1], [4, 1, 3, 2], [2, 3, 1, 4] ] test_case = Sudoku(board) print(test_case.is_valid())
""" Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. """ def maxArea(height): most_water = 0 i = 0 j = len(height) - 1 while j-i > 0: temporal_square = min(height[i], height[j]) * (j-i) if temporal_square > most_water: most_water = temporal_square if height[i] > height[j]: j -= 1 else: i += 1 return most_water
import numpy as np import matplotlib.pyplot as plt from sklearn.neural_network import MLPRegressor def MSE(y, yhat): return np.mean((y - yhat)**2) def example_data(rows = 100): x = np.linspace(start=0, stop=30, num = 100).reshape((rows, 1)) #y = 2*np.sin(x) + x y = np.sqrt(x) # scale the data x = (x - 15)/10 y = y /10 return x, y.reshape(len(y)) X, y = example_data() model = MLPRegressor(hidden_layer_sizes=(50,5), activation='relu', shuffle=False, batch_size= len(y), solver='sgd', alpha=0, learning_rate='constant', learning_rate_init=0.0001, max_iter=100000, validation_fraction=0) model.fit(X = X, y = y) print(model.loss_) yhat = model.predict(X) plt.plot(y) plt.plot(yhat) plt.show()
import curses import time import random from collections import defaultdict from itertools import tee CONNECTED = {"N": 1, "S": 2, "E": 4, "W": 8} DIRECTIONS = {"N": (-1, 0), "S": (1, 0), "E": (0, 1), "W": (0, -1)} ANTIPODES = {"N": "S", "S": "N", "W": "E", "E": "W"} WALL = {12: '═', 3: '║', 10: '╗', 5: '╚', 9: '╝', 6: '╔', 7: '╠', 11: '╣', 14: '╦', 13: '╩', 15: '╬', 0: " ", 4: "═", 8: "═", 1: "║", 2: "║"} VISITED = 16 class Maze: def __init__(self, height, width, start=(0, 0)): self.height = height self.width = width self.stack = [] self.cells = {(y, x): 0 for y in range(height) for x in range(width)} self.build(start) def eligible_neighbours(self, y, x): return [((y + i, x + j), d) for d, (i, j) in DIRECTIONS.items() if (y + i, x + j) in self.cells.keys() and not self.cells[(y + i, x + j)] & VISITED] def connected_cells(self, y, x): cell_directions = [d for (d, v) in CONNECTED.items() if v & self.cells[(y, x)]] return {(y + i, x + j): d for d, (i, j) in DIRECTIONS.items() if d in cell_directions} def build(self, start): current_cell = start while [c for c in self.cells.values() if not c & VISITED]: self.cells[current_cell] |= VISITED eligible_neighbours = self.eligible_neighbours(*current_cell) if not eligible_neighbours: next_cell = self.stack.pop() else: self.stack.append(current_cell) next_cell, direction = random.choice(eligible_neighbours) self.cells[current_cell] |= CONNECTED[direction] self.cells[next_cell] |= CONNECTED[ANTIPODES[direction]] current_cell = next_cell def track(self, start=(0, 0)): yield start current_cell = start self.stack = [] for coord in self.cells.keys(): self.cells[coord] &= ~VISITED while [c for c in self.cells.values() if not c & VISITED]: self.cells[current_cell] |= VISITED eligible_neighbours = [(c, d) for (c, d) in self.connected_cells(*current_cell).items() if not self.cells[c] & VISITED] if not eligible_neighbours: next_cell = self.stack.pop() else: self.stack.append(current_cell) next_cell, direction = random.choice(eligible_neighbours) yield next_cell current_cell = next_cell def __repr__(self): buffer = [[0 for _ in range(2 * self.width + 1)] for _ in range(2 * self.height + 1)] for row in range(self.height): for col in range(self.width): if row: buffer[2 * row][2 * col + 1] = (~self.cells[row, col] & CONNECTED["N"]) << 3 if col: buffer[2 * row + 1][2 * col] = (~self.cells[row, col] & CONNECTED["W"]) >> 3 if row and col: buffer[2 * row][2 * col] = (buffer[2 * row][2 * col - 1] | (buffer[2 * row][2 * col + 1] >> 1) | buffer[2 * row - 1][2 * col] | (buffer[2 * row + 1][2 * col] << 1)) for row in range(1, 2 * self.height): buffer[row][0] = CONNECTED["N"] | CONNECTED["S"] | (buffer[row][1] >> 1) buffer[row][2 * self.width] = (CONNECTED["N"] | CONNECTED["S"] | buffer[row][2 * self.width - 1]) for col in range(1, 2 * self.width): buffer[0][col] = (CONNECTED["E"] | CONNECTED["W"] | (buffer[1][col] << 1)) buffer[2 * self.height][col] = (CONNECTED["E"] | CONNECTED["W"] | buffer[2 * self.height - 1][col]) buffer[0][0] = CONNECTED["S"] | CONNECTED["E"] buffer[0][2 * self.width] = CONNECTED["S"] | CONNECTED["W"] buffer[2 * self.height][0] = CONNECTED["N"] | CONNECTED["E"] buffer[2 * self.height][2 * self.width] = CONNECTED["N"] | CONNECTED["W"] return "\n".join(["".join(WALL[cell] for cell in row) for row in buffer]) def path(maze, start, finish): heuristic = lambda node: abs(node[0] - finish[0]) + abs(node[1] - finish[1]) nodes_to_explore = [start] explored_nodes = set() parent = {} global_score = defaultdict(lambda: float("inf")) global_score[start] = 0 local_score = defaultdict(lambda: float("inf")) local_score[start] = heuristic(start) def retrace_path(current): total_path = [current] while current in parent.keys(): current = parent[current] total_path.append(current) return reversed(total_path) while nodes_to_explore: nodes_to_explore.sort(key=lambda n: local_score[n]) current = nodes_to_explore.pop() if current == finish: return retrace_path(current) explored_nodes.add(current) for neighbour in maze.connected_cells(*current).keys(): tentative_global_score = global_score[current] + 1 if tentative_global_score < global_score[neighbour]: parent[neighbour] = current global_score[neighbour] = tentative_global_score local_score[neighbour] = global_score[neighbour] + heuristic(neighbour) if neighbour not in explored_nodes: nodes_to_explore.append(neighbour) def draw_path(path, screen, delay=0, head=None, trail=None, skip_first=True): if not head: head=("█", curses.color_pair(1)) if not trail: trail=("█", curses.color_pair(1)) current_cell = next(path) old_cell = current_cell for idx, next_cell in enumerate(path): first = (not idx) and skip_first if screen.getch() == ord("q"): break screen.refresh() for last, cell in enumerate([(current_cell[0] + t * (next_cell[0] - current_cell[0]), current_cell[1] + t * (next_cell[1] - current_cell[1])) for t in [0, 1/2]]): time.sleep(delay) if not first: screen.addstr(*coords(cell), *head) if last: if not first: screen.addstr(*coords(current_cell), *trail) old_cell = cell elif not first: screen.addstr(*coords(old_cell), *trail) screen.refresh() current_cell = next_cell def coords(node): return (int(2 * node[0]) + 1, int(2 * node[1]) + 1) def construction_demo(maze, screen): head = ("*", curses.color_pair(2)) trail = (".", curses.color_pair(1)) draw_path(maze.track(), screen, delay=.1, head=head, trail=trail, skip_first=False) screen.nodelay(False) screen.getch() def pathfinding_demo(maze, screen): start = [] finish = [] solution = None old_solution = None def reset(start_or_finish, cell, colour): nonlocal solution, old_solution if start_or_finish: screen.addstr(*coords(start_or_finish.pop()), " ") screen.addstr(*coords(cell), "█", colour) screen.refresh() if old_solution: draw_path(old_solution, screen, head=" ", trail=" ") start_or_finish.append(cell) if start and finish: solution, old_solution = tee(path(maze, start[0], finish[0])) draw_path(solution, screen) while True: key = screen.getch() if key == ord("q"): break elif key == curses.KEY_MOUSE: _, x, y, _, state = curses.getmouse() cell = (int(y / 2), int(x / 2)) if state & curses.BUTTON3_PRESSED: reset(finish, cell, curses.color_pair(2)) elif state & curses.BUTTON1_PRESSED: reset(start, cell, curses.color_pair(3)) def main(screen): curses.curs_set(False) curses.mousemask(curses.ALL_MOUSE_EVENTS) screen.nodelay(True) curses.init_pair(1, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK) screen.clear() height, width = screen.getmaxyx() height, width = int((height - 2)/2), int((width - 2)/2) maze = Maze(height, width) screen.addstr(0, 0, str(maze)) screen.refresh() # construction_demo(maze, screen) pathfinding_demo(maze, screen) if __name__ == '__main__': curses.wrapper(main)
""" Karis Kim 1624226 CIS 2348 """ def selection_sort_descend_trace(lst): for n in range(len(lst) - 1): largest_value = n for j in range(n + 1, len(lst)): if lst[j] > lst[largest_value]: largest_value = j lst[n], lst[largest_value] = lst[largest_value], lst[n] for i in lst: print(i, end=' ') print() return lst if __name__ == '__main__': numbers = [int(i) for i in input().split()] selection_sort_descend_trace(numbers)
""" Karis Kim CIS 2348 1624226 """ def caroptions(): # options print("Davy's auto shop services") print("Oil change -- $35") print("Tire rotation -- $19") print("Car wash -- $7") print("Car wax -- $12") # setting the prices oil_change = 35; tire_rotation = 19; car_wash = 7; car_wax = 12; total = 0; first_service = 0; sec_service = 0; caroptions() # userinput option_one = input("Select first service:\n") if ("oil" in option_one.lower()): total = total + oil_change; first_service = oil_change; elif ("tire" in option_one.lower()): total = total + tire_rotation; first_service = tire_rotation; elif ("wash" in option_one.lower()): total = total + car_wash; first_service = car_wash; elif ("wax" in option_one.lower()): total = total + car_wax; first_service = car_wax; elif (option_one == "-"): option_one = "No service"; total = total + 0; # userinput for 2nd service option_two = input("Select second service:\n") if ("oil" in option_two.lower()): total = total + oil_change; sec_service = oil_change; elif ("tire" in option_two.lower()): total = total + tire_rotation; sec_service = tire_rotation; elif ("wash" in option_two.lower()): total = total + car_wash; sec_service = car_wash; elif ("wax" in option_two.lower()): total = total + car_wax; sec_service = car_wax; elif (option_two == "-"): option_two = "No service"; sec_service = 0; total = total + 0; print() print("Davy's auto shop invoice") print() # noservice part of the code if (option_one == "No service") and (option_two == "No service"): print("Service 1: " + first_service) print("Service 2: " + sec_service) print() elif (sec_service == "No service"): print("Service 1: " + option_one + ", $" + option_one) print("Service 2: " + option_two) print() elif (option_one == "No service"): print("Service 1: " + option_one) print("Service 2: " + option_one + ", $" + str(option_two)) print() else: print("Service 1: " + option_one + ", $" + str(first_service)) print("Service 2: " + option_two + ", $" + str(sec_service)) print() # give output total print("Total: $" + str(total))
""" Karis Kim 1624226 CIS 2348 """ numbers = input().split() noneg_int=[] for num in numbers: # Convert the string number into integer. num = int(num) # Checks whether number is non-negative. if num >= 0: noneg_int.append(num) noneg_int.sort() for i in noneg_int: print(i,end=' ')
""" % the Set-game. % In Set, 12 cards are placed on the table. % Each card has some object(s) depicted. A card has 4 'parameters': % - number % - shape % - filling % - colour % % The objective is to find sets (|set| = 3) of cards that have all of % these properties the same, or, per property all different. See the % web if needed: https://secure.wikimedia.org/wikipedia/en/wiki/Set_(game) % and http://tao-game.dimension17.com/ % %: card(Colour, Shape, Fill, Count). % number (one, two, or three); % symbol (diamond, squiggle, oval); % shading (full, striped, or empty); % and color (red, green, or purple) """ import itertools import random numbers = (1,2,3) shapes = ("diamond", "squiggle", "oval") fills = ("full", "striped", "empty") colors = ("red", "green", "purple") class Card(object): def __init__(self, color, shape, fill, number): assert color in colors assert shape in shapes assert fill in fills assert number in numbers self.color = color self.shape = shape self.fill = fill self.number = number def __repr__(self): return "Card(%s, %s, %s, %i)"%(self.color, self.shape, self.fill, self.number) def __getitem__(self, index): return self.__dict__[index] def color_same(cards, n=3): assert len(cards) == n return (cards[0].color == cards[1].color == cards[2].color) def attr_same(cards, attr): first = cards[0][attr] same = all((card[attr] == first for card in cards)) return same def attr_diff(cards, attr): values = [card[attr] for card in cards] if sorted(list(values)) == sorted(list(set(values))): return True else: return False def findsets(cards, n=3): """cards is a list of Card-objects. For each possible pair of n cards, verify if it is a set""" attributes = ("color", "shape", "fill", "number") sets = set() for triple in itertools.combinations(cards, n): #if for all attributes, the attribute is either all the same of totally different: if all((attr_diff(triple, attribute) or attr_same(triple, attribute) for attribute in attributes)): sets.add(tuple(sorted(triple))) #don't add multiple sets with the same card, only with different orders. return sets def generate_all_cards(): """Generates all possible combinations of properties""" for color in colors: for fill in fills: for shape in shapes: for num in numbers: yield Card(color, shape, fill, num) def brute(): sets = findsets(all_cards)#findsets(random.sample(all_cards, 15))#findsets(set1) for s in sets: for card in s: print card print "-------" return sets if __name__ == "__main__": ## sets = brute() all_cards = list(generate_all_cards()) table = random.sample(all_cards, 12) c1 = Card("green", "squiggle", "full", 1) c2 = Card("green", "oval", "empty", 2) c3 = Card("green", "diamond", "striped", 3) c4 = Card("green", "diamond", "full", 3) allcards = [c1, c2, c3, c4] set1 = [c1, c2, c3] noset = [c1, c2, c4] k1 = Card("purple", "squiggle", "full", 1) k2 = Card("purple", "squiggle", "striped", 1) k3 = Card("purple", "oval", "empty", 1) k4 = Card("green", "squiggle", "empty", 1) k5 = Card("purple", "squiggle", "empty", 3) k6 = Card("green", "diamond", "full", 2) k7 = Card("purple", "diamond", "full", 3) k8 = Card("red", "oval", "empty", 1) k9 = Card("red", "oval", "empty", 2) k10 = Card("red", "diamond", "empty", 3) k11 = Card("green", "oval", "empty", 2) k12 = Card("purple", "diamond", "full", 1) cards = [k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12] print findsets(cards)
def checkWinner(board): """ Returns true if winner exist """ states = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5 ,8], [0, 4, 8], [2, 4, 6] ] # flatten board flat_board = [] for row in board: for col in row: flat_board.append(col) # No empty states, return tie if '' not in flat_board: return 'tie' # Winner exist for state in states: a, b, c = state if flat_board[a] == flat_board[b] == flat_board[c] and flat_board[a] != '': return flat_board[a] # Game still continuing return '' def minimax(board, depth, isMax): """ Takes a 3x3 list depth is recursion depth isMax is maximizing player """ bestMove = [] result = checkWinner(board) if result == 'x': # heristic values return 10 if result == 'o': return -10 if result == 'tie': return 0 if isMax: # maximizing player is 'x' bestScore = -float("Inf") if result == '': # is there empty spot to play for i in range(3): for j in range(3): if board[i][j] == '': board[i][j] = 'x' # add depth to optimize play, want player to choose fastest win value = minimax(board, depth+1, False) - depth board[i][j] = '' bestScore = max(bestScore, value) else: # minimizing player is 'o' bestScore = float("Inf") if result == '': for i in range(3): for j in range(3): if board[i][j] == '': board[i][j] = 'o' value = minimax(board, depth+1, True) + depth board[i][j] = '' bestScore = min(bestScore, value) # return the best score for the given board return bestScore def calculateScores(board, isMax): # calculate values with heuristic score scores = [ ['', '', ''], ['', '', ''], ['', '', ''] ] for i in range(3): for j in range(3): if board[i][j] == '': if isMax: board[i][j] = 'x' scores[i][j] = minimax(board, 0, not isMax) else: board[i][j] = 'o' scores[i][j] = minimax(board, 0, not isMax) board[i][j] = '' return scores def pickOptimalMove(board, isMax, returnScore=False): if isMax: bestScore = -float("Inf") for i in range(3): for j in range(3): if board[i][j] == '': board[i][j] = 'x' score = minimax(board, 0, False) board[i][j] = '' if score > bestScore: bestScore = score bestMove = (i, j) else: bestScore = float("Inf") for i in range(3): for j in range(3): if board[i][j] == '': board[i][j] = 'o' score = minimax(board, 0, True) board[i][j] = '' if score < bestScore: bestScore = score bestMove = (i, j) if returnScore: return bestMove, bestScore return bestMove # board = [ # ['x', 'x', ''], # ['', 'o', ''], # ['', '', 'o'] # ] board = [ ['', 'o', 'x'], ['o', 'x', ''], ['', '', ''] ] # (2, 0) # board = [ # ['x', 'o', ''], # ['o', 'x', ''], # ['', '', ''] # ] # (2, 2) # board = [ # ['x', 'o', ''], # ['x', 'o', ''], # ['', '', ''] # ] (2, 0) # board = [ # ['', '', ''], # ['', '', ''], # ['', '', ''] # ] print(minimax(board, 0, isMax=True)) print(calculateScores(board, True)) print(pickOptimalMove(board, isMax=True, returnScore=False)) ### Play game # while True: # print(calculateScores(board, isMax=True)) # ai = pickOptimalMove(board, isMax=True, returnScore=False) # board[ai[0]][ai[1]] = 'x' # print(board) # x = int(input()) # y = int(input()) # board[x][y] = 'o' # print(board)
#!/usr/bin/env python3 num = 1000 def main(): for a in range(1,num,1): for b in range (1,num-1,1): c = num - a - b if a**2 + b**2 == c**2: print(a * b * c) return if __name__ == '__main__': main()
#!/usr/bin/env python3 def is_pallindrome(i): str_ = str(i) str_rev = rev(str_) return str_ == str_rev def rev(s): return s[::-1] def main(): i=999 j=999 palindromes = [] for m in range(i,100,-1): for n in range(j,100,-1): if is_pallindrome(m * n): palindromes.append(m*n) print(max(palindromes)) if __name__ == '__main__': main()
#!/usr/bin/env python3 from math import factorial n = 20 def main(): print (int((factorial(2 * n) / (factorial(n) * factorial(n))))) if __name__ == '__main__': main()
#!/usr/bin/env python3 import re def parse_data(file): data_file = open(file, 'r') data = data_file.read().splitlines() passports = [] attr = {} for line_number, line in enumerate(data): # print(line) key_value = line.split(' ') # print(key_value) for i in key_value: # print(i) if '' not in key_value: key = i.split(':')[0] value = i.split(':')[1] # print(key) # print(value) attr[key] = value if ('' in key_value) or (line_number == (len(data) - 1)): passports.append(attr) attr = {} continue return passports def check_year(year, min, max): if len(str(year)) == 4 and int(year) >= min and int(year) <= max: return True return False def check_height(height): unit_re = re.compile('.*(cm|in)') unit = unit_re.match(height) if unit and unit.group(1) == 'cm': height_re = re.compile('(\d{3})cm') height_digits = height_re.match(height) if height_digits and int(height_digits.group(1)) >= 150 and int(height_digits.group(1)) <= 193: return True elif unit and unit.group(1) == 'in': height_re = re.compile('(\d{2})in') height_digits = height_re.match(height) if height_digits and int(height_digits.group(1)) >= 59 and int(height_digits.group(1)) <= 76: return True return False def check_haircolor(haircolor): haircolor_re = re.compile('#([0-9a-f]{6})') haircolor_match = haircolor_re.match(haircolor) if haircolor_match: return True return False def check_eyecolor(eyecolor): valid_colors = ['amb','blu','brn','gry','grn','hzl','oth'] if eyecolor in valid_colors: return True return False def check_id(id): if len(str(id)) == 9: return True return False def check_passport(passport): required_field = ['byr','iyr','eyr','hgt','hcl','ecl','pid','cid'] missing_keys = [] for key in required_field: if key not in passport: if key == 'cid': continue missing_keys.append(key) if key == 'byr' and key not in missing_keys: if not check_year(passport['byr'], 1920, 2002): missing_keys.append(key) if key == 'iyr' and key not in missing_keys: if not check_year(passport['iyr'], 2010, 2020): missing_keys.append(key) if key == 'eyr' and key not in missing_keys: if not check_year(passport['eyr'], 2020, 2030): missing_keys.append(key) if key == 'hgt' and key not in missing_keys: if not check_height(passport['hgt']): missing_keys.append(key) if key == 'hcl' and key not in missing_keys: if not check_haircolor(passport['hcl']): missing_keys.append(key) if key == 'ecl' and key not in missing_keys: if not check_eyecolor(passport['ecl']): missing_keys.append(key) if key == 'pid' and key not in missing_keys: if not check_id(passport['pid']): missing_keys.append(key) return missing_keys def main(): passports = parse_data('data') # print("{}".format(passports)) # print(len(passports)) number_valid_passports = 0 for passport in passports: missing = check_passport(passport) # print(missing) # print(len(missing)) if len(missing) == 0: number_valid_passports += 1 print("# valid passports: {}".format(number_valid_passports)) if __name__== "__main__": main()
# A light weight- python program to count the vote to sum and find the winner # the length of the file is 803,000 import csv my_file = "../GWDC201805DATA3-Class-Repository-DATA/03-Python/Resources/election_data.csv" with open(my_file, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") # To read the header from the csv file header = next(csvreader) #print(header) # intialize the vote count vote_count = 0 # intialize and record candidate name candidate_name = [] # intialize and record each candidate name and vote count candidate_vote = {} # track the winner_vote wining_vote = 0 # track wining candidate wining_candidate = "" for reader in csvreader: vote_count += 1 candidate = reader[2] if candidate not in candidate_name: # In a way, this loop is "discovering" candidates as it goes and counts the vote while it starts counting # the candidate vote candidate_name.append(candidate) candidate_vote[candidate] = 1 else: candidate_vote[candidate] = candidate_vote[candidate] + 1 for row in candidate_vote: vote_per = candidate_vote.get(row) vote_percentage = vote_per/vote_count if vote_per > wining_vote: wining_vote = vote_per wining_candidate = row winner_percentage = wining_vote/vote_count print(row) print(vote_per) print(vote_percentage* 100,"%") print("-------------") print("winner summary") print(f'Winner :{wining_candidate}') print(f'wining count : {wining_vote}') print(f'wining percentage : {winner_percentage * 100}%')
# 第五章 クラスの作成/インスタンスの作成/メソッドの利用/継承 class MyObj: pass ob = MyObj() print(type(ob)) # メモクラス (Memo)を作成する class Memo: message = "OK" memo = Memo() print(memo.message) memo.message = "Hello!" print(memo.message) class MyClass: message = "OK" # print関数とは別にここではprintメソッドを定義する def print(self): # selfでなくても大丈夫 print(self.message) ob1 = MyClass() ob1.message = "Hello Python!" ob1.print() class MyYou: def __init__(self, msg): self.message = msg def print(self): print(self.message) ob2 = MyYou('Hello!') ob2.print() class MyMe: def __init__(self): self.__num = 123 # プライベート変数だからインスタンスでのアクセスができない self.message = 'OK!' def print(self): print(str(self.__num) + 'num' + self.message) ob4 = MyMe() ob5 = MyMe() ob5.__num = 321 # プライベート変数は変更されない -> 出力後 123のまま ob4.message = 'Hi!' ob4.print() ob5.print() class MyMe: message = "OK!" @classmethod def print(cls): print(cls.message) MyMe.print() # クラスメソッドは、クラスから直接呼び出して実行できる MyMe.message = 'Welcome' MyMe.print() class Str: def __init__(self, msg): self.message = msg def print(self): print(self.message) def __str__(self): return "<Str: message='>" + self.message + "'>" ob7 = Str('Hi!you') print(ob7) class Person: name = "name" class Human(Person): age = 20 ob10 = Person() print(ob10.name) ob9 = Human() print(ob10.name + ',' + str(ob9.age)) ''' # クラスの定義    class クラス名 : クラスの内容 # インスタンスの作成 クラス名() # クラス変数のクラス内での定義    class クラス名 : 変数 = 値 # 値を取り出す    インスタンス.変数 # 値を変更する    インスタンス.変数 = 値 # メソッドの利用    class クラス名: def メソッド名(self, 引数): --------実行文--------   # 初期化のメソッド      def __init__(self): ---------初期化処理-------- # プライベート変数 __変数名 = 値 # クラス変数へのアクセス   クラス.変数 # クラスメソッドの書き方 @classmethod def メソッド名(cls, 引数1, 引数2,...): # 演算子のための演算メソッド{ # +演算子 __add__(self, other) # +=演算子 __iadd__(self, other) # -演算子 __sub__(self, other) # -=演算子 __isub__(self, other) # *演算子 __mul__(self, other) # *=演算子 __isul__(self, other) # /演算子 __truediv__(self, other) # /=演算子 __itruediv__(self, other) # //演算子 __floordiv__(self, other) # //=演算子 __ifloordiv__(self, other) # %演算子 __mod__(self, other) # %=演算子 __imod__(self, other) } # 文字列として取り出す動作を定義する def__str__(self): return 文字列 # プロパティの定義    @property def プロパティ名(self): return 値 # プロパティ名.setter def プロパティ名(self, 値): ---------値を設定する処理------ # 継承するクラスの定義    class クラス名(継承クラス): -----実行中----- '''
from enum import Enum import pickle class ReplayMode(Enum): WRITE = 1 READ = 2 class Replay: """ A class for the record used for the replay. """ def __init__(self, seed=None, path=None): """ If path isn't None, the replay should load the corresponding file. Otherwise, the instance goes write mode and can be later written on the discs. """ if path is not None: self.mode = ReplayMode.READ self.load(path) self.position = 0 else: self.seed = seed self.mode = ReplayMode.WRITE self.history = [] def set_opts(self, options): """ This should set the variable : difficulty and number of players in order to save them to the replay """ assert self.mode == ReplayMode.WRITE, "Wrong Mode for Replay class" self.options = options def get_opts(self): """ Give option in read mode """ assert self.mode == ReplayMode.READ, "Wrong Mode for Replay class" return self.options def load(self,path): """ Should load from some file """ assert self.mode == ReplayMode.READ, "Wrong Mode for Replay class" with open(path, "rb") as f: self.options, self.seed, self.history = pickle.load(f) def save(self, path): """ write the replay in order to load it later """ assert self.mode == ReplayMode.WRITE, "Wrong Mode for Replay class" with open(path, "wb") as f: pickle.dump((self.options, self.seed, self.history), f, pickle.HIGHEST_PROTOCOL) def is_empty(self): """ return if this instance has been initialised """ return self.history == [] def read(self, frame): """ Return what happens at a given frame Should happen only in read mode and in sequential order """ assert self.mode == ReplayMode.READ, "Wrong Mode for Replay class" while True: if self.position >= len(self.history) or self.history[self.position][0] > frame: return None if self.history[self.position][0] == frame: return self.history[self.position][1] if self.history[self.position][0] < frame: self.position += 1 def write(self, frame, key): """ Write to the end of the file what's happening Should be called only in write mode """ assert self.mode == ReplayMode.WRITE, "Wrong Mode for Replay class" self.history.append([frame, key])
import random from constants import * class game: def __init__(self): self.ball_y = WINDOW_HEIGHT - BALL_RADIUS # y position of ball self.ball_x = BALL_X_POS # x position of ball self.y_change = 0 # change in y of the ball self.score = 0 # score of the game self.obstacles = [] # list of obstacles self.is_over = False # is the game over self.jumped = False # represents whether the ball was jumped self.in_air = False # represents whether the ball is in the air self.current_obstacle = 0 # represents index of current obstacle self.generation = 0 # generation of networks self.top_score = 0 # top score of all networks def get_top_score(self): return self.top_score def set_top_score(self, networks): ''' Updates top score based on hit networks from previous generation ''' new_score = networks[0]['score'] if new_score > self.top_score: self.top_score = new_score def get_generation(self): return self.generation def increment_generation(self): ''' Increments self.generation by one ''' self.generation += 1 def move_ball(self): ''' Moves ball vertically according to gravity by changing ball_y field. ''' # ball on the floor and in_air is True if self.in_air and self.ball_y >= WINDOW_HEIGHT - (BALL_RADIUS * 2): self.jumped = False self.in_air = False self.y_change = 0 # ball on the floor and jumped is True elif self.ball_y >= WINDOW_HEIGHT - (BALL_RADIUS * 2) and self.jumped: self.ball_y += self.y_change self.y_change += GRAVITY self.in_air = True elif self.ball_y >= WINDOW_HEIGHT - (BALL_RADIUS * 2) and not self.jumped: self.y_change = 0 else: self.ball_y += self.y_change self.y_change += GRAVITY def jump_ball(self): ''' Makes the ball jump up by changing y_change ''' # only jump if y_change is zero if not self.jumped: self.y_change -= 25 self.jumped = True def generate_obstacle(self): ''' Generates an obstacle to be added to self.obstacles with random heights within a range ''' height = random.randint(HEIGHT_MIN, HEIGHT_MAX) o = obstacle(height, OBSTACLE_WIDTH) self.obstacles.append(o) def clear_obstacles(self): self.obstacles = [] def move_obstacles(self): ''' Moves every obstacle across the screen ''' for obs in self.obstacles: obs.x_loc -= OBSTACLE_X_CHANGE def is_collision(self, obstacles): ''' Checks if a collision occured between ball and current obstacle ''' # confirm that obstacle is created if len(obstacles) > self.current_obstacle: current_obs = obstacles[self.current_obstacle] # True if right wall of ball is past left wall of obstacle passed_left_wall = (self.ball_x + BALL_RADIUS) >= current_obs.x_loc # True if bottom of ball is below the wall height below_wall_height = (self.ball_y + BALL_RADIUS) >= (WINDOW_HEIGHT - current_obs.height) # True if left wall of ball is not passed right wall of obstacle not_passed_right_wall = (self.ball_x - BALL_RADIUS) <= current_obs.x_loc + current_obs.width if passed_left_wall and below_wall_height and not_passed_right_wall: print('hit') #self.is_over = True return True elif not not_passed_right_wall: self.current_obstacle += 1 self.score += 1 return False def get_inputs(self, obstacles): if len(obstacles) > self.current_obstacle: current_obs = obstacles[self.current_obstacle] x_obstacle = current_obs.x_loc # x location of current obstacle height_obstacle = current_obs.height return x_obstacle - self.ball_x, height_obstacle else: return None class obstacle: def __init__(self, height, width): self.x_loc = INIT_X_LOC self.height = height self.width = width
" Step 2: Add drop-downs" execfile("step0.py") # How Bokeh interpret all goes in one single document (container) from bokeh.io import curdoc from bokeh.layouts import row, column # Column data source to wrap our data from bokeh.models import ColumnDataSource # Select boxes for drop down menu (widget) from bokeh.models.widgets import Select # Defining the figure object from bokeh.plotting import figure apple = load_ticker("AAPL") google = load_ticker("GOOG") data = pd.concat([apple, google], axis=1) datasource = ColumnDataSource(data) # Create the correlation plot (initialising the plot) plot = figure(title="Correlation Plot", plot_width=500, plot_height=500) plot.circle("AAPL_returns", "GOOG_returns", size=2, source=datasource) plot.title.text_font_size = "25px" plot.title.align = "center" # Create # We just pick 5 from 100 stocks STOCKLIST = ['AAPL', 'GOOG', 'INTC', 'BRCM', 'YHOO'] # Creating two drop down boxes ticker1 = Select(value="AAPL", options=STOCKLIST) ticker2 = Select(value="GOOG", options=STOCKLIST) # Define the layout (creating a column with the boxes, and then a row # between the column and the plot) layout = row(column(ticker1, ticker2), plot) curdoc().add_root(layout) curdoc().title = "Stock Correlations"
from graphics import* def askUserColour(): coloursList = [] validColours = ["red", "green", "blue", "magenta", "cyan", "orange", "brown", "pink"] while True: colour = input("Enter a colour for your patch (eg: red, green, " + "blue, magenta, cyan, orange, brown and pink): ") if colour in validColours: #checks if the colour is valid coloursList.append(colour) validColours.remove(colour) else: print("Invalid, please re-enter eg:", validColours) if len(coloursList) == 3: print("Your colour list for your patch is complete") break return coloursList def askUserSize(): while True: validSizes = ["5", "7", "9", "11"] size = input("Enter patch size (eg: 5, 7, 9, 11): ") #checks input is a valid type if size in validSizes: return int(size) break else: print("Invalid, please re-enter (eg:", validSizes, ": ") #This patch creates the final digit pattern def drawFinalDigitPatch(win, startX, startY, coloursList): for i in range(0, 100, 20): line1 = Line(Point(startX + i, startY), Point(startX + 100, startY + 100 - i)) line2 = Line(Point(startX, startY + i), Point(startX + 100 - i, startY + 100)) line1.draw(win) line1.setOutline(coloursList) line2.draw(win) line2.setOutline(coloursList) line3 = Line(Point(startX + i, startY), Point(startX, startY + i)) line4 = Line(Point(startX + i, startY + 100), Point(startX + 100, startY + i)) line3.draw(win) line3.setOutline(coloursList) line4.draw(win) line4.setOutline(coloursList) #Draws part of the penultimate patch def drawPenultimatePatch1(win, startX, startY, coloursList, i, z): rectangle1 = Rectangle(Point(startX + i, startY + z), Point(startX + 20 + i, startY + 20 + z)) rectangle1.draw(win) rectangle1.setFill("white") triangle1 = Polygon(Point(startX + i, startY + z), Point(startX + i, startY + 20 + z), Point(startX + 10 + i, startY + 10 + z)) triangle1.draw(win) triangle1.setFill(coloursList) triangle2 = Polygon(Point(startX + 20 + i, startY + z), Point(startX + 20 + i, startY + 20 + z), Point(startX + 10 + i, startY + 10 + z)) triangle2.draw(win) triangle2.setFill(coloursList) #Draws second part of the penultimate patch def drawPeniltimatePatch2(win, startX, startY, coloursList, i, z): rectangle2 = Rectangle(Point(startX + i, startY + z), Point(startX + 20 + i, startY + 20 + z)) rectangle2.draw(win) rectangle2.setFill("white") triangle3 = Polygon(Point(startX + i, startY + z), Point(startX + i + 20, startY + z), Point(startX + 10 + i, startY + 10 + z)) triangle3.draw(win) triangle3.setFill(coloursList) triangle4 = Polygon(Point(startX + i, startY + 20 + z), Point(startX + 20 + i, startY + 20 + z), Point(startX + 10 + i, startY + 10 + z)) triangle4.draw(win) triangle4.setFill(coloursList) def drawPeniltimatePatch(win, x, y, coloursList): count = 0 for z in range (0, 100, 20): for i in range (0, 100, 20): if count % 2 == 0: drawPenultimatePatch1(win, x, y, coloursList, i, z) else: drawPeniltimatePatch2(win, x, y, coloursList, i, z) #draws the two parts of the peniltimate patch in the window count += 1 def drawPatchWork(win, x, y, coloursList): i = 100 size = x size = y colourListIndex = 0 for y in range(0, size * 100, 100): for x in range(0, size * 100, 100): if x < i: drawFinalDigitPatch(win, size + x, size + y, coloursList[colourListIndex]) colourListIndex += 1 #makes the list loop through the differnt colours when drawing each patch else: drawPeniltimatePatch(win, size + x, size + y, coloursList[colourListIndex]) colourListIndex += 1 if colourListIndex == 3: colourListIndex = 0 i = i + 100 def main(): size = askUserSize() coloursList = askUserColour() win = GraphWin("PW", size * 100, size * 100) drawPatchWork(win, size, size, coloursList) win.getMouse() win.close() main()
def get_all_files(path_string): all_files = [] p = Path(path_string) for file_or_folder in p.iterdir(): if file_or_folder.is_dir(): print(str(file_or_folder) + " is a folder") f = Path(path_string + '/' + str(file_or_folder) + '/') print("reading " + str(f)) get_all_files(f) else: all_files.append(file_or_folder) return all_files
# We now want to count the number of items in the list (6). What do we need to add to the accumulator now? numbers = [4, 8, 15, 16, 23, 42] count = 0 for n in numbers: count = count + __ print(count)
# Print the 3x3 identity matrix with nested lists. identity_3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] print(identity_3)
# Run the code to see what happens when we try to retrieve the length of one number, which is not a list. Note: First run the code as it is, and only then fix the code by making a list with on element on line 1. list_of_one = 5 should_be_one = len(list_of_one) print(should_be_one)
# Store 27 in the variable temperature. Line 2 prints the value of temperature so if you fill it correctly it will print 137. temperature = __ print(temperature)
# Some things are wrong with the nested loop. Can you fix it? suits = ['clubs', 'diamonds', 'hearts', 'spades'] values = ['7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] for suit in suits: for value in values: print(value + ' of ' + suit.capitalize())
# <div>We want to use the nested loops to print the cards in order of value, so: 7 of Clubs</div><div>7 of Diamonds 7 of Hearts</div><div>7 of Spades</div><div>8 of Clubs </div><div>... How should we change the code?</div><div> </div> suits = ['clubs', 'diamonds', 'hearts', 'spades'] values = ['7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'] for suit in suits: for value in values: print(value + ' of ' + suit.capitalize())
# Negative numbers get elements from the end of a list. Fill the blanks to make the assertEqual's pass. beatles = ['John', 'Paul', 'George', 'Ringo'] assertEqual(beatles[-1], __) assertEqual(beatles[-2], __) assertEqual(beatles[-3], __)
# Change line 2 such that the loop prints all numbers again. But... do not use while odd != []:! It must be as short as possible! odd = [1, 3, 5, 7, 9, 11] while odd == []: item = odd.pop() print(item)
# class AboutSets(unittest.TestCase): def test_set_have_arithmetic_operators(self): beatles = {'John', 'Ringo', 'George', 'Paul'} dead_musicians = {'John', 'George', 'Elvis', 'Tupac', 'Bowie'} great_musicians = beatles | dead_musicians self.assertEqual(__, great_musicians) living_beatles = beatles - dead_musicians self.assertEqual(__, living_beatles) dead_beatles = beatles & dead_musicians self.assertEqual(__, dead_beatles)
# Indeed, translation can be created with a dictionary. In this first step we create the dictionary and retrieve an item. Can you finish the code? calculations_to_letters = __ #<-- create the dictionary here one_in_letters = __ #<-- loop up '1' here print(one_in_letters) plus_in_letters = __ #<-- loop up '+' here print(plus_in_letters)
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 wmsj100 <wmsj100@hotmail.com> # # Distributed under terms of the MIT license. """ """ def power1(m,n): result = 1 for i in range(n): result *= m return result def power2(m,n): if n == 0: return 1 else: return m * power2(m,n-1) print(power1(3,3)) print(power2(3,3))
def cal(p1, p2, *nums): print nums sum = p1**2 + p2**2 for num in nums: sum += num**2 return sum print cal(1,2, 4,5) def cal1(p1,p2,**args): print args cal1(1,2,name='wmsj',age=12)
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 ubuntu <ubuntu@VM-0-13-ubuntu> # # Distributed under terms of the MIT license. """ """ class People: def __init__(self, name): self.name = name def say(self): print("I am people {}".format(self.name)) class Animal: def __init__(self, food): self.food = food def eat(self): print("I eat food {}".format(self.food)) class Anys(People, Animal): def __init__(self, name, food): super().__init__(name) Animal.__init__(self, food)
#import statements and variables import random suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} playing = True #Classes definition class Card(): def __init__(self,suit,rank): self.suit = suit self.rank = rank def __str__(self): return self.rank + 'of ' + self.suit class Deck: def __init__(self): self.deck = [] # start with the same empty list every time for suit in suits: for rank in ranks: self.deck.append(Card(suit,rank)) def __str__(self): deck_comp = '' # start with an empty string for card in self.deck: deck_comp += '\n '+card.__str__() # print each Card object return 'The deck has:' + deck_comp def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card class Hand: def __init__(self): self.cards = [] self.value = 0 self.aces = 0 def add_card(self,card): #passed card from Deck.deal() self.cards.append(card) self.value += values[card.rank] #keep number of aces if card.rank == 'Ace': self.aces += 1 def adjust_for_ace(self): #If we score over 21, change ace from 21 to 1 while self.value > 21 and self.aces > 0: self.value -= 10 self.aces -= 1 class Chips: def __init__(self): self.total = 1000 self.bet = 0 def win_bet(self): self.total += self.bet def lose_bet(self): self.total -= self.bet #Functions definitions def take_bet(chips): while True: try: chips.bet = int(input('How many chips will you bet?')) except: print('Please provide an integer') else: if chips.bet > chips.total: print('Sorry, not enough chips.') else: break def hit(deck,hand): hand.add_card(deck.deal()) hand.adjust_for_ace() def hit_or_stand(deck,hand): global playing while True: x = input('Hit or Stand? Press h or s') if x[0].lower() == 'h': hit(deck,hand) elif x[0].lower() == 's': print("Player stops, dealer's turn") playing = False else: print('Wrong input, press h or s') continue break def show_some(player,dealer): print ('Dealers hand:') print('One card is hidden.') print(dealer.cards[1]) print('\n') print('Players hand:') for card in player.cards: print(card) def show_all(player,dealer): print ('Dealers hand:') for card in dealer.cards: print(card) print('\n') print('Players hand:') for cards in player.cards: print(card) def player_busts(player,dealer,chips): print('Player busted!') chips.lose_bet() def player_wins(player,dealer,chips): print('Player wins!') chips.win_bet() def dealer_busts(player,dealer,chips): print('Dealer busted.Player wins!') chips.win_bet() def dealer_wins(player,dealer,chips): print('Dealer wins!') chips.lose_bet() def push(player,dealer): print("It's a tie!") #Gameplay while True: print('Welcome to Blackjack!') deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) #player chips player_chips = Chips() #ask for bet take_bet(player_chips) #show cards(one hidden for dealer) show_some(player_hand,dealer_hand) while playing: #ask for hit or stand hit_or_stand(deck,player_hand) show_some(player_hand,dealer_hand) if player_hand.value > 21: player_busts(player_hand,dealer_hand,player_chips) break #Dealers turn, if player has not busted if player_hand.value <=21: #if dealer less that 17, hit while dealer_hand.value < 17: hit(deck,dealer_hand) show_all(player_hand,dealer_hand) #Check winning conditions if dealer_hand.value > 21: dealer_busts(player_hand,dealer_hand,player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_hand,dealer_hand,player_chips) elif dealer_hand.value < player_hand.value: player_wins(player_hand,dealer_hand,player_chips) else: push(player_hand,dealer_hand) print("\n Players chips are ",player_chips.total) #Ask for new game new_game = input("Would you like a new game?y/n") if new_game[0].lower() == 'y': playing = True continue else: print('Thank you for playing.') break
class Stack: def __init__(self): self.size = 0 self.list = [] def isEmpty(self): return self.size == 0 def push(self, data): self.list.append(data) self.size+=1 def pop(self): self.list.pop() self.size-=1 def peek(self): return self.list[len(self.list)-1] stck = Stack() stck.push(10) stck.push(35) stck.push(100) stck.pop() print stck.size print stck.list print stck.peek() print stck.isEmpty()
''' 1.) swapping two variables 2.) Fibonacci Sequence ''' a = 5 b = 10 print(a,b) temp = 0 #temporary variabale is created temp = a #temporary variable is used to save value of a a = b #value of b is given to a b = temp #b recieves previous value of a via temp print(a,b) print() #WHILE LOOPS x = 1 while x < 10: print(x,end='') x = x + 1 print() x = 1 y = 1 z = 1 cont = 1#cont = 'c' n = int(input("Enter how many numbers you'd like")) while cont <= n - 1: print(x + y) z = x x = y y = y + z cont = cont + 1 print("Fibonacci number is ",x + y)
''' Operations with Lists Keyewords : addition(conactenate), slices, deleting(removing) elements Gerardo Riverra 12-6-18 ''' from gerardolib import fibon_sequence alist = ["a", "b", "c", "d", "e"] blist = ["v", "w" ,"x", "y", "z"] # Concatenation print(alist + blist) print(alist) # slicing lists print("\nSLICING LISTS\n") print(alist[1:3]) print(alist[1:1]) print(alist[0:]) #Squeezing lists print("\nSQUEEZING LISTS\n") alist[3:3] = blist[0:] print(alist) alist = ["a", "b", "c", "d", "e"] #Erase print("\nERASE\n") alist[3:7] = [] print(alist) alist = ["a", "b", "c", "d", "e"] #deleting elements with del list[index] print("\nDELETING ELEMENTS\n") del alist[0] print(alist) alist = ["a", "b", "c", "d", "e"] fibon_sequence(5)
#!/usr/bin/env python3 """ --- Day 6: Memory Reallocation --- """ memory_banks = '4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5'.split('\t') debug_input = [0, 2, 7, 0] """ Execution of a weirdly-changing program counter """ def string(lst): """ Not ''.join, because then [12,3] == [1,2,3] collision happens.""" return '_'.join(str(x) for x in lst) def compute(): """ main algorithm to do stuff """ banks = [int(x) for x in memory_banks] configurations = {string(banks): 0} num_configs = 1 while len(configurations) == num_configs: cell_index = banks.index(max(banks)) values = banks[cell_index] banks[cell_index] = 0 while values != 0: cell_index = (cell_index + 1) % len(banks) values -= 1 banks[cell_index] += 1 num_configs += 1 if string(banks) not in configurations: configurations[string(banks)] = num_configs - 1 cycle_length = num_configs - configurations[string(banks)] - 1 return num_configs, cycle_length def main(): num_configs, cycle_length = compute() print("A repeating configuration after %s iterations." % str(num_configs-1)) print("Cycle has length of %s." % cycle_length) return if __name__ == '__main__': main()
#!/usr/bin/env python3 """ --- Day 1: Inverse Captcha --- """ input_file = 'input_day1.txt' def get_input(): with open(input_file, 'r') as f: return f.read().strip() def compute_half_circular(input_code, step): result = 0 size = len(input_code) # step = size / 2 for i, ch in enumerate(input_code): nexti = (i + step) % size if input_code[i] == input_code[nexti]: result += int(ch) return result def main(): input_code = get_input() # part 1 result = compute_half_circular(input_code, 1) print("Captcha 1: {}".format(result)) # part 2 result2 = compute_half_circular(input_code, len(input_code) // 2) print("Captcha 2: {}".format(result2)) if __name__ == '__main__': main()
#!/usr/bin/env python3 """ --- Day 5: A Maze of Twisty Trampolines, All Alike --- """ input_file = 'input_day5.txt' def get_input(): # test input: # return [0, 3, 0, 1, -3] with open(input_file, 'r') as f: return f.readlines() def out_of_range(index, size): return index < 0 or index >= size def compute(part=1): """ go through, instruction by instruction. """ instrs = [int(x) for x in get_input()] pc = 0 counter = 0 while not out_of_range(pc, len(instrs)): # execute: old_pc = pc pc += instrs[pc] if part == 1: instrs[old_pc] += 1 else: instrs[old_pc] += 1 if instrs[old_pc] < 3 else -1 counter += 1 # increment old value return counter def main(): result = compute(part=1) print("Part 1: {}".format(result)) result2 = compute(part=2) print("Part 2: {}".format(result2)) return if __name__ == '__main__': main()
def main(): #主函数定义在前,增加可读性 message()#程序解释 dic = build_dic()#创建字典 active = 1 #程序运行状态选项 while active != 0: bar() user_in = input("1,查询,2,增加,3,删除,0,退出:") if is_number(user_in) == True : #判断输入的是不是一个数字 user_inf = float(user_in) active = int(user_inf) if float(active) != user_inf or len(user_in) != 1 : #判断输入的是不是浮点数或者多位数 print("请输入正确的选项:") else: if active > 3 or active < 0 : print("请输入正确的选项:") if active == 1: search_dic(dic) #查找字典 if active == 2: dic = change_dic(dic) #更改字典 if active == 3: dic = delete_dic(dic) #删除字典 if active == 0: save_dic(dic) #保存字典 else : print("请输入正确的选项:") def message(): #程序功能解释 print("==========================================================") print("= 这是我编写的第一个python程序!程序的基本功能: =") print("= 创建一个查询英文单词的字典,并且可以随时添加或删除条目. =") print("= 这可以用来保存英文文献中的单词并且随时查询,不错的主意! =") print("==========================================================") def bar(): #这是一条分割线 print("--------------------------------------------------") def is_number(s): #判断输入的是不是一个数 try: # 如果能运行float(s)语句,返回True(字符串s是浮点数) float(s) return True except ValueError: # ValueError为Python的一种标准异常,表示"传入无效的参数" pass # 如果引发了ValueError这种异常,不做任何事情(pass:不做任何事情,一般用做占位语句) try: import unicodedata # 处理ASCii码的包 unicodedata.numeric(s) # 把一个表示数字的字符串转换为浮点数返回的函数 return True except (TypeError, ValueError): pass return False def build_dic(): #创建或者读取词典文件来获取词典 try: fp = open("dictionaries.txt",'r') print("找到已有文件,读取已有词典:") dic = {} for line in fp: v = line.strip().split(':') dic[v[0]] = v[1] fp.close() except FileNotFoundError: fp = open("dictionaries.txt",'w') print("未找到已有的词典文件,新建词典:") dic = {} fp.close return dic def search_dic(dic): #查找字典中的单词 key = input("请输入需要查询的单词:").rstrip() if key in dic.keys(): print("已找到单词:"+ str(key) +","+str(dic[key])) else: print("未找到单词!") def change_dic(dic): #更新字典 key = "a" value = "a" print("进入增加单词模式,按q退出:") while key != "q" and value != "q" : key = input("请输入单词:").rstrip() if key != "q" and value != "q" : value = input("请输入词义:").rstrip() dic[key] = value print("已更新单词:"+ str(key) +","+str(dic[key])) return dic def delete_dic(dic): #删除单词 key = input("请输入需要删除的单词:").rstrip() if key in dic.keys(): print("已删除单词:"+ str(key) +","+str(dic[key])) del dic[key] else: print("未找到单词!") return dic def save_dic(dic): #保存词典到文件 fp = open("dictionaries.txt",'w') number = len(dic) num = int(1) bar() print("一共有"+str(number)+"个单词,如下所示:\n\n") for key,value in dic.items(): words = key + ":" + value + "\n" word = str(num) + ": " + key + ":" + value print(str(word)) fp.write(str(words)) num += 1 fp.close() print("\n") bar() def main_pause(): main_pause = input( ) main() main_pause()
import math class Location: def __init__(self, x, y): self.x = x self.y = y self.xi = int(math.floor(x)) self.yi = int(math.floor(y)) def distance_euclidean(l1, l2): x2 = math.pow(l1.x - l2.x,2) y2 = math.pow(l1.y - l2.y,2) return math.sqrt(x2 + y2) def distance_manhatan(l1, l2): x_abs = abs(l1.xi - l2.xi) y_abs = abs(l1.yi - l2.yi) return x_abs + y_abs def interection_point(l1, l2): if(distance_manhatan(l1,l2) == 0): return distance_euclidean(l1,l2) x0 = 0; y0 = 0; if(l1.yi == l2.yi): x0 = max(l1.xi, l2.xi) y0 = l1.y + (l2.y - l1.y) * (x0 - l1.x) / (l2.x - l1.x) else: y0 = max(l1.yi, l2.yi) x0 = l1.x + (l2.x - l1.x) * (y0 - l1.y) / (l2.y - l1.y) return (x0, y0) # l1 = Location(1.25, 1.25) # l2 = Location(2.25, 1.75) l1 = Location(0, 0) l2 = Location(50, 50) de = distance_euclidean(l1, l2) dm = distance_manhatan(l1, l2) print("de: " + str(de)) print("dm: " + str(dm)) ip = interection_point(l1, l2) print("ip: " + str(ip))
#Gets the data from the Olympics.txt file and puts them into two lists, #one for the year of the Olmypics and one for the place the games took place. #Return : yearList, placeList def getData(): olympData = open("Olympics.txt", 'r') yearList = [] placeList = [] curLine = olympData.readline() while curLine != "": curLine = curLine.strip() year, loc = curLine.split("\t") yearList.append(year) placeList.append(loc) curLine = olympData.readline() return yearList, placeList #This uses Binary Searching to locate the location of a specific Olympic Games. def findLoc(yearList, locList, year): guess = 0 length = len(yearList) counter = 0 #This loop will keep running until counter equals the guess then it throws # an error string while True: if guess == length: return "nowhere because that was not a valid year", counter mid = (guess + length) // 2 midYear = int(yearList[mid]) if midYear == year: return locList[mid], counter if midYear < year: guess = mid + 1 else: length = mid counter += 1 #Main method. Asks user for a year and returns a string with the place. # Also tells the user how many times the search loop was exceuted. def main(): yearList, placeList = getData() year = int(input("Enter a year that the summer olympics were held: ")) loc, count = findLoc(yearList, placeList, year) print("In the year,", year, "the olympics were in " , loc, ".") print("That loop was executed", count, "times.")
if __name__ == '__main__': # Create an array for the counters and initialize each element to 0. from array import Array theCounters = Array(127) # Open the text file for reading and extract each line from the file # and iterate over each character in the line. theFile = open("C:/temp/atextfile.txt", 'r') for line in theFile: for letter in line: code = ord(letter) theCounters[code] += 1 # Close the file theFile.close() # Print the results. The uppercase letters have ASCII values in the # range 65..90 and the lowercase letters are in the range 97..122. for i in range(26): print("%c - %4d %c - %4d" % (chr(65 + i), theCounters[65 + i], chr(97 + i), theCounters[97 + i]))
# written by Christopher Shanor # cshanor@zoho.com from tkinter import * window = Tk() def convert(): grams = float(e1_value.get()) * 1000 lbs = float(e1_value.get()) * 2.205 oz = float(e1_value.get()) * 35.274 t1.insert(END, grams) t2.insert(END, lbs) t3.insert(END, oz) l1 = Label(window, text="Kg --->") l1.grid(row=0, column=0) b1 = Button(window, text="Convert", command = convert) b1.grid(row = 0, column = 2) e1_value = StringVar() e1 = Entry(window, textvariable=e1_value) e1.grid(row = 0, column = 1) t1 = Text(window, height=1, width=20) t1.grid(row=1, column=0) t2 = Text(window, height=1, width=20) t2.grid(row=1, column=1) t3 = Text(window, height=1, width=20) t3.grid(row=1, column=2) window.mainloop()
#Creating and instantiating python classes #classes - they allow us to logically group data(attributes) and functions (methods) '''class Employee: pass print ("Class (Blueprint) vs Instance") emp1 = Employee() emp2 = Employee() print (emp1) print (emp2) print ("instance variables contains data unique to each instance") emp1.first ='Manoj' emp1.last = 'Putchala' emp1.email = 'manojkumar@gmail.com' emp1.pay = 5000 emp2.first ='Lalitha' emp2.last = 'Putchala' emp2.email = 'Lalithakumar@gmail.com' emp2.pay = 6000 print (emp1.email) print (emp2.email) ''' class Employee: #Constructor or Initializer #Instance is called as self(by default should be used) #Name, email and pay are attributes def __init__(self,first,last, pay): self.fname = first self.lname = last self.epay = pay self.email = first+'.'+last+'@company.com' def fullname(self): #method for code reuse #self should not be forgotten (one common mistake) return '{} {}'.format(emp1.fname,self.lname) emp1 = Employee('Manoj','Kumar',100000) print (emp1.epay) print (emp1.fullname()) print (Employee.fullname(emp1)) # another way of calling the instance using class
# Para obtener ciertas estadísticas de un recorrido, se pide realizar un # y en metros por segundo. programa que dada una distancia, entregue la # velocidad en kilómetros por hora. Para esto, existen dos variables tiempo # y distancia que vienen en segundos y kilómetros respectivamente. Tu programa # debe guardar en la variable resultado un string, por ejemplo, # para el siguiente caso: # tiempo = 1 # # distancia = 0.01 # La variable resultado debería tener lo siguiente: # "La velocidad es 36.0 km/h o 10.0 m/s" # # Para poder resolver este problema , debes escribir el código que falta en el # espacio que lo señala. Asume que ya existen variables con los nombres tiempo # y distancia, que ya contienen. los valores requeridos (no debes pedírselos # al usuario), haz los cálculos que necesites, y luego deja el resultado en una # variable llamada resultado. def velocidad(distancia, tiempo): # desde aquí hacia abajo debes modificar el programa # modifica la variable resultado # recuerda que los datos están en las variables distancia y tiempo return resultado # Prueba de ejecución distancia_prueba = 0.01 tiempo_prueba = 1 resultado = velocidad(distancia_prueba, tiempo_prueba) print(resultado)
import cv2 import matplotlib.pyplot as plt import MaxPool import ConvOp import Activations import sys # Using sys.stdout to print the output of this script to a text file sys.stdout = open("CNN_from_Scratch_output.text", "w") # Reading a sample image to test our implementation of Convolutional Neural Network sample_image = cv2.imread("WhatsApp_Image_2021-09-04_at_21.59.00_225x225.jpeg", cv2.IMREAD_GRAYSCALE)/255 plt.imshow(X = sample_image, cmap = "gray") plt.show() print("Sample Image Shape :", sample_image.shape) # Applying our Convolutional layer to our sample image cnn = ConvOp.ConvOp(num_filters = 18, filter_size = 7) out = cnn.forward_prop(image = sample_image) print("Sample Image Shape after applying a Convolutional layer :", out.shape) plt.imshow(out[:, :, 17], cmap = "gray") plt.title("Plotting the 17th image of size (219, 219)") plt.show() # Applying our MaxPool layer to the output of our Convolutional layer cnn2 = MaxPool.Max_Pool(filter_size = 4) out2 = cnn2.forward_prop(image = out) print("Sample Image Shape after applying a MaxPool layer :", out2.shape) plt.title("Plotting the 17th image of size (54, 54)") plt.imshow(out2[:, :, 17], cmap = "gray") plt.show() # Applying our Softmax layer to the output of MaxPool layer cnn3 = Activations.Softmax(input_node = 54*54*18, softmax_node = 10) out3 = cnn3.forward_prop(image = out2) print("Softmax prediction outputs :", out3) sys.stdout.close()
# Lukas Schwab, 6/15/14 # github.com/lukasschwab # lukas.schwab@gmail.com #-----------------------# # Defines a color as a weighted average between two, input as a percentage. #-----------------------# # Prompt the two color inputs clr0=raw_input('Enter the hex value for the 0 percent color. ') clr100=raw_input('Enter the hex value for the 100 percent color. ') # Split into a list of the component 2-digit numbers clrlist0=[clr0[i:i+2] for i in range(0, len(clr0), 2)] clrlist100=[clr100[i:i+2] for i in range(0, len(clr100), 2)] # Start off the while-loop at x=0 so it isn't triggered loopit=0 # Open the loop. Will continue indefinitely until an unacceptable value is input. while loopit < 1: # Input the percentage you're looking for pct=raw_input('Enter the percentage, without a percent sign, or quit. ') if pct=='quit': import sys print "Ending Script" sys.exit() pct = int(pct) pct=float(100-pct) pct=pct/100 # Final color to 0 clrf="" # Loop for every index in each of the lists for x in range(0,3): # Convert the value in both of those spots to a decimal dec0=int(clrlist0[x],16) dec100=int(clrlist100[x],16) # Find the modified color by taking a weighted average modded=int(dec100*pct)+int(dec0*(1-pct)) # Convert back to hex. modded=hex(modded)[2:] # Make sure it's two digits if len(modded) < 2: modded2="0" modded2+=str(modded) modded=modded2 # Concatonate to the string. clrf+=str(modded) print '#' + clrf