text
stringlengths
37
1.41M
import crypt import argparse def crack_pass(ctext, pw_dict): salt = ctext[0:2] with open(pw_dict, 'r') as pw_dict: for word in pw_dict.readlines(): word = word.strip() crypt_word = crypt.crypt(word, salt) if crypt_word == ctext: return word return None def analyze_file(filename, pw_dict): with open(filename, 'r') as f: for line in f.readlines(): (user, pword) = tuple([x.strip() for x in line.split(':')[0:2]]) plaintext = crack_pass(pword, pw_dict) if plaintext: print('User: {}\tPassword: {}'.format(user, plaintext)) else: print('User: {}\tNo Password Found'.format(user)) def main(): parser = argparse.ArgumentParser() parser.add_argument('filename') parser.add_argument('--dict', default='dictionary.txt') args = parser.parse_args() analyze_file(args.filename, args.dict) if __name__ == '__main__': main()
def main(): count = 1 answer = 0 while count < 1000: if count % 3 == 0: answer += count if count % 5 == 0 and count % 3 != 0: answer += count count += 1 print(answer) main()
""" These are the basic image-stack processing commands. They aren't really filters as they don't change the data in the image slices but instead work on changing which slices we are using. They generally create ImageStackCollection image stacks. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from itertools import chain, izip_longest, islice from ..general import itr2str from ._stack import ImageStack, ImageSlice, ImageStackArray, ImageStackCollection, Homogeneous from ..imstack import Command, Help, Opt class ZCommand(Command): @classmethod def name(cls): return 'z' @classmethod def flags(cls): return ('z',) @classmethod def print_help(cls, width): p = Help(width) p.title("Select Image Slices") p.text("""Select, reorder, and duplicate Z slices from a stack.""") p.newline() p.flags(cls.flags()) p.newline() p.stack_changes(consumes=("Image stack to reorganize",), produces=("Reorganized image stack",)) p.newline() p.text("Command format:") p.cmds("-z image-slice-numbers-or-slices ...") p.newline() p.text(""" The command is simply followed by a series of numbers or slices. These are the image slices that you wish to keep and their order. If the integers are negative then they are relative to the last image slice. Instead of integers you can also use slices, which are specified as [first][:step]:[last] which will expand into all integers from first to last (inclusive of first and last) that increment by step. Each part is optional, with step defaulting to one, and first and last defaulting to the ends of the stack - for whatever makes sense for the step. If a particular slice is specified twice, it will be duplicated. Examples:""") p.list("-z 0 1 2 # keep first three image slices", "-z 0:2 # same as above", "-z 0 0 # have a copy of the top image slices and nothing else", "-z -1 # keep last image slice only", "-z :-1: # reverse the order of the image stack (same as --flip z)", "-z :2: # keep all every other slice", "-z :2: 1:2: # interleave even and odd slices") p.newline() p.text("See also:") p.list('flip', 'split', 'combine') @staticmethod def __fmt(idx): if isinstance(idx, int): return idx start, stop, step = idx.start, idx.stop, idx.step return (('' if start is None else str(start)) + ('' if step==1 else ':'+str(step)) + ':' + ('' if stop is None else str(stop))) def __str__(self): return "selecting slices "+itr2str((ZCommand.__fmt(i) for i in self.__inds),", ") def __init__(self, args, stack): if len(args.positional) == 0: raise ValueError("No image slices selected") if len(args.named) != 0: raise ValueError("No named options are accepted") stack.pop() stack.push() self.__inds = [] try: for arg in args.positional: arg = arg.strip() if ':' in arg: # slice: different order from how Python normally operates parts = [int(i) if len(i) > 0 else None for i in arg.split(':', 2)] start, stop, step = parts[0], parts[-1], ((parts[1] if len(parts) == 2 else None) or 1) self.__inds.append(slice(start, stop, step)) # not a real slice since stop is inclusive else: self.__inds.append(int(arg)) except ValueError: raise ValueError("Only integers and slices ([first][:step]:[last]) are allowed") def execute(self, stack): ims = stack.pop() last_ind = len(ims)-1 inds = [] #all_neg = True for i in self.__inds: if isinstance(i, slice): # slice: stop is inclusive (not normally in Python) start, stop, step = i.start, i.stop, i.step if step > 0: start = 0 if start is None else ((last_ind+start) if start < 0 else start) stop = (last_ind if stop is None else ((last_ind+stop) if stop < 0 else stop))+1 #all_neg = False else: # step < 0 start = last_ind if start is None else ((last_ind+start) if start < 0 else start) stop = (0 if stop is None else ((last_ind+stop) if stop < 0 else stop))-1 inds.extend(xrange(start, stop, step)) else: inds.append((i+last_ind) if i < 0 else i) #all_neg = False out = ImageStackCollection(ims[inds]) #pylint: disable=protected-access out._ims = ims # make sure we save a reference to the image stack so it doesn't get cleaned up stack.push(out) class SplitCommand(Command): @classmethod def name(cls): return 'split' @classmethod def flags(cls): return ('split',) @classmethod def print_help(cls, width): p = Help(width) p.title("Split Image Stack") p.text("""Split a stack into two stacks.""") p.newline() p.flags(cls.flags()) p.newline() p.stack_changes(consumes=("Image stack to split",), produces=("Selected image slices","Complementary image stack")) p.newline() p.text("Command format:") p.cmds("--split [first][:step]:[last]") p.newline() p.text(""" The command is followed by a 'slice'. This desribes the image slices to put into one of the stacks. The other stack is formed from the complement of that stack. The 'slice' describes all slices to use, including first and last that are multiples of step from first. Each part is option, with step defaulting to 1, and first and last defaulting to the ends of the stack - for whatever makes sense for the step. At least one of the parts must be given a non-default value. Additionally the variable n can be used in as a substitute for the number of image slices in the source stack and used with simple math. Examples:""") p.list("--split :2: # split into stacks with all even slices and with all odd slices", "--split :n/2 # split into into first half and second") p.newline() p.text("See also:") p.list('z', 'combine') def __str__(self): return "spliting stack into %s and the inverse"%self.__raw @staticmethod def __safe_eval(x, n): # At this point we have also already sanitized and made sure there are only digits, operators, and n return eval(x, globals={'__builtins__':{}}, locals={'n':n}) #pylint: disable=eval-used @staticmethod def __cast(x): if 'n' not in x: return int(x) if any((c not in '0123456789*/+-()n') for c in x): raise ValueError try: SplitCommand.__safe_eval(x, 1) except: raise ValueError() return x def __init__(self, args, stack): if len(args.positional) != 1: raise ValueError("Exaclty one option required") if len(args.named) != 0: raise ValueError("No named options are accepted") stack.pop() stack.push() stack.push() try: self.__raw = arg = args[0].strip() if ':' not in arg: raise ValueError # slice: different order from how Python normally operates and can have 'n' parts = [SplitCommand.__cast(i) if len(i) > 0 else None for i in arg.split(':', 2)] self.__start, self.__stop, self.__step = parts[0], parts[-1], ((parts[1] if len(parts) == 2 else None) or 1) except ValueError: raise ValueError("Option must be a single slice ([first][:step]:[last]) with at least one non-default value set") def execute(self, stack): ims = stack.pop() last_ind = len(ims)-1 inds = [] # slice: stop is inclusive (not normally in Python) and can include 'n' start, stop, step = (SplitCommand.__safe_eval(self.__start, last_ind), SplitCommand.__safe_eval(self.__stop, last_ind), SplitCommand.__safe_eval(self.__step, last_ind)) forward = step > 0 if forward: start = 0 if start is None else ((last_ind+start) if start < 0 else start) stop = (last_ind if stop is None else ((last_ind+stop) if stop < 0 else stop))+1 else: # step < 0 start = last_ind if start is None else ((last_ind+start) if start < 0 else start) stop = (0 if stop is None else ((last_ind+stop) if stop < 0 else stop))-1 inds.extend(xrange(start, stop, step)) u_inds = frozenset(inds) c_inds = xrange(0, last_ind+1, 1) if forward else xrange(last_ind, -1, -1) c_inds = (i for i in c_inds if i not in u_inds) stack.push(ImageStackCollection(ims[c_inds])) stack.push(ImageStackCollection(ims[inds])) class CombineCommand(Command): @classmethod def name(cls): return 'combine' @classmethod def flags(cls): return ('C', 'combine') @classmethod def _opts(cls): return ( Opt('nstacks', 'The number of stacks to combine', Opt.cast_int(lambda x:x>=2), 2), Opt('interleave', 'If the combined stacks should be interleaved instead of concatenated', Opt.cast_bool(), False), ) @classmethod def print_help(cls, width): p = Help(width) p.title("Combine Image Stacks") p.text(""" Combines two or more image stacks into a single stack. The next image stack is placed on top, followed by the second-to-next, and so forth.""") p.newline() p.flags(cls.flags()) p.newline() p.text(""" Consumes: 2+ image stacks Produces: 1 image stack""") p.newline() p.text("Command format:") p.cmds("-C [nstacks] [interleave]") p.newline() p.text("Options:") p.opts(*cls._opts()) p.newline() p.text("See also:") p.list('z', 'split') def __str__(self): return ("interleaving" if self.__interleave else "combining")+(" %d image stacks"%self.__nstacks) def __init__(self, args, stack): self.__nstacks, self.__interleave = args.get_all(*CombineCommand._opts()) for _ in xrange(self.__nstacks): stack.pop() stack.push() def execute(self, stack): ims = [stack.pop() for _ in xrange(self.__nstacks)] if self.__interleave: itr = (x for x in chain.from_iterable(izip_longest(*ims)) if x is not None) else: itr = chain(*ims) stack.push(ImageStackCollection(itr)) class MemCacheCommand(Command): @classmethod def name(cls): return 'memcache' @classmethod def flags(cls): return ('M', 'memcache') @classmethod def _opts(cls): from tempfile import gettempdir return ( Opt('memmap', 'Use a memory-mapped physical backing store for the cache', Opt.cast_bool(), False), Opt('tmp', 'Temporary directory to put memory-mapped files in', Opt.cast_writable_dir(), gettempdir()), ) @classmethod def print_help(cls, width): p = Help(width) p.title("Memory Cache") p.text(""" This commands reads all available image stacks (causing them read from disk, compute, etc) into cached image stacks so that they are never re-read or re-computed if they are used in multiple places (which may not be explicit, for example a crop command may double-read data by requesting it once to compute the padding and once to actually crop). This command can greatly speed up future commands at the cost of using more memory. If you are likely to run out of virtual memory using these caches, you can provide the memmap argument to have the caches backed by physical storage via memory-mapped files. They will only be written to disk as the OS deems necessary so it is unlikely to slow things down too much. Note that on Linux the system-default for tmp is frequently on a tmpfs or shmfs filesystem which is simply backed by swap, so specifying that will not help reduce swap load. After things are cached, the garbage collector is run and all previous image stacks should be removed from memory, causing release of memory. This means when using multiple memory cache commands only the last two need to fit in memory (along with the intermediate steps). One downside of using memory caches is that the some features of the original image stacks will be lost, such as headers for image stacks on disk. The features lost are mainly useful for debugging with the info command, which can be placed immediately before this command if needed.""") p.newline() p.flags(cls.flags()) p.newline() p.text("Command format:") p.cmds("-M [memmap] [tmp]") p.newline() p.text("Options:") p.opts(*cls._opts()) def __str__(self): return "memory-mapped caching" if self.__memmap else "memory caching" def __init__(self, args, _): self.__memmap, self.__tmpdir = args.get_all(*MemCacheCommand._opts()) def execute(self, stack): import gc imss = [stack.pop() for _ in xrange(len(stack))] # pop all image stacks imss.reverse() # make sure that they will stay the same order if self.__memmap: for ims in imss: stack.push(MemMapCacheImageStack(ims, tmpdir=self.__tmpdir)) else: from numpy import empty for ims in imss: info = [(im.shape, im.dtype) for im in ims] if all(i == info[0] for i in islice(info, 1, None)): # Homogeneous - single 3D array sh, dt = info[0] stk = empty((ims.d,) + sh, dtype=dt) for z, slc in enumerate(ims): stk[z,:,:,...] = slc.data stack.push(ImageStackArray(stk)) else: # Heterogeneous - one array per slice stack.push(ImageStackCollection(slc.data for slc in ims)) gc.collect() # TODO: run some tests to make sure we aren't leaking objects (unreachable cycle with __del__) class MemMapCacheImageStack(ImageStack): __file = None def __init__(self, ims, tmpdir=None): from numpy import ndarray, cumsum slices = ims[:] info = [(im.dtype, im.shape) for im in slices] d = len(slices) if d == 0: return homogeneous = all(i == info[0] for i in islice(info, 1, None)) if homogeneous: dt,sh = info[0] self._arr = ndarray((d,)+sh, dt, self.__open((sh[0]*sh[1]*dt.itemsize)*d, tmpdir)) for z, slc in enumerate(slices): self._arr[z,:,:,...] = slc.data self._arr.flags.writeable = False super(MemMapCacheImageStack, self).__init__( [MemMapImageSlice(self,z,im,dt,sh) for z,im in enumerate(self._arr)]) self._h, self._w = sh self._shape = sh self._dtype = dt self._homogeneous = Homogeneous.All else: nbytes = [sh[0]*sh[1]*dt.itemsize for dt,sh in info] nbytes_aligned = [(x - x % -4) for x in nbytes] offsets = [0] + cumsum(nbytes_aligned).tolist() mm = self.__open(offsets.pop(), tmpdir) ims = [ndarray(sh, dt, mm, off) for (dt,sh),off in zip(info,offsets)] for im,slc in zip(ims, slices): im[:,:,...] = slc.data im.flags.writeable = False super(MemMapCacheImageStack, self).__init__( [MemMapImageSlice(self,z,im,dt,sh) for (z,im),(dt,sh) in zip(enumerate(ims),info)]) def __open(self, size, tmpdir): from os import name from tempfile import TemporaryFile from mmap import mmap, ACCESS_WRITE self.__file = TemporaryFile('wb', 0, dir=tmpdir) if name == 'nt': return mmap(self.__file.fileno(), size, access=ACCESS_WRITE) self.__file.truncate(size) return mmap(self.__file.fileno(), size, access=ACCESS_WRITE) @ImageStack.cache_size.setter #pylint: disable=no-member def cache_size(self, value): pass # prevent built-in caching - this is a cache! #pylint: disable=arguments-differ def close(self): self.__file.close() self.__file = None def __delete__(self, instance): self.close() @property def stack(self): return self._arr # only if homogeneous class MemMapImageSlice(ImageSlice): def __init__(self, stack, z, im, dt, sh): super(MemMapImageSlice, self).__init__(stack, z) self._set_props(dt, sh) self._im = im def _get_props(self): pass def _get_data(self): return self._im
# -*-coding:utf-8-*- # Link: https://leetcode.com/problems/insert-interval/ # Problem Description: # Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). # You may assume that the intervals were initially sorted according to their start times. # Example: # Input: intervals = [[1,3],[6,9]], newInterval = [2,5] # Output: [[1,5],[6,9]] # Example: # Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] # Output: [[1,2],[3,10],[12,16]] # Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. # 思路:本题已经进行了排序,只需要把新区间也加进来,然后综合排序,即可像上一道题一样处理 # Definition for an interval. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ intervals = intervals + [newInterval] intervals = sorted(intervals, key=lambda x: x[0]) res = [intervals[0]] for n in intervals[1:]: # 有重叠 if res[-1][1] >= n[0]: res[-1][1] = max(res[-1][1], n[1]) else: # 无重叠 res.append(n) return res if __name__ == '__main__': # Input: intervals = [[1,3],[6,9]], newInterval = [2,5] # Output: [[1,5],[6,9]] print(Solution().insert([[1, 3], [6, 9]], [2, 5])) # Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] # Output: [[1,2],[3,10],[12,16]] print(Solution().insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))
# -*-coding:utf-8-*- # Link: https://leetcode.com/problems/jump-game/ # Problem Description: # Given an array of non-negative integers, you are initially positioned at the first index of the array. # Each element in the array represents your maximum jump length at that position. # Determine if you are able to reach the last index. # Example: # [2,3,1,1,4] # Result: # true # Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. # Example: # [3,2,1,0,4] # Result: # false # Explanation: You will always arrive at index 3 no matter what. # Its maximum jump length is 0, which makes it impossible to reach the last index. # 思路:用一个能量值来记录可以跳过的最远距离,这个距离应该是当前位置与该位置的能量之和,与nums的长度比 class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ jumpPower = 0 # 用于记录当前最大跳跃值 for i in range(len(nums)): if i > jumpPower: break # 证明当前的位置已经跳不过去了,不用考虑了 jumpPower = max(i + nums[i], jumpPower) # 更新最大跳跃值 return jumpPower >= len(nums)-1 # 判断最大跳跃值能否跳到最后 if __name__ == '__main__': solution = Solution() # Example: # [2,3,1,1,4] # Result: # true # Example: # [3,2,1,0,4] # Result: # false print(solution.canJump([2, 3, 1, 1, 4])) print(solution.canJump([3, 2, 1, 0, 4]))
# Example based on: # https://towardsdatascience.com/building-a-deep-learning-model-using-keras-1548ca149d37 import numpy as np import pandas as pd import matplotlib.pyplot as plt from keras.models import Sequential from keras.layers import Dense from keras.callbacks import EarlyStopping from helpers import create_fake_dataset # (1) GENERATE OR IMPORT TRAINING DATA inp, out, _ = create_fake_dataset(n_samples=50000, distr='Uniform') # inp, out, _ = create_fake_dataset(n_samples=40000, distr='Gaussian') data_dict = {'x_in': inp[0,:], 'xp_in': inp[1,:], 'x_out': out[0,:], 'xp_out': out[1,:]} df = pd.DataFrame(data_dict) # (2) PREPARE DATA FOR TRAINING # TODO: data normalization necessary? train_X = df.drop(columns=['x_out', 'xp_out']) train_y = df.drop(columns=['x_in', 'xp_in']) # (3) BUILD MODEL: use Sequential model # (sequential is the simplest way to build model in keras: # we add layer by layer) n_nodes_NN = 7 NN_tracker_model = Sequential() # Input layer n_input_nodes = train_X.shape[1] # 2 input nodes for 1D betatron NN_tracker_model.add( Dense(n_nodes_NN, activation='relu', input_shape=(n_input_nodes,), use_bias=True, kernel_initializer='random_uniform')) # Middle layer # NN_tracker_model.add(Dense(n_nodes_NN, activation='relu')) # Output layer n_output_nodes = train_y.shape[1] # 2 output nodes for 1D betatron NN_tracker_model.add(Dense(n_output_nodes)) # (4) COMPILE MODEL # Choose optimiser and loss function NN_tracker_model.compile(optimizer='adam', loss='mean_squared_error') # (5) TRAIN MODEL # Fitting of model in epochs: use EarlyStopping to cancel # training in case model does not improve anymore before # reaching end of max. number of epochs (patience=3 means: # stop if model does not change for 3 epochs in a row) early_stopping_monitor = EarlyStopping(patience=6) training_history = NN_tracker_model.fit( train_X, train_y, validation_split=0.2, epochs=500, callbacks=[early_stopping_monitor]) # (6) MAKE PREDICTIONS WITH THE MODEL # Create new data with same 'machine': try to track with NN # and compare to linear tracking matrix test_inp, test_out, _ = create_fake_dataset(distr='Gaussian', n_samples=200) test_data_dict = { 'x_in': test_inp[0,:], 'xp_in': test_inp[1,:], 'x_track': test_out[0,:], 'xp_track': test_out[1,:]} test_df = pd.DataFrame(test_data_dict) test_X = test_df.drop(columns=['x_track', 'xp_track']) test_y = test_df.drop(columns=['x_in', 'xp_in']) # Predict with trained NN model nn_pred_y = NN_tracker_model.predict(test_X) nn_pred_df = pd.DataFrame( {'x_NN': nn_pred_y[:,0], 'xp_NN': nn_pred_y[:,1]}) # Compare to actual tracking output ax = nn_pred_df.plot(title='NN prediction vs. tracker') test_y.plot(ax=ax, ls='--') ax.set(xlabel='Particle idx.', ylabel='Coord. x') plt.tight_layout() plt.show() # Plot differences diff_df = pd.DataFrame() diff_df['x_diff'] = nn_pred_df['x_NN'] - test_y['x_track'] diff_df['xp_diff'] = nn_pred_df['xp_NN'] - test_y['xp_track'] ax2 = diff_df.plot(title='Differences after 1 turn') ax2.set(xlabel='Particle idx.', ylabel='Coord. diff. (NN - tracking)') plt.tight_layout() plt.show() # TRACK 'SEVERAL' TURNS n_turns = 200 test_inp, test_out, centroid = create_fake_dataset( distr='Gaussian', n_samples=4000, n_turns=n_turns) test_data_dict = { 'x_in': test_inp[0,:], 'xp_in': test_inp[1,:], 'x_track': test_out[0,:], 'xp_track': test_out[1,:]} test_df = pd.DataFrame(test_data_dict) test_X = test_df.drop(columns=['x_track', 'xp_track']) test_y = test_df.drop(columns=['x_in', 'xp_in']) # Predict with trained NN model centroid_pred = np.zeros((n_turns, 2)) nn_pred_y = test_X.copy() for i in range(n_turns): centroid_pred[i,:] = np.mean(nn_pred_y, axis=0) nn_pred_y = NN_tracker_model.predict(nn_pred_y) # Compare turn-by-turn centroid centroid_track_df = pd.DataFrame( data={'xbar_track': centroid[:,0], 'xpbar_track': centroid[:,1]}) centroid_NN_df = pd.DataFrame( data={'xbar_NN': centroid_pred[:,0], 'xpbar_NN': centroid_pred[:,1]}) ax3 = centroid_track_df.plot() centroid_NN_df.plot(ax=ax3, ls='--') ax3.set(xlabel='Turn', ylabel='Centroid (arb. units)') plt.tight_layout() plt.show()
import pyglet from character import * from Map import * GRAVITY = 2 class Player(Character): def __init__(self, x, y, path, BG, win, spdx = 0, spdy = 0): Character.__init__(self, x, y, path, BG) self.mid = (win[0]/2-100, win[1]/2, 100) self.onGround = False self.jumping = False self.moving = False self.state = 'stand' def move(self, dx, dy): if dx == 0 and dy == 0 and self.onGround: if self.ori == 'left' and not self.moving: self.anime = self.sprite.sprite['standL'] elif self.ori == 'right' and not self.moving: self.anime = self.sprite.sprite['standR'] else: if self.XaroundMid() and self.map.XinLim(-dx): self.map.move(-dx, 0) else: self.x += dx self.img.x += dx temp = dy self.onGround, dy = self.groundCheck(dx, dy) if self.jumping: dy = temp if self.YaroundMid() and self.map.YinLim(-dy): self.map.move(0, -dy) else: self.y += dy self.img.y += dy # self.jumping decides whether the player is in the process of # elevation; if so, do not stop when encounter ground; if not, that # means the player have started falling and would stop when he # encounters ground; Also, unless the player is on Ground, he would # always fall (spdy decreaes) whether he is elevating or not( # whether self.jumping is True or not) if not self.jumping: if self.onGround: self.spdy = 0 self.state = 'stand' else: self.spdy -= GRAVITY else: self.spdy -= GRAVITY # if self.onGround and not self.jumping: # self.spdy = 0 # self.state = 'stand1' # else: # self.spdy -= GRAVITY if self.jumping and self.spdy == 0: self.jumping = False if dx != 0: if self.onGround: self.state = 'walk1' else: self.state = 'jump' def groundCheck(self, dx = 0, dy = 0): a = min(self.y, self.y + dy) b = max(self.y, self.y + dy) # because each frame may skip multiple pixels, it is important that we # check all the pixels in between when we check if we have landed for ypos in range(a, b + 1): for ground in self.map.ground: if ground.onGroundY(ypos): if ground.onGroundX(self.x + dx): if self.jumping: return (True, dy) else: return (True, ypos - self.y) return (False, dy) def jump(self, dy): m = pyglet.media.Player() m.queue(pyglet.resource.media('audio/jump.mp3')) m.play() self.jumping = True if self.ori == 'left': self.anime = self.sprite.sprite['jumpL'] else: self.anime = self.sprite.sprite['jumpR'] if self.YaroundMid() and self.map.YinLim(-dy): self.map.move(0, -dy) else: self.y += dy self.img.y += dy # checks if the player is around mid and decide whether to move map or player def XaroundMid(self): midx = self.mid[0] - self.mid[2] <= self.x < self.mid[0] + self.mid[2] return midx def YaroundMid(self): midy = self.mid[1] - self.mid[2] <= self.y < self.mid[1] + self.mid[2] return midy def draw(self): self.img.draw() # check which direction the character is facing and set the sprite images to # the correct images with the right direction def stateToAnime(self): if self.ori == 'left': self.anime = self.sprite.sprite[self.state + 'L'] else: self.anime = self.sprite.sprite[self.state + 'R']
''' Problem 2.6 Determine if a LinkedList is a Palindrome September 4, 2017 Kevin Chen ''' from datastructures import LinkedList import unittest def isLinkedListPalindrome(ll): ''' Add first half as stack, then compare reversed first half with second half. time: o(n) space: o(n) where n is the # of nodes in the list Note: Using slow/fast pointer technique. Always lands at end of left partition. ''' stack = [] slow = fast = ll.head while fast and fast.next: stack.append(slow) slow = slow.next fast = fast.next.next # shift right partition for odd node lists if fast: slow = slow.next while slow: if stack.pop().data != slow.data: return False slow = slow.next return True def isLinkedListPalindromeRecursive(ll): ''' Recursively (recurse halfway (left), then pass down the next node (right) when recursing back through the stack) This is the same as creating a stack in the first half and iterating through the next and popping time: o(n) space: o(n) where n is the # of nodes in the list ''' return recurse(ll.head, lengthOfList(ll), [None]) def recurse(head, length, node): if length == 1: # odd node[0] = head.next return True elif length == 0: # even node[0] = head return True if not recurse(head.next, length - 2, node): return False # propagate Failure if node[0].data != head.data: return False node[0] = node[0].next return True def lengthOfList(ll): count = 0 curr = ll.head while curr: count += 1 curr = curr.next return count class Test(unittest.TestCase): def test_simple_one_palindrome(self): ll = LinkedList.LinkedList() ll.add_node('a') self.assertTrue(isLinkedListPalindrome(ll)) self.assertTrue(isLinkedListPalindromeRecursive(ll)) def test_simple_two_palindrome(self): ll = LinkedList.LinkedList() ll.add_node('a') ll.add_node('a') self.assertTrue(isLinkedListPalindrome(ll)) self.assertTrue(isLinkedListPalindromeRecursive(ll)) def test_simple_three_palindrome(self): ll = LinkedList.LinkedList() ll.add_node('a') ll.add_node('b') ll.add_node('a') self.assertTrue(isLinkedListPalindrome(ll)) self.assertTrue(isLinkedListPalindromeRecursive(ll)) def test_long_palindrome(self): ll = LinkedList.LinkedList() ll.add_node('a') ll.add_node('b') ll.add_node('b') ll.add_node('b') ll.add_node(4) ll.add_node('b') ll.add_node('b') ll.add_node('b') ll.add_node('a') self.assertTrue(isLinkedListPalindrome(ll)) self.assertTrue(isLinkedListPalindromeRecursive(ll)) def test_not_two_palindrome(self): ll = LinkedList.LinkedList() ll.add_node('a') ll.add_node('b') self.assertFalse(isLinkedListPalindrome(ll)) def test_not_palindrome_repetition(self): ll = LinkedList.LinkedList() ll.add_node('a') ll.add_node('b') ll.add_node('a') ll.add_node('b') self.assertFalse(isLinkedListPalindrome(ll)) if __name__ == '__main__': unittest.main()
''' Problem 2.5 Sum two linked lists whose contents represent an integer's digits in reverse order August 27, 2017 Kevin Chen ''' from datastructures import LinkedList import unittest def sumLists(list1, list2): ''' time: o(n) space: o(n) where n is the # of elements in the greater list ''' curr1 = list1.head curr2 = list2.head rem = 0 new_nodes = [] while curr1 or curr2: sum = rem if curr1 is not None: sum += curr1.data curr1 = curr1.next if curr2 is not None: sum += curr2.data curr2 = curr2.next rem = sum / 10 val = sum % 10 new_nodes.append(val) ll = LinkedList.LinkedList() for new_node in reversed(new_nodes): ll.add_node(new_node) return ll def sumListsForward(list1, list2): ''' Recursive solution to forward variant of sum lists problem ''' padListZeroes(list1, list2) ll = LinkedList.LinkedList() sumListsForwardHelper(list1.head, list2.head, ll) return ll def sumListsForwardHelper(curr1, curr2, ll): if not curr1 and not curr2: return 0 # base case, 0 carry carry = sumListsForwardHelper(curr1.next, curr2.next, ll) # starts at bottom of list sum = curr1.data + curr2.data + carry val = sum % 10 new_carry = sum / 10 ll.add_node(val) return new_carry def padListZeroes(list1, list2): diff = getDiff(list1, list2) smaller_list = list2 if diff < 0 else list1 for i in range(abs(diff)): smaller_list.add_node(0) def getDiff(list1, list2): diff = 0 curr1, curr2 = list1.head, list2.head while curr1 or curr2: if curr1: diff += 1 curr1 = curr1.next if curr2: diff -= 1 curr2 = curr2.next return diff class Test(unittest.TestCase): def test_addition(self): list1 = LinkedList.LinkedList() list2 = LinkedList.LinkedList() list1.add_node(3) list1.add_node(2) list1.add_node(1) list2.add_node(3) list2.add_node(2) list2.add_node(1) self.assertTrue(str(sumListsForward(list1, list2)) == 'LinkedList<Node<2>, Node<4>, Node<6>>') if __name__ == '__main__': unittest.main()
''' Problem 3.2 Create a stack that keeps the minimum September 8, 2017 Kevin Chen ''' import unittest import math class StackMin(object): ''' A stack that holds the minimum (retrieved in O(1)). Returns infinity for minimum of empty list. time: o(1) space: o(1) ''' def __init__(self): self.stack = [] def push(self, data): if not self.stack: self.stack.append((data, data)) # first element in stack else: self.stack.append((data, min(self.getMin(), data))) def pop(self): return self.stack.pop()[0] def getMin(self): if self.stack: return self.stack[-1][1] raise IndexError("min from empty list") class Test(unittest.TestCase): def test_min(self): stack = StackMin() stack.push(3) self.assertTrue(stack.getMin() == 3) stack.push(2) self.assertTrue(stack.getMin() == 2) stack.push(4) self.assertTrue(stack.getMin() == 2) stack.push(-1) self.assertTrue(stack.getMin() == -1) stack.pop() self.assertTrue(stack.getMin() == 2) stack.pop() self.assertTrue(stack.getMin() == 2) stack.pop() self.assertTrue(stack.getMin() == 3) if __name__ == '__main__': unittest.main()
class bst: def __init__(self, parent=None, val:int =None, left=None, right=None): self.parent = parent self.val = val self.left = left self.right = right # ouh my god you dingdong # be careful about putting commas after stuff in your constructor # you're thinking JS objects or something bizarre, but you turned your ints to tuples of (3,) def search_tree(root, x): if not root: return None if root.val == x: return root if x < root.val: return search_tree(root.left, x) else: return search_tree(root.right, x) holder = bst() root = bst(None, 10, None, None) lv2_right = bst(root,15,None,None) lv2_left = bst(root,7,None,None) lv3_first_right = bst(lv2_left,8,None,None) root.left = lv2_left root.right = lv2_right lv2_left.right = lv3_first_right print(search_tree(root,8)) # smallest key must live in the left subtree, and biggest must live in the right subtree. # this makes life easier for me. # iterative for this one, so no need to worry about the if none killing your return def find_min(root): if not root: return None curr = root while curr.left: # the reason why we do curr.left here instead of my # frequent curr stuff is because it'd give us None all the time otherwise. # I'd want to do curr.left so that I can get my cutey minimum back once there's no more left to go. curr = curr.left print(curr.val) return curr # Damn, trying to write this from my head I still forked it up, worried about it being # recursive when I knew I was writing an iterative one, and I wrote while curr instead of while curr.left print(find_min(root)) def find_max(root): if not root: return None curr = root while curr.right: curr = curr.right print(curr.val) return curr print(find_max(root)) # tree traversal dear me # I want to traverse all the nodes in this tree. Let us do a recursive t r a v e r s e # I need to write a way to stick an array into a BST format, dude. def traverse_tree(root): if root: traverse_tree(root.left) print(root.val) traverse_tree(root.right) # traverse_tree(root) def traverse_tree_with_depth(root, depth = 0): if root: traverse_tree_with_depth(root.left, depth + 1) print(root.val, depth) traverse_tree_with_depth(root.right, depth + 1) # If I have an array, for example [3,6,2,56,3] is there a simple way to load this array up into a BST? # First I need to sort the array. Doing it with an unsorted array would be a bodonka. # Step one would be to find the middle element of the array, turn that into root # Step two would be then to take the left side of the array and do the same for the left side # Step three then you take the right side of the array and do the same on that side. # Pls go over how to set up merge sort again. test_arr = [3,2,1,4,5,8,7,6] test_arr.sort() print(test_arr) # uhhh I wrote this shitty quick turning into bst code, does it work? def turn_into_bst(arr, parent=None): if len(arr) == 0: return None print(arr) curr = bst() low, high = 0, len(arr)-1 mid = (low + high) // 2 curr.parent = parent curr.val = arr[mid] curr.left = turn_into_bst(arr[0:mid], curr) curr.right = turn_into_bst(arr[mid+1:], curr) return curr giveme = turn_into_bst(test_arr) traverse_tree(giveme) #find_min(giveme) #find_max(giveme) teeny = [1,2,4,5,8,14,34] tryagain = turn_into_bst(teeny) #find_min(tryagain) # So for insertion, there's only one place to insert an item into # such that we can find it again. We have to look for where they key would be, # and when unsuccessful, stick that key there. def insert(node, x): if x < node.val: if not node.left: new_node = bst() new_node.parent = node new_node.val = x node.left = new_node return else: insert(node.left, x) else: if not node.right: new_node = bst() new_node.parent = node new_node.val = x node.right = new_node return else: insert(node.right, x) # I think this insertion code takes O(height) like the search code. # Is that O(log n) where n is the number of entries? only if balanced I think insert(tryagain, 19) traverse_tree_with_depth(tryagain) # Deletion from a tree is trickier because there's three cases. # The three cases are as follows: # 1. The node is a leaf node. Just remove the reference # 2. The node has one child: parent node gets ref'd to that child, remove the one node # 3. The node has two children: need to find next successor, stick it in where current node is. def find_successor(node): if node.right: return find_min_node_and_parent(node.right) else: return None def find_min_node_and_parent(node): parent = None curr = node while curr.left: parent = curr curr = curr.left return curr, parent def delete(node, x, parent): if node.val == x: if not node.left and not node.right: if parent.left == node: parent.left = None else: # parent.right == node: parent.right = None elif not node.left: if parent.left == node: parent.left = node.right else: # parent.right == node parent.right = node.right elif not node.right: if parent.left == node: parent.left = node.left else: parent.right = node.left # it has two children else: successor_node, successor_parent = find_successor(node) # successor will always have no kids? node.val = successor_node.val successor_parent.left = None return if x < node.val: delete(node.left, x, node) else: delete(node.right, x, node) # delete(tryagain, 14, None) # traverse_tree_with_depth(tryagain) # Yeah, this is really messy. I am needing to carry info around on the parent since I can't just # set the successor node to None in Python--that successor node that is stored in the variable seems to be a copy! # Why not just use the delete_node function I made? def find_min_node(node): curr = node while curr.left: curr = curr.left return curr def delete2(node, x): if not node: return node if x < node.val: node.left = delete2(node.left, x) elif x > node.val: node.right = delete2(node.right, x) else: # key is same! if not node.left: temp = node.right node = None return temp elif not node.right: temp = node.left node = None return temp temp = find_min_node(node.right) node.val = temp.val node.right = delete2(node.right, temp.val) # finds that one that we pulled in return node delete(tryagain, 14, None) traverse_tree_with_depth(tryagain) # That delete2 function I got from geeks for geeks is way nicer. # So an immediate successor node has to either be a leaf node, or else it is # a node that has a right node but it's the immediate one on the .right of our node. # because the righter you get, the bigger you get.
class Node: def __init__(self, val): self.val = val self.left = None self.right = None # 1 # 2 3 # 6 # 7 8 # # l = [1,2,3,None,None,None,6,7,8] def generate_tree_from_list(l): if not l: return None nodes = [None if i is None else Node(i) for i in l] children = nodes[::-1] root = children.pop() for node in nodes: if node: if len(children): node.left = children.pop() if len(children): node.right = children.pop() return root ex_tree = generate_tree_from_list(l) # a) Give an algorithm to generate a max-size independent set if G is a tree. # I think for a tree we can pick all the leaves, then exclude them and their parents and pick leaves again. def independent_set_tree(root): res = [] def helper(node, res): if not node: return False # not picked if not node.right and not node.left: res.append(node.val) return True # picked left = helper(node.left, res) right = helper(node.right, res) if left or right: # if the child was picked we don't pick the current one return False else: res.append(node.val) return True helper(root, res) return res print(independent_set_tree(ex_tree)) # b) Let G = (V, E) be a tree with weights associated with the vertices such that # the weight of each vertex is equal to the degree of that vertex. Give an efficient # algorithm to find a maximum independent set of G. # What we did for the minimum weight vertex cover of G last time will work too, if this question wants a maximum weight independent set AND the weight of each vertex is equal to the degree. # We'll pick a level and alternate from it. # The wording's kinda bad. If it wants a maximum size independent set then it's the same as before without the weights. # c) Let G = (V, E) be a tree with arbitrary weights associated with the vertices. # Give an efficient algorithm to find a maximum independent set of G. # 2 # 5 4 # 2 40 6 # 10 2 4 13 # 6 # It should pick [10,2,6,40,2,6] another = [2,5,4,2,40,None,6,10,2,4,13, None, None, None, None, None, None, None, 6] ex_nother = generate_tree_from_list(another) # When we pick the current node, we can get current node's value plus that of the children's nonpicked value. # When we don't pick the current node, we can get either the children's picked value OR the children's nonpicked value. So grab the best out of that. class Result: def __init__(self, picked_sum, picked_path, unpicked_sum, unpicked_path): self.picked_sum = picked_sum self.picked_path = picked_path self.unpicked_sum = unpicked_sum self.unpicked_path = unpicked_path def max_weight_indep_set(root): def helper(node): if not node: return Result(0, [], 0, []) left = helper(node.left) print(left.unpicked_sum) right = helper(node.right) left_path_if_curr_unpicked = None right_path_if_curr_unpicked = None if left.unpicked_sum > left.picked_sum: left_path_if_curr_unpicked = left.unpicked_path else: left_path_if_curr_unpicked = left.picked_path if right.unpicked_sum > right.picked_sum: right_path_if_curr_unpicked = right.unpicked_path else: right_path_if_curr_unpicked = right.picked_path return Result( node.val + left.unpicked_sum + right.unpicked_sum, [node.val] + left.unpicked_path + right.unpicked_path, max(left.unpicked_sum, left.picked_sum) + max(right.unpicked_sum, right.picked_sum), left_path_if_curr_unpicked + right_path_if_curr_unpicked) final = helper(root) if final.picked_sum > final.unpicked_sum: return final.picked_path else: return final.unpicked_path print(max_weight_indep_set(ex_nother))
def has_balenced_parens(parens_string): i=0 for letter in parens_string: if i<0: return False elif letter=="(": i+=1 elif letter==")": i-=1 if i==0: return True else: return False
#question1 import numpy def vectorpi(n): v=numpy.arange(0,n) #lists numbers 1 to n v=0.5*v*numpy.pi/(n-1) return v # question 2 import numpy from tutorial2 import vectorpi #assignment is the file containing the module called vector def integrate(n): dx=numpy.pi/2/n vec=vectorpi(n) tot=numpy.sum(numpy.cos(vec)) return dx*tot #question2B import numpy from tutorial2 import vectorpi from tutorial2 import integrate def del_hardcoded(n): mydeltas=[10,30,100,300,1000] for n in mydeltas: numerical_integral=integrate(n) print 'simple integration with ' + repr(n) + ' points gives ' + repr(numerical_integral) #question3 (used in question 4) #vec=numpy.cos(vectorpi(n)) # x_even=vec[2:-1:2] # x_odd=vec[1:-1:2] #question4 import numpy from tutorial2 import integrate #for comparison purposes from tutorial2 import vectorpi def simpson_integral(n): deltas=numpy.pi/2/(n-1)*2 vec=numpy.cos(vectorpi(n)) x_even=vec[2:-1:2] x_odd=vec[1:-1:2] total=numpy.sum(x_even)/3+numpy.sum(x_odd)*2/3+vec[0]/6+vec[-1]/6 return total*deltas #question4B import numpy from tutorial2 import simpson_integral from tutorial2 import vectorpi def number_errors(n): integral_val=simpson_integral(n) int_err=numpy.abs(integral_val-1) print 'error on 11 points is ' + repr(int_err-1) vec=numpy.cos(vectorpi(n)) x_even=vec[2:-1:2] for n in x_even: int_err=numpy.abs(simpson_integral(n)-1) print 'simpsons error on ' + repr(n) + ' is ' + repr(int_err) #question5 import numpy from matplotlib import pyplot as plt from tutorial2 import vectorpi from tutorial2 import simpson_integral def error_plot(n): nelem=[11,310,1010,3010,10010,30010,100010,300010,1000010] nelem=numpy.array(nelem) simpson_err=numpy.zeros(nelem.size) simple_err=numpy.zeros(nelem.size) for ii in range(nelem.size): n=nelem[ii] simpson_err[ii]=numpy.abs(simpson_integral(n)-1) simple_err[ii]=numpy.abs(simpson_integral(n)-1) plt.plot(nelem,simple_err) plt.plot(nelem,simpson_err) ax=plt.gca() ax.set_yscale('log') ax.set_xscale('log') plt.show() #first bonus question #It works by judging by the flatness and slope of the function it is integrating how to treat the step size it uses for numerical integration in order to maximize efficiency. What this means is that you may get slightly different answers from one region to the next even if they're analytically the same. #second bonus question (works with scipy) #from scipy import integrate #N = 5 #def f(t, x): # return np.exp(-x*t) / t**N
#def print_formatted(number): # your code goes here # for i in range(1,number): # print(tohex(i)) #print_formatted(6) def fun(N): width = len(bin(N)) - 2 for i in range(1,N+1): print "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i,width = width) n = input() fun(n)
import csv with open("data.csv",newline="") as f: reader= csv.reader(f) file_data= list(reader) numbers = 0 numberofnumbers = len(file_data) for sum in file_data: numbers = numbers+ float(sum[1]) mean= numbers / numberofnumbers print("mean is: "+ str(mean)) import math diffrence= 0 for dif in file_data: diffrence = (diffrence - mean) diffrence_squared= diffrence ** 2 print("difference of each number by the mean and squared is: " + str(diffrence_squared)) standard_deviation= math.sqrt(diffrence_squared/ (file_data - 1)) print("standard deviation is: " + str(standard_deviation))
# -------------------- Менеджеры контекста --------------------------------------- # Как работает оператор with? # with open('test', 'w') as f: # f.write('Stroka') # Оператор with использует интерфейс менеджера контекста объекта. # Создадим свой класс, реализующий интерфейс менеджера контекста. class ListTransaction: def __init__(self, thelist): self.thelist = thelist def __enter__(self): self.workingcopy = list(self.thelist) return self.workingcopy def __exit__(self, exc_type, value, traceback): print(exc_type, value, traceback) if exc_type is None: self.thelist[:] = self.workingcopy return False items = [1, 2, 3] with ListTransaction(items) as tr: tr.append(4) tr.append(5) print(items) try: with ListTransaction(items) as working: working.append(6) working.append(7) raise ValueError("Ошибка в транзакции! Данные не будут сохранены") except ValueError: print("Произошёл системный сбой! Проверьте данные!") print(items) # Небольшое упрощение с использованием модуля contextlib... from contextlib import contextmanager @contextmanager def ListTransaction(thelist): workingcopy = list(thelist) yield workingcopy # Часть кода после строки yield будет выполнена, если не возникло исключений # Изменить оригинальный список, только если не возникло ошибок print('No exception') thelist[:] = workingcopy items = ['Фродо', 'Сэм', 'Горлум'] try: with ListTransaction(items) as working: # working = 'l-i-s-t-' working.append('Кольцо') working.append('Мордор') raise(ValueError('oop')) except ValueError: print("Кто-то!") print(items)
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() fruits = ["яблоко", "банан", "киви", "арбуз"] right_offset = len(max(fruits, key=len)) for item in fruits: print('{}. {:>{}}'.format(fruits.index(item)+1, item, right_offset)) # Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. list_a = [1, 2, 3, 4, 5, 6] list_b = [3, 4, 5, 6, 7, 8] #TODO значения могут повторятся! for b in list_b: if b in list_a: list_a.remove(b) print(list_a) # Задача-3: # Дан произвольный список из целых чисел. # Получите НОВЫЙ список из элементов исходного, выполнив следующие условия: # если элемент кратен двум, то разделить его на 4, если не кратен, то умножить на два. a = [1, 5, 7, 9, 5, 3, 4, 6, 8, 54, 3453, 7, 345, 7, 4, 3] print(a) new_a = [] for val in a: if val % 2 == 0: new_a.append(int(val / 4)) else: new_a.append(val * 2) print(new_a)
import random class Card: def __init__(self, title='', rows_amount=3, cols_amount=9, nums_per_row=5, max_num=90): self._rows_amount = rows_amount self._cols_amount = cols_amount self._nums_per_row = nums_per_row self._max_num = max_num self._title = title self._card = [['' for _ in range(self._cols_amount)] for _ in range(self._rows_amount)] self._nums = random.sample(range(1, self._max_num + 1), self._nums_per_row * self._rows_amount) self._pixels = self._cols_amount * 3 self._nums_for_game = self._nums[:] @property def nums(self): return len(self._nums_for_game) def _mapping_card(self): for row in self._card: while row.count('*') != self._nums_per_row: row[random.randrange(self._cols_amount)] = '*' def _filling_card_with_numbers(self): for i, row in enumerate(self._card): tmp = sorted(self._nums[i * self._nums_per_row:(i + 1) * self._nums_per_row], reverse=True) for j, item in enumerate(row): self._card[i][j] = tmp.pop() if item else '' def __str__(self): res = ['{:-^{}}'.format(self._title, self._pixels), ] for row in self._card: res.append(' '.join(['{:<2}'.format(x) for x in row])) res.append('=' * self._pixels) return '\n'.join(res) def modify_card(self, num): i = int(self._nums.index(num) / self._nums_per_row) self._card[i][self._card[i].index(num)] = '-' self._nums_for_game.remove(num) def check_num(self, num): return num in self._nums def create_card(self): self._mapping_card() self._filling_card_with_numbers() class Game: def __init__(self, max_num=90): self._max_num = max_num self._unit1 = Card('====== Ваша карточка ======') self._unit2 = Card('=== Карточка компьютера ===') def _get_random_num(self): random_numbers = random.sample(range(1, self._max_num + 1), self._max_num) for i in random_numbers: yield i, self._max_num - random_numbers.index(i) - 1 def _check_answer(self, unit, num, answer): if answer != 'y' and answer != 'n': self._check_answer(unit, num, input('Зачеркнуть цифру? (y/n)')) elif answer == 'y' and unit.check_num(num): unit.modify_card(num) return 0 elif answer == 'n' and not unit.check_num(num): return 0 elif answer == 'y' and not unit.check_num(num): print('======== Цифры {} нет на вашей карточке! Следующий ход: ========'.format(num)) #, end=' ') # return 1 elif answer == 'n' and unit.check_num(num): print('{} на вашей карточке.'.format(num), end=' ') return 1 def lets_play(self): self._unit1.create_card() self._unit2.create_card() num_generator = self._get_random_num() while self._unit1.nums and self._unit2.nums: num, left = next(num_generator) print(self._unit1) print(self._unit2) print('Новый бочонок: {} (осталось {})'.format(num, left)) if self._check_answer(self._unit1, num, input('Зачеркнуть цифру? (y/n)')): return 'К сожалению, вы проиграли.' if self._unit2.check_num(num): self._unit2.modify_card(num) if not self._unit1.nums and not self._unit2.nums: return 'Ничья!' elif self._unit2.nums: return 'Поздравляем, вы победили!' else: return 'Компьютер успел первым. Попробуйте еще раз.' if __name__ == '__main__': game = Game() print(game.lets_play())
# print('Hello' + ' ' + 'world') # print('Hello' ' ' 'world') # print('Hello! ' * 3) # # url = 'http://yandex.ru' # index = url.find('yandex') # print(url.find('yandex')) # print(url[index:]) # name = 'ivAn peTrov' # print(name.title()) # print(name.upper()) # print(name.lower()) # print(len(name)) # name = 'Иван' # surname = 'Петров' # age = 30 # bank_account = 100.30 # print('Привет ' + name + ' ' + surname) # print('Привет %s %s' % (name, surname)) # print('Привет {} {} {}'.format(name, surname, name)) # print('Привет {} {} вам на данный момент {} лет, на вашем банковском счету {} рублей'.format(name, surname, age, bank_account)) # my_list = [1, 2, 1] # print(my_list) # my_list[-1] = 100 # print(my_list[1:]) # print(my_list + [4, 5, 6]) # print(my_list) # my_list.extend([4, 5, 6]) # print(my_list) # # my_list.remove(1) # print(my_list) # # my_list.append(200) # print(my_list) # my_list.insert(2, 300) # print(my_list) # # last_element = my_list.pop() # print(last_element) # my_list = [4, 5, 6, 7, 1, 2, 3, 3, 3, 3] # # print(my_list.count(3)) # # my_list = ['zxcvzbnxcvznxc', 'aaaaaa', 'aa'] # # my_list.sort(key=len) # print(my_list) # # [1,2,3].reverse() # my_list = ['Ivan', 'Andrey', 'Olga'] # if 'Ivan' in my_list: # print('Ivan есть в списке') # a = [] # список # b = () # кортеж # c = {} # словарь # my_tuple = (2, 3, 4) # list(my_tuple).sort() # fruits = ['apple', 'banana', 'mango', 'orange', 'melon'] # i = 0 # while i < len(fruits): # print(fruits[i]) # i += 1 # for fruit in fruits: # print(fruit) # fruits.remove(fruit) # for index, fruit in enumerate(fruits): # print(index, fruit) # my_list = [1, 2, 3] # name = 'Ivan' # human = {'name': name, 'surname': 'Petrov', 'data': {}} # # my_list[0] = 100 # human['name'] = 'Vasya' # print(my_list) # print(human) # # my_list.append(200) # human['age'] = None # print(human) # human = {'name': 'Ivan', 'surname': 'Petrov'} # for key, value in human.items(): # print(key, value) # # for key in human.keys(): # print(key) # for value in human.values(): # print(value) # print(human.pop('name')) # print(human) x = 3 y = 3 a = {1, 2, 3, x} b = {y, 4, 5, 6} # print(a) # print(b) # print(a == b) # print(a >= b) # print(a & b) print(a - b) # print(a | b) words = ['Ivan', 'Oleg', 'Ivan', 'Olga', 'Oleg'] print(set(words)) a = {1, 2, 3} b = set([1, 2, 3]) print(a, b)
import csv with open('data.csv') as f_n: f_n_reader = csv.reader(f_n) for row in f_n_reader: print(row) print() with open('data.csv') as f_n: f_n_reader = csv.reader(f_n) print(f_n_reader) print() with open('data.csv') as f_n: f_n_reader = csv.reader(f_n) print(list(f_n_reader)) print() with open('data.csv') as f_n: f_n_reader = csv.reader(f_n) f_n_headers = next(f_n_reader) print('Headers: ', f_n_headers) for row in f_n_reader: print(row) # Почему выводит не словарь а OrderedDict? print() with open('data.csv') as f_n: f_n_reader = csv.DictReader(f_n) for row in f_n_reader: print(row) # print(row['hostname'], row['model'])
# class Colors: # def __init__(self, colors): # self.colors = colors # # def __iter__(self): # i = 0 # while True: # yield self.colors[i] # i += 1 # if i == len(self.colors): # i = 0 # # class Colors2: # def __init__(self, colors): # self.colors = colors # self.i = 0 # # def __iter__(self): # return self # # def __next__(self): # self.i += 1 # if self.i == len(self.colors): # self.i = 0 # return self.colors[self.i] # # colors = Colors(['red', 'green', 'blue']) # # # for color in colors: # # print(color, end='') # # input() # # colors2 = Colors2(['green', 'red', 'white']) # # for color in colors2: # print(color, end='') # input() # # f = open('bla') # # for line in f: # print(line) # # f = close('bla') # import random # # class RandNumbers: # num = 0 # # def __iter__(self): # return self # # def __next__(self): # self.num += 1 # if self.num > 100: # raise StopIteration # return random.randint(-10, 10) # # rnd = RandNumbers() # # # for el in rnd: # # print('random number = ', el, end='') # # input() # # # print(list(rnd)) # # # print(list(rnd)) # import itertools # # # # l = iter([1, 2, 3]) # # l1 = iter ([4, 5]) # # # # for el in itertools.chain(l, l1): # # print(el) # # # # # for el in itertools.count(): # # # print(el) # НЕ ЗАПУСКАТЬ!!! # # colors = ['red', 'green', 'blue'] # # for color in itertools.cycle(colors): # print(color) # input() # class Vector: # def __init__(self, coords): # self.x, self.y = coords # # def __add__(self, other): # x = self.x + other.x # y = self.y + other.y # return Vector((x, y)) # # def __sub__(self, other): # x = self.x - other.x # y = self.y - other.y # return Vector((x, y)) # # def __mul__(self, other): # x = self.x * other.x # y = self.y * other.y # return Vector((x, y)) # # def __str__(self): # return 'v (%s %s)' %(self.x, self.y) # # v1 = Vector((10, 20)) #синтаксический сахар # #Vector.__init__((10, 20)) #аналогичная запись, вверху синтаксический сахар # v2 = Vector((11, 21)) # # v3 = v1 + v2 # #v1.__add__(v2) #аналог, вверху синтСахар # print(v3.x, v3.y) # # v4 = v1 - v2 # print(v4.x, v4.y) # # v5 = v1 * v2 # print(v5.x, v5.y) # # l = [1, 2, 3] # # l = list(1, 2, 3) #аналогичная запись, выше синтСахар # # a = 2 # # a = int(2) #аналогичная запись, выше синтСахар # # # def new(): # # pass # # # # new = def() # # # v1 = Vector((10, 22)) # # print(v1) # # a = 2 + 2.5 # print(a) # import os # # # class LogReader: # # def __init__(self): # self.files = [] # # for file in os.listdir(): # if os.path.isdir(file): # continue # if file.startswith('log'): # file_descriptor = open(file, encoding='UTF-8') # self.files.append(file_descriptor) # # self.i = 0 # # def __del__(self): # for file_descriptor in self.files: # file_descriptor.close() # print('Файлы закрыты') # # def __iter__(self): # return self # # def __next__(self): # while self.i < len(self.files): # for line in self.files[self.i]: # return line # self.i += 1 # raise StopIteration # # # log_reader = LogReader() # # for i in log_reader: # print(i.strip())
import data_import as data import matplotlib.pyplot as plt import model.two_layer as two_layer import model.l_layer as l_layer import prediction.post_function as pdt # Loading Data and knowing Dimension train_x_origin, train_y, test_x_origin, test_y, classes = data.load_data() m_train, num_px, m_test = data.gettingDimension(train_x_origin, test_x_origin) train_x, test_x = data.flattening_data(train_x_origin, test_x_origin) # Visualizing one test examples index = 10 plt.imshow(train_x_origin[index]) plt.show() print("\ny = " + str(train_y[0, index]) + ". It's a " + classes[train_y[0, index]].decode("utf-8") + " picture.") # 2 Layer Neural Network (basic) n_x = train_x.shape[0] n_h = 7 n_y = 1 parameters = two_layer.two_layer_model(train_x, train_y, layer_dims=( n_x, n_h, n_y), num_iterations=2500, print_cost=True) predictions_train = pdt.predict(train_x, train_y, parameters) predictions_test = pdt.predict(test_x, test_y, parameters) # L layer Neural Network print("\n train_x.shape[0] : {}".format(train_x.shape[0])) layers_dims = [train_x.shape[0], 20, 7, 5, 1] parameters = l_layer.L_layer_model( train_x, train_y, layers_dims, num_iterations=2500, print_cost=True) predictions_train = pdt.predict(train_x, train_y, parameters) predictions_test = pdt.predict(test_x, test_y, parameters)
''' 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. ''' user_str = (input('Введите слова через пробел: ')).split(' ') i = 1 for word in user_str: if len(word) > 10: print(i, word[0:10]) else: print(i, word) i +=1
''' 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. ''' def divisions(a, b): return a / b a = input('Введите делимое: ') b = input('Введите делитель: ') if not a.isdigit() or not b.isdigit() or b == '0': print('Неверный формат ввода') exit() result = divisions(int(a), int(b)) print('Результат деления:', result)
n = input('Введите целое положительное число: ') # короткий вариант max_d = max(map(int, n)) print(max_d) # вариант с while i = 0 max = n[0] while i < len(n) - 1: if n[i] < n[i+1]: max = n[i+1] i +=1 print(max)
import turtle # creatring a turtle-object tu = turtle.Turtle() # hide cursor tu.hideturtle() # set up the window as full turtle.setup(width=1.0, height=1.0, startx=None, starty=None) screen_height = turtle.screensize(canvwidth=None, bg=None) screen_height = float(screen_height[0]) print(screen_height) tu.penup() tu.sety(-screen_height) tu.pendown() # set up the pensize of 2 pixels tu.width(2) # adjust the turtle by turning it on 90° to the left tu.left(90) # turtle speed - the parameters are ''' “fastest”: 0 “fast”: 10 “normal”: 6 “slow”: 3 “slowest”: 1 ''' tu.speed(0) # move the turtle 100 pixels forward tu.forward(100) # recursive function wich creates the fractal def tree(length): # check if length is not to short if length < 10: return else: tu.forward(length) tu.left(30) tree(3*length/4) tu.right(60) tree(3*length/4) tu.left(30) tu.backward(length) # call the function with a length of 100 pixels tree(screen_height/2) # close the window by mouse click turtle.Screen().exitonclick()
# Team member: Hanna Magan and Kristine # Course: CS151, Dr.Rajeev # Date: 22 September 2021 # Programing Assignment 1 # import math # Program Inputs: ask user for population (births,deaths and migration by year) birth = float(input("Enter_births")) deaths = float(input("Enter_death")) migration = float(input("Enter _migration")) current_population= float(input("Enter _current_population")) year = float(input("Enter_year")) # Program Outputs: ask user for current population total_population = float(31536000*(year*(birth - deaths + migration))) + current_population print(total_population)
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Justin Dano 10/23/2016 # Design inspired by articles on Quantstart.com from abc import ABCMeta, abstractmethod class Portfolio(object): """ Abstract Base class for a portfolio. Currently it includes logic to generate positions based on the Strategy class, and to perform backtesting. Portfolios will contain a basket of stocks with their respected holdings, cash total and any returns. """ __metaclass__ = ABCMeta @abstractmethod def generate_positions(self): """Provides the logic to allocate cash to certain stock positions based on signals created from the Strategy class.""" raise NotImplementedError("Must implement generate_positions()!") @abstractmethod def backtest_portfolio(self): """Provides the necessary functionality to execute pseudo-orders, and dynamically update the portfolio after each bar of data. The portfolio should also be able to calculate returns and report total equity.""" raise NotImplementedError("Must implement backtest_portfolio()!")
# Based on this # https://www.youtube.com/watch?list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_&time_continue=6&v=jA5LW3bR0Us # Pretty simple one buuuuuut names = ['Jeff', 'Gary', 'Jill', 'Samantha'] ##for name in names: ## #print('Hello there, ' + name) ## print(' '.join(['Hello there', name])) #print(', '.join(names)) who = 'Gary' how_many = 12 print(who, 'bought', how_many) print('{} bought {} apples today'.format(who, how_many))
import sys class Justify(object): def __init__(self, text, maxWidth): self.words = text self.maxWidth = maxWidth def fullJustify(self): """ :type words: List[str] :type maxWidth: int :rtype: List[str] """ text_len = len(self.words) dp = [0]*text_len parent = [0]*text_len dp[-1] = self.badness([self.words[-1]]) parent[-1] = text_len - 1 for i in range(text_len-2, -1, -1): min_score = sys.maxint min_split = None for j in range(i+1, text_len): badness = dp[j] + self.badness(self.words[i:j]) if badness < min_score: min_score = badness min_split = j dp[i] = min_score parent[i] = min_split print dp print parent def badness(self, text): word_len = sum([len(i) for i in text]) sentence_len = word_len + len(text) - 1 print 'badness:', text if sentence_len > self.maxWidth: print sys.maxint return sys.maxint else: print pow(self.maxWidth - sentence_len, 2) return pow(self.maxWidth - sentence_len, 2) tool = Justify(["This", "is", "an", "example", "of", "text", "justification."], 25) tool.fullJustify()
import dfs def dfs_connected(graph): connected_components = list() discovered_nodes = set() for node in graph.keys(): if node not in discovered_nodes: connected = dfs.dfs(graph, node) connected_components.append(connected) discovered_nodes = discovered_nodes.union(connected) print 'connected_components', connected_components print 'discovered_nodes', discovered_nodes return connected_components if __name__ == '__main__': disconnected_graph = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 4, 2], 4: [1, 3, 2], 6: [7], 7: [6], } print list(dfs_connected(disconnected_graph))
def find_kth(A, B, k): # Stopping condition is when only k elements are left in both the array # return the max of the last elements if len(A) > len(B): A, B = B, A if not A: return B[k] if len(A) + len(B) - 1 == k: return max(A[-1], B[-1]) # invariant k = i + j # set i to be k/2 whenever possible; this way we at least eliminate k/2 elements in each cycle. i = min(len(A)-1, k/2) j = min(len(B)-1, k-i) # if A[i] is greater; at least i elements from A is in the set of k-smallest elements. # similarly if B[j] is greater; at least j elements from B are in the set of k-smallest elements. # so remove them and reduce k accordingly and recursively call find_kth. if A[i] > B[j]: return find_kth(A[:i], B[j:], i) else: return find_kth(A[i:], B[:j], j) A = [0, 2, 4, 6, 8, 10] B = [1, 3, 5, 7, 9, 11] k = find_kth(A, B, 5) print "kth smallest:", k
import time def dfs_recusive(graph, start): visited = set() def _dfs(node): visited.add(node) for next_node in set(graph[node]) - visited: _dfs(next_node) _dfs(start) return visited if __name__ == '__main__': test_graph = {1: [2, 3, 4, 7], 2: [1, 3, 4], 3: [1, 2, 4], 4: [1, 2, 3, 5], 5: [4, 6, 7, 8], 6: [5, 7, 8], 7: [1, 5, 6, 8], 8: [5, 6, 7] } print 'using recursive dfs implementation' timer = time.time() print dfs_recusive(test_graph, 1) print time.time() - timer
import unittest class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.datastack = [] self.minstack = [] def push(self, x): """ :type x: int :rtype: void """ # insert into min stack if len(self.datastack) == 0: self.minstack.append(x) elif x <= self.minstack[-1]: self.minstack.append(x) # insert into data stack self.datastack.append(x) self.display() def pop(self): """ :rtype: void """ # self.display() data = self.datastack.pop() if data == self.minstack[-1]: self.minstack.pop() return data def top(self): """ :rtype: int """ # print 'top', self.datastack[-1] return self.datastack[-1] def getMin(self): """ :rtype: int """ return self.minstack[-1] # def display(self): # print 'data:', self.datastack # print 'min:', self.minstack class TestMinStack(unittest.TestCase): def test_min(self): ms = MinStack() ms.push(-3) ms.push(0) ms.push(-2) self.assertTrue(ms.getMin() == -3) self.assertTrue(ms.top() == -2) def test_min_after_pop(self): ms = MinStack() ms.push(-2) ms.push(0) ms.push(-3) self.assertTrue(ms.pop() == -3) self.assertTrue(ms.getMin() == -2) self.assertTrue(ms.top() == 0) if __name__ == '__main__': unittest.main() # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
class Employee: raise_amount=1 num_of_emps=0 def __init__(self,first,last,pay): self.first=first self.last=last self.pay=pay Employee.num_of_emps += 1 def fullname(self): return'{}{}'.format(self.first,self.last) def apply_raise(self): self.pay=int(self.pay*self.raise_amount) @classmethod def set_raise_amount(cls,amount): cls.raise_amount = amount emp_1=Employee('satyam','kumar',50000) emp_2=Employee('shivam','kumar',70000) print(emp_1) #<__main__.Employee object at 0x000002B2D4488460> print(emp_1.pay) #50000 print(emp_2.first) print(emp_1.fullname()) print(Employee.raise_amount) print(Employee.num_of_emps) Employee.set_raise_amount(4) print(Employee.raise_amount)
class Employee: pass emp1=Employee() emp1.first='satyam' emp1.last='kumar' emp1.job='sonus' emp1.salary=60000 emp1.email='[email protected]' print(emp1.first) print(emp1.last) print(emp1.job) print(emp1.salary) print (emp1.email) print(emp1) emp2=Employee() print(emp2) emp2.first='Shivam' emp2.last='kumar' emp2.job='google' emp2.salary=200000 emp2.email='[email protected]' print(emp2.first) print(emp2.last) print(emp2.job) print(emp2.salary) print(emp2.email)
import sqlite3 app_senha="senha123@" senha=input("Insira a senha: ") if senha !=senha: print("senha invalida ! encerrando...") exit() conn= sqlite3.connect("senhas.db") cursor= conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( servico text not null, usuario text not null, senha interger not null ); ''') def menu(): print("********************************") print("* i : inserir uma nova senha *") print("* l : listar todos os serviços salvos") print("* r : recuperar um senha **") print("* s : sair do programa **") print("*********************************") def get_password(services): cursor.execute(f''' select usuario, senha from users where servico ='{services}' ''') if cursor.rowcount ==0: print(" Nao foi cadastrado nem uma senha (use l para listar todas as senhas) ") else: for i in cursor.fetchall(): print(i) def insert_password(servicoes,loginn,senhaa): cursor.execute(f''' insert into users(servico,usuario,senha) values ('{servicoes}','{loginn}','{senhaa}') ''') conn.commit() def show_passwords(): cursor.execute(''' select * from users; ''') for x in cursor.fetchall(): print(x) while True : menu() opc=input("O que deseja fazer ? :") if opc not in ['i','l','r','s']: print("Opcao invalida !") continue elif opc =='s': break elif opc =='l': show_passwords() elif opc =='i': servicoes=input('Qual serviço deseja armazenar ? ') loginn=input('Qual o usuario ? ') senhaa=input('Qual a senha ? ') insert_password(servicoes,loginn,senhaa) elif opc =='r': servico=input('Qual servico voce quer recuperar a senha ? ') get_password(servico) conn.close()
_sum = 0 number = 0 while number < 20: number += 1 if number == 10 or number == 11: continue _sum += number print(number, end = " ") print(_sum, end = " ")
# File: Goldbach.py # Description: This is a program that displays all pairs of prime numbers that sum to equal a user defined number for a user defined range of numbers # Student Name: Derek Orji # Student UT EID: dao584 # Course Name: CS 303E # Unique Number: 51845 # Date Created: 3/24/2017 # Date Last Modified: 3/24/2017 # this function determines if a number is prime def is_prime (n): if (n == 1): return False limit = int (n ** 0.5) + 1 divisor = 2 while (divisor < limit): if (n % divisor == 0): return False divisor += 1 return True def main(): # User input for lower and upper limits of range a = eval(input("Enter the lower limit: ")) b = eval(input("Enter the upper limit: ")) # both lower and upper limit must be even, lower limit must be less than upper limit, and lower limit must be greater than 4. If any of these aren't true, then re-prompt the user while a < 4 or a % 2 != 0 or b % 2 != 0 or (b <= a): a = eval(input("Enter the lower limit: ")) b = eval(input("Enter the upper limit: ")) # gets pairs of prime numbers for every even number in user defined range for i in range(a, b+1, 2): # eligible is a list that will hold all prime numbers less than a given number eligible = [] print(i, end = " ") # we only populate eligible with those prime numbers that are up to half of the given number we are looking at for j in range(2,i//2+1): if is_prime(j) == True: eligible += [j] # subtract eligible prime number from its given number to find the checker, the checker is then checked to see if it is prime # if the checker is prime, then both it and its corresponding eligible number are a pair that sum up to the user defined number for x in range(len(eligible)): checker = i - eligible[x] if is_prime(checker) == True: print("=", eligible[x], "+", checker, end = " ") print() main()
s = input("Enter a string: ") if len(s) % 2 == 0: print(s, "contains an even number of characters") else: print(s, "contains an odd number of characters")
pay = eval(input("What is your pay? ")) score = eval(input("What is your score? ")) if score > 90: pay = 1.03 * pay print("For your efforts, your new pay is", round(pay, 3),"!")
year = 1 tuition = 10000 for year in range(0, 10): year = year + 1 tuition = 1.05 * tuition tuition10 = tuition print(tuition10) tuitioninitial = tuition10 year = 0 _sum = tuitioninitial while year < 3: year = year + 1 tuitioninitial = 1.05 * tuitioninitial _sum += tuitioninitial print(_sum)
# File: Benford.py # Description: This program counts the frequency of the leading digit of a population sample # Student Name: Derek Orji # Student UT EID: dao584 # Course Name: CS 303E # Unique Number: 51845 # Date Created: 4/29/2017 # Date Last Modified: 4/29/2017 def main(): # create an empty dictionary pop_freq = {} # initialize the dictionary pop_freq['1'] = 0 pop_freq['2'] = 0 pop_freq['3'] = 0 pop_freq['4'] = 0 pop_freq['5'] = 0 pop_freq['6'] = 0 pop_freq['7'] = 0 pop_freq['8'] = 0 pop_freq['9'] = 0 # open file for reading in_file = open ("./Census_2009.txt", "r") # read the header and ignore header = in_file.readline() # read subsequent lines for line in in_file: line = line.strip() pop_data = line.split() # get the last element that is the population number pop_num = pop_data[-1] # make entries in the dictionary if pop_num[0] == "1": pop_freq['1'] += 1 if pop_num[0] == "2": pop_freq['2'] += 1 if pop_num[0] == "3": pop_freq['3'] += 1 if pop_num[0] == "4": pop_freq['4'] += 1 if pop_num[0] == "5": pop_freq['5'] += 1 if pop_num[0] == "6": pop_freq['6'] += 1 if pop_num[0] == "7": pop_freq['7'] += 1 if pop_num[0] == "8": pop_freq['8'] += 1 if pop_num[0] == "9": pop_freq['9'] += 1 # close the file in_file.close() # write out the result print("Digit Count %") sum1 = 0 for key in pop_freq: sum1 += pop_freq[key] for key in pop_freq: #print(str(key)+" "+str(pop_freq[key])+" "+str(format(((pop_freq[key]/sum1)*100), '.1f'))) print(str(key)+" "+str(pop_freq[key]) +" "+ (" "*(7 - len(str(pop_freq[key]))))+str(format(((pop_freq[key]/sum1)*100), '.1f'))) main()
def main(): filerandom = open("randomfile.txt", "w") filerandom.write("I am the greatest basketball player that ever lived because I love to play basketball and basketball loves me, I love basketball basketball you dont love me basketball you hate me basketball lets rock and roll basketball yes") filerandom.close() dobbie = input("What file do you want to look at? ").strip() string1 = input("What word are you looking for: ").strip() filerandom = open(dobbie, "r") newfile = filerandom.readlines() count = 0 for line in newfile: count += line.count(string1) print(string1, "appears", count, "times in", dobbie) main()
import turtle import math line_size = 150 wn = turtle.Screen() wn.bgcolor("lightgreen") t = turtle.Turtle() t.speed(1) t.shape('turtle') t.color('blue') t.penup() t.left(90) t.stamp() t.right((360/12)/2) t.forward((line_size * 2 * math.pi)/12) #t.forward(line_size/2) t.stamp() for i in range(9): t.stamp() t.right(360/12) t.forward((line_size * 2 * math.pi)/12) print(t.shapesize()) wn.exitonclick()
# count = 2 # while count<=15: # print(count) # count+=3 # print(count) invalid_number = True while invalid_number: user_value = int(input("Enter a number above 10: ")) if user_value>10: print("Thanks,thats wrks! is a great choice") invalid_number = False else: print("ok") print("stop")
# def calculator(operation,a,b): # if operation=="add": # return a+b # elif operation == "subtract": # return a-b # elif operation == "multiply": # return a*b # elif operation == "divide": # return a/b # else: # return "Not sure about the answer" # print(calculator("add",4,8)) # print(calculator("subtract",47,8)) # print(calculator("multiply",14,8)) # print(calculator("divide",4,28)) # print(calculator(",",4,8)) zip_code = "902910" # check if len (zip_code): check = "Valid" else: check = "Invalid" check = "Valid" if len(zip_code) ==5 else "Invalid" print(check) # print(len(zip_code)) # print(zip_code("check"))
# 2016, Day 1. # Input is a single line consisting of movement instructions separated by commas. # Start facing north, each movement instruction dictates whether to turn left or # right and then walking a certain distance on a manhattan grid. # # Part 1: Calculate final distance from starting point. # Part 2: Determine first point on grid that we visit twice. NAME = "Day 1: No Time for a Taxicab" NORTH = lambda x, y, d : [x + d, y] SOUTH = lambda x, y, d : [x - d, y] WEST = lambda x, y, d : [x, y - d] EAST = lambda x, y, d : [x, y + d] LEFT = {NORTH: WEST, WEST: SOUTH, SOUTH: EAST, EAST: NORTH} RIGHT = {NORTH: EAST, EAST: SOUTH, SOUTH: WEST, WEST: NORTH} def parseInput(stream): return [({'L': LEFT, 'R': RIGHT}[x[0]], int(x[1:])) for x in stream.read().strip().split(", ")] def part1(moves): x, y, z = [0, 0, NORTH] for (c, d) in moves: z = c[z] x, y = z(x, y, d) return abs(x)+abs(y) def part2(moves): seen = set() x, y, z = [0, 0, NORTH] for (c, d) in moves: z = c[z] # Visit each point along the way. for _ in range(d): if (x, y) in seen: return abs(x)+abs(y) seen.add((x, y)) x, y = z(x, y, 1)
# 2016, Day 16. # We fill a disk with non-random bits. This sequence of bits is constructed from # a pattern that grows by reversion and inversion, using a method similar to the # growth of the binary dragon curve. # # Approach: we don't need to expand the string, only generate its checksum. Each # letter in the checksum represents a even-sized block in the expanded string and # its value is purely controlled by whether the number of "1"s (or "0"s) in that # block is even or odd. # # Such a block consists of several things that control its inverted parity. # - a certain number n of AB pairs. Where A is the input and B is the reversed inversion of A. # - a certain number of bits from the dragon fractal sprinkled throughout. # - a prefix of an AB pair, the AB pair is then split between two checksum blocks. # - a suffix of an AB pair, because the prefix is in the previous block. # # Part 1: Calculate the checksum for a disk of 242 bits. # Part 2: Calculate the checksum for a disk of 35651584 bits. NAME = "Day 16: Dragon Checksum" # The parity of the first n digits of the dragon fractal. # Apparently, no one knows how this works. def dragonParity(n): gray = n ^ (n >> 1) return (gray ^ (n & gray).bit_count()) & 1 # Based on https://www.reddit.com/r/adventofcode/comments/5ititq/comment/dbbk6o9 def solve(pattern, diskSize): # Bit trick returns the largest power of 2 that divides l. # 272 = 100010000 # 272-1 = 100001111 # ~(272-1) = 011110000 # 272 & ~(272-1) = 000010000 blockSize = diskSize & ~(diskSize-1) pair = pattern + [x ^ 1 for x in reversed(pattern)] sum = [] prev = 0 offset = blockSize while offset <= diskSize: nDragons = offset // (len(pattern)+1) nPairs = (offset - nDragons) // (len(pair)) prefix = pair[:(offset - nDragons) % len(pair)] p = dragonParity(nDragons) # Parity of entire dragon fractal considered so far over all prev. blocks. p ^= nPairs & len(pattern) # Parity of n AB pairs is 1 if both len(pattern) and N are odd. p ^= prefix.count(1) % 2 # Parity of the prefix in this block. p &= 1 # Only consider last bit. sum.append(p ^ prev ^ 1) offset += blockSize prev = p return ''.join([str(x) for x in sum]) def parseInput(stream): return [int(x) for x in stream.read().strip()] def part1(input): return solve(input, 272) def part2(input): return solve(input, 35651584)
# 2016, Day 3. # Input is a table of numbers with 3 columns. # # Part 1: Count the rows that form a possible set of triangle numbers. # Part 2: For each group of three lines, count the number of columns # (of size 3) that form a possible set of triangle numbers. NAME = "Day 3: Squares With Three Sides" def trianglish(a, b, c): return a+b > c and a+c > b and b+c > a def parseInput(stream): return [[int(x) for x in line.split()] for line in stream.readlines()] def part1(rows): return len([1 for [a, b, c] in rows if trianglish(a, b, c)]) def part2(rows): count = 0 for row in range(0, len(rows), 3): for col in range(3): if trianglish(rows[row+0][col], rows[row+1][col], rows[row+2][col]): count += 1 return count
""" Problem Statement : https://www.hackerearth.com/practice/data-structures/hash-tables/ basics-of-hash-tables/practice-problems/algorithm/exists/ """ from collections import deque from sys import argv, stdin def hash_insert(element, hash_table, size): index = element % size if hash_table[index] is not None: hash_table[index].append(element) else: hash_table[index] = [element] def hash_search(element, hash_table, size): index = element % size if hash_table[index] is not None: if float(element) in hash_table[index]: print("Yes") return else: print("No") else: print("No") input_file = open(argv[1]) if len(argv) - 1 > 0 else stdin inputs = deque() elements = list(map(int, input_file.read().split())) inputs.extend(elements) no_of_test_cases = inputs.popleft() for _ in range(no_of_test_cases): size_of_array = inputs.popleft() hash_table = dict.fromkeys(list(range(0, 5*size_of_array))) array = [] for i in range(size_of_array): array.append(inputs.popleft()) for element in array: hash_insert(element, hash_table, 5*size_of_array) no_of_queries = inputs.popleft() search_queries_list = [] for i in range(no_of_queries): search_queries_list.append(inputs.popleft()) for element in search_queries_list: hash_search(element, hash_table, 5*size_of_array)
# Programma PERMUTAZIONI in Python # Figura 10.8 del libro "Il Pensiero Computazionale: dagli algoritmi al coding" # Autori: Paolo Ferragina e Fabrizio Luccio # Edito da Il Mulino def esamina(p): print p def permutazioni(p, k): """ Permutazioni degli elementi di un sottovettore p[k:n-1], estremi inclusi :param p: vettore da permutare :param k: indice inferiore del vettore p """ n = len(p) if k == n - 1: esamina(p) else: for i in range(k, n): p[i], p[k] = p[k], p[i] # scambia p[k] con p[i] permutazioni(p, k + 1) p[i], p[k] = p[k], p[i] # ripristina la situazione originaria def main(): citta = ['FI', 'MI', 'PA'] permutazioni(citta, 0) if __name__ == "__main__": main()
# Programma ALBERTI in Python # Figura 6.6 del libro "Il Pensiero Computazionale: dagli algoritmi al coding" # Autori: Paolo Ferragina e Fabrizio Luccio # Edito da Il Mulino def alberti(): """ Trasforma un messaggio nel relativo crittogramma applicando il metodo di Leon Battista Alberti, ove k e' la chiave del cifrario. """ esterno = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '1', '2', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', '3', '4', '5', 'Z'] interno = ['F', 'B', 'M', 'K', 'R', 'O', 'A', 'V', 'T', 'Z', 'Y', 'C', 'G', 'N', 'L', 'X', 'P', 'Q', 'H', 'J', 'D', 'I', 'E', 'U', 'S', 'W'] k = 0 # k (la chiave) e' l'entita' della rotazione antioraria del disco interno rispetto al disco esterno msg = raw_input('comunica il messaggio: ') # msg e' un vettore di 140 caratteri contenente il messaggio crt = [' '] * 140 # crt e' un vettore di 140 caratteri contenente il crittogramma for h in range(0, 140): if h < len(msg): i = 0 while msg[h] != esterno[i]: # cerca msg[h] in esterno i = i + 1 j = (i + k) % 26 # ora msg[h] = esterno[i] crt[h] = interno[j] if esterno[i] in ['1', '2', '3', '4', '5']: k = (i + k) % 26 # msg[h] e' un carattere speciale: l'operazione aggiorna la chiave print ''.join(crt) def main(): alberti() if __name__ == "__main__": main() """ Esempio di interazione con l'utente python alberti.py comunica il messaggio: BUONA3SERA BDLNFELFNE Process finished with exit code 0 """
# Programma RICERCA_BINARIA in Python # Figura 2.8 del libro "Il Pensiero Computazionale: dagli algoritmi al coding" # Autori: Paolo Ferragina e Fabrizio Luccio # Edito da Il Mulino # carica le funzioni matematiche import math def ricerca_binaria(insieme, dato): """ Ricerca binaria di un elemento dato in insieme :param insieme: insieme su cui ricercare (ordinato) :param dato: dato da ricercare """ # n indica il numero di elementi di insieme n = len(insieme) i = 0 j = n - 1 while i <= j: # math.floor() restituisce l'intero <= x piu' vicino a x # int() rimuove la virgola # m e' la posizione centrale tra i e j m = int(math.floor((i + j) / 2)) if dato == insieme[m]: print "%s e' presente" % dato return if dato < insieme[m]: j = m - 1 if insieme[m] < dato: i = m + 1 print "%s non e' presente" % dato def main(): citta = ['FI', 'MI', 'PA', 'NA', 'BO', 'TO', 'VE', 'CA'] ricerca_binaria(citta, 'NA') ricerca_binaria(citta, 'RC') if __name__ == "__main__": main()
# Programma TH_ITER in Python # Figura 10.5 del libro "Il Pensiero Computazionale: dagli algoritmi al coding" # Autori: Paolo Ferragina e Fabrizio Luccio # Edito da Il Mulino def th_iter(n, p): """ Algoritmo iterativo per risolvere il problema della Torre di Hanoi L'ordine in cui si considerano i pioli e' diverso per n pari o dispari. :param n: numero dischi :param p: vettore di pioli """ k = 0 index = 1 if n % 2 == 1 else 2 # se n e' dispari, A,B,C, altrimenti A,C,B iter_index = 0 while len(p[index]) < n: print iter_index, p[0], p[1], p[2] # sposta il 1 disco p[(k + 1) % 3].append(p[k].pop()) # esegue lo spostamento possibile di un disco tra i rimanenti pioli if (len(p[k]) > 0) and (len(p[(k + 2) % 3]) > 0): if p[k][-1] < p[(k + 2) % 3][-1]: p[(k + 2) % 3].append(p[k].pop()) else: p[k].append(p[(k + 2) % 3].pop()) elif (len(p[k]) > 0) and (len(p[(k + 2) % 3]) == 0): p[(k + 2) % 3].append(p[k].pop()) elif (len(p[k]) == 0) and (len(p[(k + 2) % 3]) > 0): p[k].append(p[(k + 2) % 3].pop()) k = (k + 1) % 3 iter_index = iter_index + 1 def main(): a = [5, 4, 3, 2, 1] b = [] c = [] p = [a, b, c] th_iter(len(a), p) print '' print a print b print c if __name__ == "__main__": main()
# Programma CARICA_RICERCA in Python # Figura 2.6 del libro "Il Pensiero Computazionale: dagli algoritmi al coding" # Autori: Paolo Ferragina e Fabrizio Luccio # Edito da Il Mulino # copia il programma ricerca2 dal file precedente from ricerca2 import ricerca2 def carica_ricerca(): """ Programma per interrogare il computer sull'informazione associata ai nomi di un elenco attraverso la chiamata di ricerca2 :return: """ citta = ['FI', 'MI', 'PA', 'NA', 'BO', 'TO', 'VE', 'CA'] prefissi = ['055', '02', '091', '081', '051', '011', '041', '070'] # cerca e' un parametro di controllo. # Per cerca == 'VAI' la ricerca prosegue # Per cerca == 'ALT' la ricerca si arresta cerca = 'VAI' while cerca == 'VAI': nome = raw_input('comunica il dato da cercare: ') ricerca2(citta, prefissi, nome) cerca = raw_input('vuoi continuare la ricerca? ') def main(): carica_ricerca() if __name__ == "__main__": main() """ Esempio di interazione con l'utente python carica_ricerca.py comunica il dato da cercare: NA l'informazione di NA e' 081 vuoi continuare la ricerca? VAI comunica il dato da cercare: RG RG non e' presente vuoi continuare la ricerca? ALT Process finished with exit code 0 """
for value in range(0,5): print(value) #list将range转换为列表 numbers=list(range(1,6)) print(numbers) squares=[] for value in range(1,9): square=value**2 squares.append(square) print(squares) print(min(squares)) print(max(squares)) print(sum(squares)) ##元组的元素不可更改,但是元组可以重新赋值 dimensions=(1,2) #dimensions[0]=2 dimensions=(2,3)
# Electronic Phone Book # ===================== # 1. Look up an entry # 2. Set an entry # 3. Delete an entry # 4. List all entries # 5. Quit # What do you want to do (1-5)? # If they choose to look up an entry, you will ask them for the person's name, and then look up the person's phone number by the given name and print it to the screen. # If they choose to set an entry, you will prompt them for the person's name and the person's phone number, # If they choose to delete an entry, you will prompt them for the person's name and delete the given person's entry. # If they choose to list all entries, you will go through all entries in the dictionary and print each out to the terminal. # Search for an entry # You can limit this to Name, or loop through the entire dictionary # If they choose to quit, end the program. # Example session: # $ python phonebook.py # Electronic Phone Book # ===================== # 1. Look up an entry # 2. Set an entry # 3. Delete an entry # 4. List all entries # 5. Search for an entry # 6. Quit # What do you want to do (1-5)? 2 # Name: Melissa # Phone Number: 584-394-5857 # Entry stored for Melissa. # Psuedo_Code: What do I need to do to create a basic phonebook app? First, I need to create a phonebook, and for that, # I'll use a dictionary for storing the data. I'll make only a few entries, and then once the app is complete, actually # use it to store additional entries. # 1. Make a phonebook with 5 entries # 2. phonebook = { "BRENDAN BRODY": "716-935-9264", #The dashes are casuing numbers to print wrong. How to fix w/o making a string?? "ELLEN BRODY": "716-982-9404", "HANNAH DUANE": "716-597-9296", "STEVEN DUANE": "716-432-2939", "SHIRLEY DUANE": "716-598-0220" } from time import sleep def welcome(): user_name = "Katie" print "Welcome to your phonebook, %s, what would like to do today?" % user_name sleep(1) print """ 1. Look up an entry 2. Set an entry 3. Delete an entry 4. List all entries 5. Quit """ " " # what the hell is a way to create a space/line break? nothing works! def look_up_entry(): name = raw_input("Type first and last name: ").upper() if name not in phonebook: print "Contact not found, try again." else: print phonebook.get(name) def add_contact(): print "Great, you'd like to add a new contact!" contact_name = raw_input("Type the first and last name of your contact: ") contact_entry = contact_name.upper() contact_num = raw_input("Enter your contact's number xxx-xxx-xxxx ") if len(contact_num) == 12: phonebook[contact_entry] = contact_num print "Contact added!" else: print "Error with phone number. Please try again." # Do I need a loop to insert logic to try again? def delete_contact(): contact_to_delete = raw_input("Type the first and last name of the contact you want to remove: ") contact_to_delete = contact_to_delete.upper() if contact_to_delete in phonebook: del phonebook[contact_to_delete] print "Contact deleted" else: print "Contact not found, try again" #Logic to try again? start = True def quit_prompt(): # This doesn't work right... doesn't print 'exiting' and doesn't actually change the boolean to stop the while loop... quit_op = raw_input("Would you like to something else or quit? Enter Q for Quit or C to continue using your phonebook: ") quit_op = quit_op.upper() if quit_op == "Q": print "Exiting..." start = False else: pass def start_phonebook(): # I need to work on how it reprints the welcome/prompts fter the user hits a number and then finishes entering. Like adding a quit or return to menu prompt or something... while start == True: welcome() user_choice = int(raw_input("Enter a number from the list: ")) if user_choice == 1: look_up_entry() quit_prompt() elif user_choice == 2: add_contact() quit_prompt() elif user_choice == 3: delete_contact() quit_prompt() elif user_choice == 4: print phonebook quit_prompt() elif user_choice == 5: # couldn't seem to create this outside the function, as 'start' was not defined quit_prompt() else: print "Option not found. Choose from 1-5" # phonebook["Maria Luna"] = "123-457-7890" ***HMMMMMM. as soon as i comment out this code, these contacts vanish from the dictionary! # phonebook["Planet Jupiter"] = "098-765-4321" # sample = "John Smith" # sample_num = "111-111-1111" # del phonebook[sample] # phonebook[sample] = sample_num # sample = "Lisa Greene" # sample_num = "111-111-1111" # phonebook.update({sample:sample_num}) # sample = "Shirley Duane" # print phonebook.get(sample) # search = phonebook.get() # print search # look_up_entry() # add_contact() # delete_contact() start_phonebook() # print phonebook
# Inheritance! class Car(object): def __init__(self, make, model, mpg): self.make = make self.model = model self.mpg = mpg def startCar(self): print "%s goes vroom!" % self.make myCar = Car('Ford', 'Fpics', 40) myCar.startCar() class Electric_Car(Car): # call this object's constructors def __init__(self, make, model, battery): # call Super class constructor super(Electric_Car, self).__init__(make, model, None) # could also say Car().__init__(make, model. "N/A") self.battery = battery # we can override a parent/super method def startCar(self): print "%s goes pssshhhhhhh!" % self.make car1 = Car("Toyota", "Camry", 35) car2 = Electric_Car("Tesla", "S", "100kh") print car1.model car2.startCar()
from tkinter import * class App: def __init__(self,master): frame=Frame(master) frame.pack() self.button=Button(frame, text="Quit",fg="green",command=quit) self.button.pack(side=LEFT) self.slogan=Button(frame, text="hello Button", command = self.write_slogan) self.slogan.pack(side=LEFT) def write_slogan(self): print("tkinter is easy to use") root = Tk() app=App(root) root.mainloop()
from tkinter import * import os creds ="tempfile.txt" def signup(): global pwordE global nameE global roots roots = Tk() roots.title("Sign Up") instruction = Label(roots,text="Please enter your credentials\n") instruction.grid(row=0,column=0,sticky=E) namel = Label(roots,text="New Username: ") pwordl = Label(roots,text="New Password: ") namel.grid(row=1,column=0,sticky=W) pwordl.grid(row=2,column=0,sticky=W) nameE = Entry(roots) pwordE = Entry(roots,show="*") nameE.grid(row=1,column=1) pwordE.grid(row=2,column=1) signupButton = Button(roots,text="Sign Up",command=FSSignup) signupButton.grid(columnspan=2,sticky=W) roots.mainloop() def FSSignup(): with open(creds,"w") as f: f.write(nameE.get()) f.write("\n") f.write(pwordE.get()) f.close() roots.destroy() login() #### LOGIN #### def login(): global nameEL global pwordEL global rootA rootA = Tk() rootA.title("Login") instruction=Label(rootA,text="Please Log-in\n") instruction.grid(sticky=E) nameL =Label(rootA,text="Username: ") pwordL =Label(rootA,text="Password: ") nameL.grid(row=1,column=0) pwordL.grid(row=2,column=0) nameEL = Entry(rootA) pwordEL = Entry(rootA,show="*") nameEL.grid(row=1,column=1) pwordEL.grid(row=2,column=1) loginB = Button(rootA,text="Login", command=check_login) loginB.grid(columnspan=2, sticky=W) rmuser=Button(rootA,text="Delete User",fg="blue",command=del_user) rmuser.grid(columnspan=2,sticky=W) rootA.mainloop() ## CHECK LOGIN ## def check_login(): with open(creds) as f: data = f.readlines() uname = data[0].rstrip() pword = data[1].rstrip() if nameEL.get() == uname and pwordEL.get() == pword: r = Tk() r.title("Welcome") r.geometry("150x150") rlabel= Label(r,text="Logged In") rlabel.pack() rlabel.mainloop() else: r=Tk() r.title("Oops") r.geometry("150x150") rlabel= Label(r,text="\n[!]Invalid Login") rlabel.pack() r.mainloop() ## DELETE USER ## def del_user(): os.remove(creds) rootA.destroy() signup() if os.path.isfile(creds): login() else: signup()
# coding=utf-8 import sys class SelfListNode(object): def __init__(self,value,next_node): self.node_value = value self.next = next_node def self_print(head): while head != None: print head.node_value head = head.next def self_revert(head): result = None; # result是用来保存最后的节点头的 # head就一直保存要翻转的节点 while head!=None: temp = head.next # 先拿到下一个节点,保存起来,这个就是下一个要翻转的节点 head.next = result # result = head # result是上个节点, head = temp # head就是下一个了 return result # 实现从数组中构造链表出来 def self_build(data_array): if data_array == None or len(data_array) <=0: return None last = None # 逆序遍历 for x in data_array[::-1]: current = SelfListNode(x,last) last = current return current if __name__ == '__main__': list_head = self_build([1,2,3,4,5,6,7]) SelfListNode.self_print(list_head) SelfListNode.self_print(self_revert(list_head))
accounts = open("Usernamelist.txt", "r+") print("Hello human!") username = input("insert your username and password ") if username in accounts: print("Access completed") else: error = input("Username not found, if you are new, type \"sign up\" if you want to try login again, type \"login\" ") if error == "sign up": sign_up = input("Enter a new username and a new password ") while sign_up in accounts: sign_up = input("Username taken, try again! ") else: accounts.write(sign_up) elif error == "login": username = input("insert your username and password ") else: print("Invalid Input")
from math import * #Calculating range until inputed number num = int(input("Input a number: ")) sum = 0 for i in range(num+1): sum = sum + i print("The sum is ", sum)
#Apartments price apartments_price = 1 apartments = [] sum_apartments = 0 while apartments_price > 0: apartments_price = int(input("Apartment price: ")) if apartments_price > 0: sum_apartments = sum_apartments + 1 apartments.append(apartments_price) print("Apartment ", sum_apartments, "price: ", apartments_price) else: print("Now enter rent price. ") break sum_price = 0 i = 0 for i in range(len(apartments)): sum_price = sum_price + apartments[i] average = sum_price / sum_apartments print(sum_apartments, "apartments have been registered. The average price for rent is", average) price = 1 while price > 0: price = int(input("Rent price: ")) if price > average: print("Above average price!") elif price == average: print("Same as average price!") elif 0 < price < average: print("Belove average price!") else: print("Quit!")
#Garage company drivers = 0 earnings = 0 while drivers >=0: member = input("Are you a member? (yes/no): ") if member == "yes": cost = 1.5 elif member == "no": cost = 3 hours = int(input("How many hours you have been parked?: ")) if 0 < hours <= 1: hours_cost = 2 elif 1 < hours <= 2: hours_cost = 3.5 elif 2 < hours <= 3: hours_cost = 4.5 else: hours_cost = 4.5 + (hours - 3)*0.5 price = cost + hours_cost print("Total amount is: ", price, "$") drivers = drivers + 1 earnings = earnings + price more = input("Do you want do continue? (yes/no)") if more == "no": print(drivers, "Driver payed. The total earnings are", earnings, "$") break
# This function set two values. def main(): print('The sum of 12 and 45 is') n1 = 12 n2 = 45 total = sum(n1, n2) print(total) # This function accepts two values and return the sum. def sum(x1, x2): result = x1 + x2 return(result) # Calling the main program. main()
# Simple I/O Program # Name: Deborah Barndt / pgm1 print("Welcome to Python Programming!") print("I'm here to assist\n") FullName = "Jane Doe" num1 = 88.581 print(format(num1, '7.2f')) print(format(num1, '15.2f')) amount_due = 5000.0 monthly_payment = amount_due / 12 # Divide the amount due by 12 print('The monthly payment is', \ format(monthly_payment, '.2f')) name = input('What is your name: ') age = int(input('How old are you: ')) income = float(input('What is your income: ')) income = eval(input('What is your income: ')) print('Income: %.2f' % income) ''' This is line1 This is line2 This is line3 '''
''' This program demonstrates Python GUI. Name: Deborah ''' import tkinter as tk win = tk.Tk() win.title('Python GUI') tk.Label(win, text = 'A Label').grid(column = 0, row = 0) def click_me(): action.configure(text = '*** I have been clicked! ***') action = tk.Button(win, text = 'Click Me!', command = click_me) action.grid(column = 1, row = 0) # Start the program. win.mainloop()
''' Deborah Barndt 4-3-19 TestMain.py hw9: Coffee Vending Machine This program will create a vending machine that will tell the user how many cups of coffee are available, the cost of one cup of coffee, and the total amount of money that the user inserted into the machine. The machine will require exact change. Written by Deborah Barndt. ''' from VendingMachine import CoffeeVendingMachine def testmain(): option = '' quantity = 10 cost = 0.50 vendingMachine = CoffeeVendingMachine(quantity, cost) print('\n\nWelcome to the Coffee Vending Machine.') while option.lower() != 'exit': option = input('Please select an option from the menu by number or name:\n' '1. Menu\n' '2. Insert Money\n' '3. Select Coffee\n' '4. Refund Money\n' '5. Exit\n\n' 'Select Option: ') # If statement for each of the options on the menu. if (option.lower() in '1. menu'): vendingMachine.menu() elif (option.lower() in '2. insert money'): # Ask user to enter the number of quarters, dimes, and nickels they are inserting. quarters = int(input('Enter the number of quarters inserted: ')) dimes = int(input('Enter the number of dimes inserted: ')) nickels = int(input('Enter the number of nickels inserted: ')) vendingMachine.insert(quarters, dimes, nickels) elif (option.lower() in '3. select coffee'): vendingMachine.select() elif (option.lower() in '4. refund money'): vendingMachine.refund() elif (option.lower() in '5. exit'): break else: print('Your input is invalid. Please enter a number or name from the menu.\n') print('Thank you for using the Coffee Vending Machine.') # Call testmain function to begin program. testmain()
''' Deborah Barndt 2-6-19 CreditCardNumberValidation.py hw3: Financial: Credit Card Number Validation This program will ask the user to input their credit card number, then will use Hans Luhn's algorithm to check if the card is valid or not valid. Once the result is displayed, it will ask the user if they would like to check another credit card number. The algorithm is useful to determine whether the card number is entered correctly or whether a credit card is scanned correctly by a scanner. The following steps are used to check the credit card numbers: double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single-digit number, add all the single-digit numbers from the first step, add all the digits in the odd places from right to left in the card number, sum the results from the second and third steps, and if the result from the fourth step is divisible by 10, the card number is valid; otherwise it is invalid. Written by Deborah Barndt. ''' # Main function to ask the user to enter a credit card number, then tell them if it # is a valid or not valid credit card number and ask if they want to check another. def main(): checkAgain = 'y' while (checkAgain == 'y'): number = int(input('Enter a credit card number between 13 and 16 digits: ')) if isValid(number): print(number, 'is valid.') # Ask user if they would like to check another credit card. checkAgain = input('Would you like to check another credit card? (y/n) ') else: print(number, 'is not valid.') # Ask user if they would like to check another credit card. checkAgain = input('Would you like to check another credit card? (y/n) ') # Return true if the card number is valid. def isValid(number): return getSize(number) >= 13 and getSize(number) <= 16 and \ (prefixMatched(number, 4) or prefixMatched(number, 5) or \ prefixMatched(number, 37) or prefixMatched(number, 6)) and \ (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0 # Get the result from Step 2. def sumOfDoubleEvenPlace(number): sum = 0 number = number // 10 while (number != 0): sum += getDigit((number % 10) * 2) number = number // 100 return sum # Return this number if it is a single digit, otherwise, return the sum # of the two digits. def getDigit(number): return number % 10 + (number // 10) # Return sum of odd place digits in number. def sumOfOddPlace(number): sum = 0 while (number != 0): sum += number % 10 number = number // 100 return sum # Return true if the digit d is a prefix for number. def prefixMatched(number, d): return getPrefix(number, getSize(d)) == d # Return the number of digits in d. def getSize(d): length = 0 while (d != 0): length += 1 d = d // 10 return length # Return the first k number of digits from number. If the number of digits # in number is less than k, return number. def getPrefix(number, k): total = number for digit in range(getSize(number) - k): total //= 10 return total # Calling the main function to check the credit card number. main()
''' Deborah Barndt 2-20-19 AlgebraMatrix.py hw5: Question 2 Algebra Matrix This program will prompt a user to enter two 3 x 3 matrices and display their product. Written by Deborah Barndt. ''' # Function that will multiply two matrices given by the user. def multiplyMatrix(a, b): rowA = len(a) colA = len(a[0]) rowB = len(b) colB = len(b[0]) if (colA != rowB): print('You entered the wrong dimensions for matrices.') return result = [[0 for row in range(colB)] for col in range(rowA)] # For loop to iterate through each of the rows and columns. for i in range(rowA): for j in range(colB): for k in range(colA): result[i][j] += round(a[i][k] * b[k][j], 1) return result # Function to prompt the user to enter the two 3 x 3 matrices and displays # the product. def userMatrix(num): userinput = input('Enter a matrix with spaces for matrix' + str(num) + ': ').split() userinput = list(map(float, userinput)) total = len(userinput) row = int(total ** 0.5) matrix = [userinput[i:i + row] for i in range(0, total, row)] return matrix # Function that will store the input into both matrices. def main(): matrix1 = userMatrix(1) matrix2 = userMatrix(2) productMatrix = multiplyMatrix(matrix1, matrix2) display = [[' ', ' '], ['* ', '= '], [' ', ' ']] print('The multplication of the matrices is:\n') for i in range(len(matrix1)): print(str(matrix1[i][0]) + ' ' + str(matrix1[i][1]) + ' ' + str(matrix1[i][2]) + '\t ' + display[i][0] + str(matrix2[i][0]) + ' ' + str(matrix2[i][1]) + ' ' + str(matrix2[i][2]) + '\t ' + display[i][1] + str(productMatrix[i][0]) + ' ' + str(productMatrix[i][1]) + ' ' + str(productMatrix[i][2])) # Call the main function to begin the program. main()
''' These are just storing some basic data structure and algorithms. After I practice leetcode, I'll add more to here. ''' import numpy as np # find x, or find the last element that is smaller than x def BinarySearch(array,x): l = 0 r = len(array)-1 while l < r: mid = l+(r-l)/2 if array[mid] < x: l = mid + 1 elif array[mid] > x: r = mid - 1 else: return (mid, array[mid]) return (r, array[r]) # find the first element that is not smaller than x def lower_bound(array,x): if array[-1]<x: return None l = 0 r = len(array)-1 while l < r: mid = l+(r-l)/2 if array[mid] < x: l = mid + 1 else: r = mid return (r, array[r]) if __name__=="__main__": d=[1,2,2,2,2,360,900,2000] idx, val = lower_bound(d, 2) print(idx, val) idx, val = lower_bound(d, 2+0.001) print(idx, val) idx, val = BinarySearch(d, 2) print(idx, val) idx, val = BinarySearch(d, 2+0.001) print(idx, val)
#!/usr/bin/python3 for character in range(97, 123): if character is 113 or character is 101: continue else: print("{}" .format(chr(character)), end="")
#!/usr/bin/python3 def uppercase(str): for character in str: if ord('a') <= ord(character) <= ord('z'): character = chr(ord(character) + (ord('A') - ord('a'))) print("{:s}" .format(character), end="") print("")
#!/usr/bin/python3 """ mod 1-my_list contains class MyList """ class MyList(list): """ define Mylist Class """ def __init__(self): """ init the object """ super().__init__() def print_sorted(self): """ prints sorted list """ print(sorted(self))
#coding:utf-8 import time def usetimeDecorate(fun): def wrapper(num_list): start_time = time.time() num_list = fun(num_list) print "Time:",time.time() - start_time return num_list return wrapper def insertionSort(num_list): """ 插入排序 思想:首先认为第一个数已经排好序,我们应该从第二个数开始,和前边排好序的数列的数据进行比较。 首先将需要比较的数选出来;获得比较数的index索引值。 根据需要,比较当前index的数和index索引递减的数。 假如是递增数列,大数在后: 如果index的数小:就和前边的数交换(由于是递减比较 ,所以每次交换的都是相邻的数据位的值),然后继续向前比较。 如果index的数大,就不用和前边交换,而且也不用再比较,因为前面的数列已经排序好。 """ print("插入排序一:"), for index in range(1,len(num_list)):#每轮比较的数据索引,从第二个元素开始 value = num_list[index] #挑选出需要比较的数据 i = index - 1 #获得比较数据的前一个数据,作为比较的开始 while i >= 0: if value < num_list[i]: #从小到大排序 num_list[i+1] = num_list[i] num_list[i] = value i = i - 1 else: #直接退出,因为前边已经排好序列。 break return num_list def insertionSort2(num_list): """ 简化的插入排序 """ print("插入排序二:"), for index in range(1,len(num_list)): value = num_list[index] i = index - 1 while i>=0 and (value < num_list[i]): num_list[i+1] = num_list[i] num_list[i] = value i = i-1 return num_list def insertionSort3(num_list): """ 插入排序,num_list[0]已经排序好,共num_list[1]到最后num_list[-1],每次挑选出一个之,与每个值之前排序好的数列进行比较; 如果不符合大小规则,就将临近的连个值进行交换(其中一个是挑选出的值)。 如果符合就跳出,不再继续向前,因为前边已经排序。 接着挑选下一个需要比较的值,与前面进行比较。 """ print("插入排序三:"), for index in xrange(1,len(num_list)): while index >0: #5)跳出 if num_list[index-1] > num_list[index]: #1)比较 num_list[index],num_list[index-1] = num_list[index-1],num_list[index] #2)交换 index = index - 1 #3)向前比较 else: break #4)已经排好序 return num_list def bubbleSort(num_list): """ 冒泡排序:选择第一个元素和第二个元素进行比较,如果不符合规则就交换 然后第二个和第三个,以及第三个和第四个。。。 相邻的进行比较,最后将极值放到最后。 比较的轮数;j = n-1 每轮比较的次数:n-1-j """ print("冒泡排序一:"), for j in xrange(len(num_list)-1): for i in xrange(len(num_list)-1-j):#第一轮比较到n-1,第二轮比较到n-1-1 if num_list[i] > num_list[i+1]: num_list[i] ,num_list[i+1] = num_list[i+1],num_list[i] return num_list def bubbleSort2(num_list): """ 先考虑一轮,最后的数为最值,已经排好序 考虑下一轮,最后一个值不用比较 """ print("冒泡排序二:"), for j in xrange(1,len(num_list)): for i in xrange(len(num_list)-j): if num_list[i] > num_list[i+1]: num_list[i] ,num_list[i+1] = num_list[i+1],num_list[i] return num_list def shellSort(num_list): """ 希尔排序:改进的插入排序,不稳定。插入排序在初始的数据有序时,速度较快。为了在初始数比较乱时有更快的排序速度,就有了希尔排序。 希尔排序基本思想:首先选择一个步长,步长的两个值进行对比: 1)对于大于步长的值可以逆向递减比较。(1)起始元素<--->起始元素索引+步长所在的元素。(2)起始元素+1<-->起始元素索引+步长所在的元素+1.。。。直到起始元素+1<步长(3)对于后边的元素进行逆向的递减步长判断 2)或者进行步长的再次扩张进行比较。(1)起始元素<--->起始元素索引+步长所在的元素。(2)起始元素索引+步长+步长所在的元素。。。。(3)对于后边的元素进行逆向的递减步长判断 最后当步长为1的时候,就是对整个序列进行排序。 步长的停止:最后一次的子列表,为分到步长的前一个元素。 程解思想: 首先设置步长为整个序列的一半(整除),然后每次减少一个步长,直到步长为0,退出。 比较方法: 当前元素i,步长step_size s首先比较从num_list[i]到num_list[step_size-1], 对于后边没有比较到的,及索引值大于2*step_size-1的,每取一个值,就跟前边减去步长的对应的元素进行比较。 例子: [4,6,3,8,1] 步长为2 4-3 6-8 比较 [3,6,4,8,1] 然后比较1-4 ,如果没有发生交换,就不用继续向前比较。 [3,6,1,8,4] 然后比较3-1 [1,6,3,8,4] 步长减少1,为1 []1-6不变;3--6交换[1,3,6,8,4];3-1不变;8-6不变;4-8交换[1,3,6,4,8];4-6交换[1,3,4,6,8] """ print("希尔排序一:"), length_list = len(num_list) step_size = length_list/2 while step_size >0: #进行步长间的值的比较 for i in range(step_size): if num_list[i] > num_list[i+step_size]: num_list[i],num_list[i+step_size] = num_list[i+step_size],num_list[i] # 比较超过一个步长的值 i+=1 while i+step_size < length_list: if num_list[i] > num_list[i+step_size]: num_list[i], num_list[i+step_size] = num_list[i+step_size], num_list[i] index = i - step_size while index >= 0: if num_list[index] > num_list[index + step_size]: num_list[index], num_list[index + step_size] = num_list[index + step_size], num_list[index] index = index - step_size else: break i+= 1 # 每次步长递减 step_size -= 1 return num_list def shellSort2(num_list): """ 每次比较的时候,根据步长来比较,最后一次比较的步长为1 每次比较的时候,选取基准索引和索引+一个或者多个步长的元素进行比较。 """ print("希尔排序二:"), length_list = len(num_list) step = length_list/2 while step>0: for i in range(step): index = i while index+step < length_list: #判断i,i+step,i+step+step。。。一直判断到最后的索引+step大于list的长度。取得值是 从第i个元素和对应的i+多个步长所在的元素。 # print num_list, num_list[index],num_list[index+step] if num_list[index] > num_list[index+step]: num_list[index],num_list[index+step] = num_list[index+step],num_list[index] index = index+step step -= 1 return num_list def shellSort3(num_list): """ 正确的希尔排序: 步长的选择是希尔排序的重要部分。只要最终步长为1任何步长序列都可以工作。 当步长为1时,算法变为插入排序,这就保证了数据一定会被排序。 Donald Shell最初建议步长选择为 n/2,并且对步长取半直到步长达到1。 排序思想:先选取步长的元素进行比对(插入排序),通过逐渐减少步长(步长的选取最后一次一定为1--插入排序)来进行排序。 是改进的插入排序,插入排序在数据有序的时候排序的速度会更快。因为插入排序比较的是前边已经排序好的序列。 """ print("希尔排序三:"), length_list = len(num_list) step = length_list/2 while step > 0: for index in range(0,step): #进行某个步长内的元素的遍历排序。 while index+step < length_list: while index>=0: #插入排序,和前边的已经排序好的比较. if num_list[index] > num_list[index+step]: num_list[index],num_list[index+step] = num_list[index+step],num_list[index] index = index - step #选取交换的元素与前边已经排序好的元素进行比较。 else: break #前边的元素已经有序,就不用再比对(这是插入排序的重要特点) index = index + step step = step/2#每次用新的步长 return num_list def quickSort(num_list,left,right): """ 快速排序: 思想:分治法,将一个序列分成两个子序列。 1:选取第一个元素作为标尺。(看做将其取出) 2:小于标尺元素的所有元素,放在左边。大于标尺元素的所有元素,放在右边。 3:每次比较的时候,当与标尺元素进行交换的时候 ,比较的方向要发生变化,因为另一个方向的元素 是已经比较完的,所以需要变换方向。 一直比较到左,右的索引值相等。 """ if left >= right : return None key = num_list[left] #基准元素-标尺 low = left #记住需要比较的范围 high = right while left < right: while left < right and num_list[right] >= key: #当右边数据比基准数据key大 right -= 1 num_list[left]= num_list[right] #此时将数据进行交换,标尺相当于放到num_list[right]然后又取出来,所以没写。 while left < right and num_list[left] <= key: #转换比较的方向 left += 1 num_list[right] = num_list[left] num_list[right] = key quickSort(num_list,low,left-1) quickSort(num_list,left+1,high) return num_list def quickSort2(num_list): if len(num_list) == 0: return [] else: return quickSort2([x for x in num_list[1:] if x < num_list[0]]) + [num_list[0]] + quickSort2([x for x in num_list[1:] if x > num_list[0]]) def directselectSort(num_list): """ 直接选择排序:(每次选择最小的数) 基本思想:第1趟,在待排序记录r[1] ~ r[n]中选出最小的记录,将它与r[1]交换; 第2趟,在待排序记录r[2] ~ r[n]中选出最小的记录,将它与r[2]交换; 以此类推,第i趟在待排序记录r[i] ~ r[n]中选出最小的记录,将它与r[i]交换,使有序序列不断增长直到全部排序完毕。 """ print("直接选择排序:"), for i in range(len(num_list)): min = i for j in range(i+1,len(num_list)): if num_list[j] < num_list[min]: min = j if min !=i: num_list[i],num_list[min] = num_list[min],num_list[i] return num_list def heapSort(num_list): """ 堆排序(Heapsort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,它是选择排序的一种。 大根堆的要求是每个节点的值都不大于其父节点的值. 二叉树:是每个节点最多有两个子树的树结构。通常子树被称作“左子树”(left subtree)和“右子树”(right subtree) 满二叉树:一棵深度为 k,且有 2k - 1 个节点称之为满二叉树 完全二叉树:虽然不是满二叉树,但是拥有的节点和满二叉树对应。除了最底层之外,每一层都是满的。叶子从左向右。 树和二叉树的三个主要差别: 树的结点个数至少为 1,而二叉树的结点个数可以为 0 树中结点的最大度数没有限制,而二叉树结点的最大度数为 2 树的结点无左、右之分,而二叉树的结点有左、右之分 堆(二叉堆)可以视为一棵完全的二叉树 堆排序就是把最大堆堆顶的最大数取出,将剩余的堆继续调整为最大堆,再次将堆顶的最大数取出,这个过程持续到剩余数只有一个时结束。在堆中定义以下几种操作: 最大堆调整(Max-Heapify):将堆的末端子节点作调整,使得子节点永远小于父节点 创建最大堆(Build-Max-Heap):将堆所有数据重新排序,使其成为最大堆 堆排序(Heap-Sort):移除位在第一个数据的根节点,并做最大堆调整的递归运算 在完全二插树中节点的编号:父节点A,左子节点2A+1,右子节点2A+2.(节点编号从0开始,对应列表的编号。) 加入拿到一个节点编号为5,那么它的左右孩子编号为11,12,父节点的编号为2. 堆是完全二叉树,最大值在数组的第0位;在需要排序即堆排序的时候,将最大值第0位的值和最后一位的值进行交换。 然后除了最后一位重新建堆,再进行交换,最后列表都被排序。 总体实现步骤: 1:调整为最大堆:父节点大于任意一个子节点。 2:创建堆:从数组最后一个节点到根节点,进行调整为最大堆 3:堆排序:由于最大堆的最大值在第一位,将第一位和最后一位进行替换。然后重新创建堆。最后将数组都进行了排序。 """ print("堆排序:"), def heapify(A,i,size): """ 规范二叉树数据:让父节点大于子 节点 在一个子树,将最大值换到父节点的位置 :param A: 完全二叉树--堆数组 :param i: 看中的那个父节点 :param size: 节点总数(堆数组的长度)--目的是防止判断左右孩子的时候出界限 """ if i >= size: return None left = 2*i + 1 #左孩子 right = 2*i + 2 #右孩子 largest = i # 最大值 if left < size: if A[largest] < A[left]: largest = left if right<size: if A[largest] < A[right]: largest = right if largest != i:#交换判断 A[largest],A[i] = A[i],A[largest] heapify(A,largest,size) #对于交换过的子节点,进行其作为父节点的二叉树的交换比对。 def create_heapify(A,size): """ 创建堆:从最后一个节点进行堆的创建。 从堆数组最后一个节点,到根节点,对于每一个节点都做一个heapify(保证父节点值最大) :param A:堆数组 :param size:堆数组的大小 最后显示的结果中数组的第一个元素是最大的。 """ for i in range(size-1,-1,-1): #从后向前选取一个节点,比对每一个节点和其子节点,将最大值放到父节点。 heapify(A,i,size) def heap_sort(A,size): """ 堆排序 : 每次创建堆,然后堆的最大值放到最后,然后除了最后一个值,重新迭代堆的创建和最大值的提取。 :param A: 堆数组 :param size: 堆数组的大小 首先由堆A,将索引0(即最大值)和最后一个索引位置进行交换, 此时的堆长度为size-1,由于进行了交换,小的值在第一位,所以需要 重新建堆。 然后再进行最大值(index=0)和最后一位(index=-1)的交换。 """ for i in range(size-1,0,-1): #这个范围到i=1,因为i=0时,就只有一个元素,就不用对比了 create_heapify(A,i+1)#首先建立堆 A[0],A[i] = A[i],A[0] #每次将根节点和数组最后的数字进行交换 。由于堆得最大值一直是A[0],交换后的位置 就是排序好的数据。 heap_sort(num_list,len(num_list)) # create_heapify(num_list,len(num_list))#测试堆的创建 return num_list if __name__ == "__main__": num_list = [12, 44, 13, 67, 11, 556, 6,3,77] # print(insertionSort(num_list[:])) # print(insertionSort2(num_list[:])) # print(insertionSort3(num_list[:])) # print(bubbleSort(num_list[:])) # print(bubbleSort2(num_list[:])) # print(shellSort(num_list[:])) # print(shellSort2(num_list[:])) # # print(shellSort3(num_list[:])) # print("快速排序一:"), # print(quickSort(num_list[:],0,len(num_list)-1)) # print("快速排序二:"), # print(quickSort2(num_list[:])) print(directselectSort(num_list[:])) print(heapSort(num_list[:]))
import pytest class TestList: # Проверка метода len def test_list_len(self): a = list() assert len(a) == 0 # Проверка создания списка def test_list_create(self): a = list() assert a == list() # Негативный тест умножения списков def test_list_multiple(self): a = [0, 1] b = [0, 1, 2] with pytest.raises(TypeError): assert a * b # Проверка метода append @pytest.mark.parametrize('i', range(0, 3)) def test_list_append(self, i): a = [1] b = i a.append(b) assert a == [1, i] # Негативный тест эквивалентности списков def test_list_equivalence(self): a = list() b = [1, 2, 0] with pytest.raises(AssertionError): assert a == b # Негативный тест обращения списка def test_list_reverse(self): a = [0, 1, 2] a = a[::-1] with pytest.raises(AssertionError): assert a == [2, 0, 1] # Проверка копирования списка def test_list_copy(self): a = [0, 1, 2] b = list(a) assert b == [0, 1, 2]
def calculator(num1, num2, cal): if cal == "+" : return num1 + num2 elif cal == "-": return num1 - num2 elif cal == "/": return num1 / num2 elif cal == "*": return num1 * num2 num1 = int(input("숫자1 :")) num2 = int(input("숫자2 :")) cal = input("사칙연산 :") print(calculator(num1, num2, cal))
n = int(input("숫자를 입력하세요:")) for i in range(n, 0, -1): print(' '*(n -i), end ='' ) print('*'*(2*i-1))
inputed_star=int(input("별역삼각형 높이를 입력해주세요 -> ")) for i in range(inputed_star) : print(" "*i+("*"*(inputed_star*2-1-2*i)))
a = int(input("줄 수를 입력해주세요: ")) for i in range(a-1, -1, -1): print(" "*(a-i-1)+("*"*(2*i+1)))
class calculator: def sum(self, num1, num2): return num1 + num2 def sub(self, num1, num2): return num1 - num2 def mul(self, num1, num2): return num1*num2 def div(self, num1, num2): return num1/num2 class can_div_zero(calculator): def div(self, num1, num2): if num2==0: print("0으로는 나눌 수 없습니다") else: return num1/num2 can_div = can_div_zero() print(can_div.sum(1,2)) print(can_div.sub(5,3)) print(can_div.mul(4,3)) print(can_div.div(100,10)) print(can_div.div(10,0))
most_add = None most_count = None results = dict() filename = input('Enter a file name:') try: file = open(filename) except: print('Could not open file: ', filename) quit() for line in file: if line.startswith('From:'): words = line.split() print(words) results[words[1]] = results.get(words[1] , 0) + 1 for add,count in results(): if most_count == None or count > most_count: most_add = add most_count = count print(most_add, most_count)
def сollatz(n): if n % 2 == 0: return(n // 2) else: return(3 * n + 1) number = int(input('Введите целое число\n')) print() list_number = [] while number != 1: сollatz(number) number = сollatz(number) #print(number) list_number.append(number) print(list_number) print('Число итераций: ', len(list_number)) print('Минимальное значение в ходе расчёта:', min(list_number)) print('Максимальное значение в ходе расчёта:', max(list_number)) input()
from list import * import random class Implant: def __init__(self): self.implantParams = Stats() self.implantName = 'Default Implant Name' def get_name(self): return self.implantName def get_params(self): return self.implantParams.get_params() def create_by_random(self): self.implantName = "" self.implantParams = Stats() for i in range(0, 3): newWord = Words().get_random(listOfWordsDicts[i]) self.implantName = self.implantName + newWord.word + " " self.implantParams.add_params(newWord.params) return self def create_by_name(self): pass class Words: def __init__(self): self.word = "" self.params = Stats() def get_random(self, wordDict): self.word = random.choice(list(wordDict.keys())) self.params = Stats().set_params(wordDict[self.word][0], wordDict[self.word][1], wordDict[self.word][2], wordDict[self.word][3]) return self class Stats: def __init__(self): self.set_params(0,0,0,0) def set_params(self, beauty, charisma, sexuality, smart): self.beauty = beauty self.charisma = charisma self.sexuality = sexuality self.smart = smart return self def add_params(self, instanceStats): self.beauty += instanceStats.beauty self.charisma += instanceStats.charisma self.sexuality += instanceStats.sexuality self.smart += instanceStats.smart return self def get_params(self): return [self.beauty, self.charisma, self.sexuality, self.smart]
from controller import ControllerCadastro, ControllerLogin while True: print("========== [MENU] ==========") decidir = int(input('Digite 1 para cadastrar\nDigite 2 para Logar\nDigite 3 para sair\n')) if decidir == 1: nome = input('Digite seu nome') email = input('Digite seu email') senha = input('Digite sua senha') resultado = ControllerCadastro.cadastrar(nome, email, senha) if resultado == 2: print("Tamanho do nome digitado inválido") elif resultado == 3: print("Email maior que 200 caracteres") elif resultado == 4: print("Tamanho da senha inválido") elif resultado == 5: print("Email já cadastrado") elif resultado == 6: print("Erro interno do sistema") elif resultado == 1: print("Cadastro realizado com sucesso") elif decidir == 2: email = input('Digite seu email') senha = input('Digite sua senha') resultado = ControllerLogin.login(email, senha) if not resultado: print("Email ou senha inválidos") else: print(resultado) else: break
# Use logistic regression to predict if a credit card application will be approved # Project taken from DataCamp # Data taken from http://archive.ics.uci.edu/ml/datasets/credit+approval # Achieve a best score of 85.07% # Import necessary modules import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix from sklearn.model_selection import GridSearchCV # Load dataset cc_apps = pd.read_csv("cc_approvals.data", header=None) # Get summary statistics and information cc_apps_description = cc_apps.describe() cc_apps_info = cc_apps.info() # Handle missing data # Inspect missing values in the dataset # print(cc_apps.tail(17)) # Replace the '?'s (missing values) with NaN cc_apps = cc_apps.replace('?', np.nan) # Impute the missing values with mean imputation cc_apps.fillna(cc_apps.mean(), inplace=True) # Count the number of NaNs in the dataset to verify cc_apps.isnull().sum() # Iterate over each column of cc_apps for col in cc_apps.columns: # Check if the column is of object type if cc_apps[col].dtypes == 'object': # Impute with the most frequent value cc_apps = cc_apps.fillna(cc_apps[col].value_counts().index[0]) # Count the number of NaNs in the dataset cc_apps.isnull().sum() # Use label encoding # Instantiate LabelEncoder le = LabelEncoder() # Iterate over all the values of each column and extract their dtypes for col in cc_apps.columns: # Compare if the dtype is object if cc_apps[col].dtypes == 'object': # Use LabelEncoder to do the numeric transformation cc_apps[col]=le.fit_transform(cc_apps[col]) # Split data # Drop the features 11 and 13 and convert the DataFrame to a NumPy array cc_apps = cc_apps.drop([11, 13], axis=1) cc_apps = cc_apps.values # Segregate features and labels into separate variables X,y = cc_apps[:,0:13] , cc_apps[:,13] # Split into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # Scale data # Instantiate MinMaxScaler and use it to rescale X_train and X_test scaler = MinMaxScaler(feature_range=(0, 1)) rescaledX_train = scaler.fit_transform(X_train) rescaledX_test = scaler.fit_transform(X_test) # Logistic Regression # Instantiate a LogisticRegression classifier with default parameter values logreg = LogisticRegression() # Fit logreg to the train set logreg.fit(rescaledX_train, y_train) # Use logreg to predict instances from the test set and store it y_pred = logreg.predict(rescaledX_test) # Get the accuracy score of logreg model and print it print("Accuracy of logistic regression classifier: ", logreg.score(rescaledX_test, y_test)) # Print the confusion matrix of the logreg model print(confusion_matrix(y_test, y_pred)) # Fine tune the model using Grid Search # Define the grid of values for tol and max_iter tol = [0.01, 0.001, 0.0001] max_iter = [100, 150, 200] # Create a dictionary where tol and max_iter are keys and the lists of their values are corresponding values param_grid = dict(zip(['tol', 'max_iter'], [tol, max_iter])) # Instantiate GridSearchCV with the required parameters grid_model = GridSearchCV(estimator=logreg, param_grid=param_grid, cv=5) # Use scaler to rescale X and assign it to rescaledX rescaledX = scaler.fit_transform(X) # Fit data to grid_model grid_model_result = grid_model.fit(rescaledX, y) # Summarize results best_score, best_params = grid_model_result.best_score_, grid_model_result.best_params_ print("Best: %f using %s" % (best_score, best_params))
print("hello world") #this will not appear when executed print("hello") print(' hi ') print("2 + 2") print(2+2) #variables daniel = "Handsome" print(daniel) print("this guy is",daniel) apple = 10 orange = 15 basket = apple + orange bill = basket * 10 print("we've bought",apple,"apples") #text names integer value print("you've also bought",orange,"oranges") #text names integer value print("your basket is now {} fruits in it".format(basket)) # basket now has sum with {} of integers - string formatting to read!!! print("you have to pay %d Dollars" %bill) # the bill variable is the total of basket * 10 # .method is format for methods print("we have {apple} apples") print("we have{0} apple, and {1}".format(apple, orange))
# #FUNCTIONS # # def say_hi(name): # """ # This function say hi to the name # """ # print("Hi, {}".format(name)) # # # say_hi("Don") # # # print(say_hi.__doc__) # the doc is giving the text in quote marks inserted # #the doc string exists even if nothing is inserted specifically for it # # #ANNOTATIONS # # def say_hello(name: str) -> str: # """ # DOCSTRING # """ # return "Hi" + name # # print(say_hello.__doc__) # print(say_hello.__annotations__) # print() # print(say_hello(" D")) #WITH OR WITHOUT return # def add1(*args): # sum = 0 # for arg in args: # sum = sum + arg # return sum # # example1 = add1(1,2,3,4,5) # print(example1) # # def add2(*args): # sum = 0 # for arg in args: # sum = sum + arg # print(sum) # example2 = add2(1,2,3,4,5) # # def add3(*args): # sum = 0 # for arg in args: # sum = sum + arg # # example3 = add3(1,2,3,4,5) # print(example3) # # def missing_char(str, n): # return str[0:n]+str[n+1:len(str)-1] # return str.replace(str[n],"") # #MODULES - 3 ways of importing a file # import day4_modules as d4 or # from day4_modules import car, car_detail # print(day4_modules.car) # # car = "Audi" # manu = "Germany" # year = 2007 # # day4_modules.car_detail(car,manu,year) # import datetime as dt # print(dt.datetime) # Package = folder with many scripts that can be imported instead of a single module #CLASSES has a collection of objects/instances #instantiate is the action of interaction between objects # class PythonProgrammer(): # beard = "not so much" # pass # # daniel = PythonProgrammer() #instances of class # kim = PythonProgrammer() # # print(daniel) # print(kim) # # daniel.beard = "a lot" # # print(daniel.beard) # print(kim.beard) # class PythonProgrammer(): # course = "Python 0 to 1" # # def __init__(self, beautiful_name, nice_age, last_name): # self.name = beautiful_name # self.age = nice_age # # self.email = beautiful_name+"."+nice_age+"gmail.com" # self.email = f"{beautiful_name}.{nice_age}@gmail.com" # self.lastname = last_name # # # dev1 = PythonProgrammer("Daniel",25,"Sexton") # dev2 = PythonProgrammer("Daeun",20, "kim") # # dev1.course = "Python 0 to 2" ##class inheritance, taking a variable as the own # # if a funct is defined inside a class it becomes a method if outside it is a function # print(dev1.lastname) # print(dev1.lastname) # print(dev1.course) # print(dev1.__dict__) # print(dev2.course) # print(dev2.__dict__) # print(PythonProgrammer.course) # print(PythonProgrammer.__dict__) class Car: def __init__(self, brandname, year, origin): #there can only be one init constructor self.year = year self.origin = origin def stats(self): #regular method print("This is {}, it is made in {} in {}".format(self.brand, self.origin, self.year)) def just_for_fun(self): sel.forFun = self.brand + "is stupid!" my_car = Car("BMW", 2000, "Germany") my_friends_car = Car("Audi", 2007, "Germany") help(my_car) # # print(my_car.forFUn # my_car.stats() # my_friends_car.stats() # if a funct is defined inside a class it becomes a method if outside it is a function
import time from numpy import matrix def fib_con_matrice(n): return (matrix( '0 1; 1 1' if n >= 0 else '-1 1; 1 0', object ) ** abs(n))[0, 1] def fibonacci(n):#la funzione calcola anche l'ennesimo negativo mediante la formula F -n = (-1)^(n+1) F n dove Fn e' l'ennesimo numero positivo di fibonacci if n < 0: if (n+1)%2 != 0: return -1 * _fibspeed(abs(n))[0] else: return _fibspeed(abs(n))[0] return _fibspeed(n)[0] def _fibspeed(n): if n == 0: return (0, 1) else: a, b = _fibspeed(int(n / 2)) c = a * (2 * b - a) d = a**2 + b**2 if n % 2 == 0: return (c, d) else: return (d, c + d) start_time = time.time() a = fibonacci(20000) print(a, len(str(a))) print("--- %s seconds ---" % (time.time() - start_time))
def row_sum_odd_numbers(n): num = 0 a = ((n-1)*n)/2 for i in range (0, n): num += 2 * a + 1 a += 1 print(num) row_sum_odd_numbers(5)
import string def rot13(message): alfa_min = string.ascii_lowercase alfa_max = string.ascii_uppercase stringa = "" for car in message: if car not in alfa_min and car not in alfa_max: stringa += car else: if car in alfa_min: stringa += alfa_min[(alfa_min.index(car) + 13) % 26] else: stringa += alfa_max[(alfa_max.index(car) + 13) % 26] return(stringa) rot13("Test")
""" Three 1's => 1000 points Three 6's => 600 points Three 5's => 500 points Three 4's => 400 points Three 3's => 300 points Three 2's => 200 points One 1 => 100 points One 5 => 50 point """ from collections import Counter as ct def score(dice): a = ct(dice) a1 = list(a) a2 = list(a.values()) #print(a1,a2) somma = 0 for index in range(0, len(a1)): if(a1[index] == 1 and a2[index] >= 3): somma += 1000 a2[index] -= 3 elif(a2[index] >= 3): somma += a1[index] * 100 a2[index] -= 3 if((a1[index] == 1 or a1[index] == 5) and a2[index] < 3): if(a1[index] == 1): somma += 100 * a2[index] else: somma += 50 * a2[index] return somma rr = [2, 4, 4, 5, 4] score(rr)
def Kapracane(num): iterazioni = 0 while(num != 6174): stringa_1 = str(num) stringa_2 = str(num) stringa_1 = sorted(stringa_1, reverse = True) stringa_2 = sorted(stringa_2) stringa_1 = ''.join(stringa_1) stringa_2 = ''.join(stringa_2) num = int(stringa_1) - int(stringa_2) print(num) iterazioni += 1 return iterazioni ingresso = raw_input("inserisci il cazzo di capracane: ") try: ingresso = int(ingresso) except: print("coglione, inserisci un dato valido") exit(1) cazz = Kapracane(ingresso) print("num. iterazioni: %d" %(cazz))
""" Тестируется реакция нескольких объектов на нажатия одновременно, в том числе и когда объекты пересекаются в момент нажатия """ from state import * COUNT = 2000 BUTTON_NUM = 4 PAUSE = 1 RUN_TIME = 10 BUTTON_SETTINGS = {"lower_w": SCREEN_WIDTH/16, "lower_h": SCREEN_HEIGHT/16, "upper_w": SCREEN_WIDTH*3/16, "upper_h": SCREEN_HEIGHT*3/16, "max_speed": 20} class PressChecker: def __init__(self, state, x, y, width, height, num): self.state = state self.xs = list(np.random.rand(num) * width + x) self.ys = list(np.random.rand(num) * height + y) self.time = list(np.random.rand(num) * RUN_TIME) self.pressed = list([False] * num) self.released = list([False] * num) self.num = num self.count = 0 self.button_pressed = list([False]*len(self.state.button_list)) def raise_press(self): for i in range(self.num): if self.time[i] <= self.state.TIME and self.pressed[i] is False: self.state.on_mouse_press(self.xs[i], self.ys[i], 0, None) self.pressed[i] = True for j in range(len(self.state.button_list)): button = self.state.button_list[j] if self.xs[i] > button.center_x + button.width / 2: continue if self.xs[i] < button.center_x - button.width / 2: continue if self.ys[i] > button.center_y + button.height / 2: continue if self.ys[i] < button.center_y - button.height / 2: continue self.button_pressed[j] = True if self.time[i] + PAUSE <= self.state.TIME and self.released[i] is False: self.state.on_mouse_release(self.xs[i], self.ys[i], 0, None) for j in range(len(self.state.button_list)): if self.button_pressed[j] is True: self.count += 1 self.button_pressed[j] = False self.released[i] = True def check(self): assert self.state.count == self.count class TesState(MainMenuState): def __init__(self, window): super().__init__(window) self.count = 0 self.TIME = 0 self.press_checker = PressChecker(self, 35, 300, 150, 180, COUNT) def set_press_checker(self, press_checker): self.press_checker = press_checker def update(self, delta_time: float): self.TIME += delta_time self.press_checker.raise_press() self.press_checker.check() if self.TIME > RUN_TIME: arcade.quick_run(1) def start_new_game(self): self.count += 1 def continue_game(self): self.count += 1 def open_options(self): self.count += 1 def exit_game(self): self.count += 1 def on_draw(self): self.gui.draw() class MovingButton(MenuButton): def __init__(self, center_x, center_y, width, height, text, action_function, speed_x=0, speed_y=0): super().__init__(center_x, center_y, width, height, text, action_function) self.speed_x = speed_x self.speed_y = speed_y def update(self, timedelta): self.center_x += self.speed_x * timedelta self.center_y += self.speed_y * timedelta if self.center_x + self.width/2 >= SCREEN_WIDTH or self.center_x - self.width/2 <= 0: self.speed_x = - self.speed_x if self.center_y + self.height/2 >= SCREEN_HEIGHT or self.center_y - self.height/2 <= 0: self.speed_y = - self.speed_y class UTestState(TesState): def __init__(self, window, num_buttons, button_settings): self.num_buttons = num_buttons self.button_settings = button_settings super().__init__(window) def setup(self): self.gui = Composite() self.listeners = ListenersSupport() game_buttons = Composite() self.gui.add(game_buttons) for i in range(self.num_buttons): width = int(np.random.sample()*self.button_settings["upper_w"]+self.button_settings["lower_w"]) height = int(np.random.sample() * self.button_settings["upper_h"] + self.button_settings["lower_h"]) button = MovingButton(int(np.random.sample()*(SCREEN_WIDTH - width) + width/2), int(np.random.sample()*(SCREEN_HEIGHT - height) + height/2), width, height, "aaaaa", self.start_new_game, int(-self.button_settings["max_speed"] + self.button_settings["max_speed"]*np.random.sample()*2), int(-self.button_settings["max_speed"] + self.button_settings["max_speed"]*np.random.sample()*2)) game_buttons.add(button) self.button_list = [button for button in self.gui.get_leaves() if isinstance(button, MovingButton)] self.listeners.add_listener(ButtonListener(self.button_list)) def update(self, delta_time: float): super().update(delta_time) for button in self.button_list: button.update(delta_time) def test_presses_and_releases_everywhere(): window = Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) state = UTestState(window, BUTTON_NUM, BUTTON_SETTINGS) state.set_press_checker(PressChecker(state, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, COUNT)) window.set_state(state) window.test(60 * RUN_TIME) window.close()
""" В процессе разработки были выявлены некоторые сложности в навигации различных меню Все эти сценарии были проанализированы и упрощены Ниже рассматриваются различные сценарии пользовательских действий, а также дизайнерские решения, их покрывающие """ """ Цель: пользователь не должен тратить более трёх нажатий мышкой для выхода из игры с любого её состояния """ def test_exit(): from_main_menu = 1 # Кнопка выхода находится в главном меню from_options = from_main_menu + 1 # Есть кнопка выхода в меню from_unit_select = from_main_menu + 1 # Есть кнопка выхода в меню from_tutorial = from_main_menu + 1 # Есть кнопка выхода в меню from_fraction_select = from_main_menu + 1 # Есть кнопка выхода в меню from_game_pause = from_main_menu + 1 # Есть кнопка выхода в меню from_ended_game = from_main_menu + 1 # Есть кнопка выхода в меню from_running_game = from_game_pause + 1 # Есть кнопка паузы assert from_main_menu <= 3 assert from_options <= 3 assert from_unit_select <= 3 assert from_tutorial <= 3 assert from_fraction_select <= 3 assert from_game_pause <= 3 assert from_ended_game <= 3 assert from_running_game <= 3 """ Цель: пользователь не должен начать игру без описания управления """ def test_tutorial(): assert True # Все пути к игровому полю лежат через Tutorial """ Цель: пользователь может отключать звуковое сопровождение """ def test_music(): assert True # В настройках можно отключить как звуки нажатия клавиш, так и музыку """ Цель: пользователь оповещён, что делают кнопки """ def test_buttons_description(): assert True # Все кнопки имеют описание """ Цель: пользователь может удобно регулировать размер армии """ def test_unit_select(): is_able_to_add = True # Юниты можно добавлять is_able_to_remove = True # Юниты можно удалять is_able_to_zeroize = True # Можно сбрасывать количество юнитов is_able_to_see_decription = True # Можно посмотреть описание юнита assert is_able_to_add assert is_able_to_remove assert is_able_to_zeroize assert is_able_to_see_decription """ Цель: пользователь имеет возможность приостановить игру, отойти от компьютера и не увидеть изменений """ def test_pause(): is_pausable = True # Во время игры можно поставить паузу are_menus_constant = True # На остальных экранах в отсутствии пользователя ничего не происходит assert is_pausable assert are_menus_constant """ Цель: пользователь может начать новую игру или продолжить старую """ def test_game_saves(): new_game = True # Всегда можно создать новую игру saves_progress = True # Даже выходе из игры прогресс игрока сохраняется assert new_game assert saves_progress """ Цель: пользователь получает подсказки во время игры """ def test_hints(): is_road_highlighed = True # При выборе дороги она подсвечивается => юниты пойдут туда, куда нужно is_unit_count_shown = True # Показано количество оставшихся юнитов => не нужно запоминать, сколько юнитов было выбрано и использовано assert is_road_highlighed assert is_unit_count_shown
# -*- coding: utf-8 -*- # import logging # logging.basicConfig(level=logging.INFO) # import pdb # s = '0' # n = int(s) # # logging.info('n = %d' % n) # pdb.set_trace() # print(10/n) def fact(n): ''' Function to calculate n! Example: >>> fact(0) Traceback (most recent call last): ... ValueError >>> fact(2) 2 >>> fact(3) 6 >>> fact(10) 3628800 ''' if n < 1: raise ValueError() if n == 1: return 1 return n * fact(n - 1) if __name__ == '__main__': import doctest doctest.testmod()
# -*- coding: utf-8 -*- # class Student(object): # def __init__(self, name): # self.name = name # def __call__(self,value): # print('My name is %s %s ' % (self.name,value)) # s = Student("Michael") # import debug.py # fact(0) # from collections import deque # q = deque(['a','b','c']) # q.append('x') # q.appendleft('y') # print (q) # q.pop() # print (q) # q.popleft() # print (q) # from collections import defaultdict # dd = defaultdict(lambda :'N/A') # dd['key1'] = 'aaa' # print dd['key1'] # print dd['key2'] # from collections import Counter # c = Counter() # for ch in 'programming': # c[ch] = c[ch]+1 # # print(c) # import base64 # a = base64.b64encode(b'abcdefg') # print(a) # b = base64.b64decode(a) # print(b) import hashlib md5 = hashlib.md5() md5.update('how to use md5 in python hashlib?'.encode('utf-8')) print(md5.hexdigest())