text
stringlengths
37
1.41M
from abc import ABC, abstractmethod class MAB(ABC): """ Abstract class that represents a multi-armed bandit (MAB) """ @abstractmethod def play(self, tround, context): """ Play a round Arguments ========= tround : int positive integer identifying the round context : 1D float array, shape (self.ndims * self.narms), optional context given to the arms Returns ======= arm : int the positive integer arm id for this round """ @abstractmethod def update(self, arm, reward, context): """ Updates the internal state of the MAB after a play Arguments ========= arm : int a positive integer arm id in {1, ..., self.narms} reward : float reward received from arm context : 1D float array, shape (self.ndims * self.narms), optional context given to arms """
from random import randint def contarDigitosPares(numero): pares=0 list2=[] for i in numero: pares=0 for k in range(i-1): if (k%2==0): pares = pares + 1 else: pares = pares+0 list2.append(pares) return list2 def metodoburbuja(newlist): for i in range(1,10): for j in range (10-i): if newlist[j] >= newlist[j+1]: ordenado = newlist[j] newlist[j]=newlist[j+1] newlist[j+1]=ordenado return newlist def main(): numeros = [] for i in range(10): s = randint(10000,100000) numeros.append(s) nuevo = contarDigitosPares(numeros) x1 = metodoburbuja(numeros) x2 = metodoburbuja(nuevo) print("EL NUMERO ",x1[9]," TIENE MÁS NUMEROS PARES EN TOTAL: ",x2[2]) if __name__ == "__main__": main()
import numpy as np import sys class DType: """ Instances of `DType` represent the kind and size of data elements. The data type of a `Tensor` can be obtained via `phi.math.Tensor.dtype`. The following kinds of data types are supported: * `float` with 32 / 64 bits * `complex` with 64 / 128 bits * `int` with 8 / 16 / 32 / 64 bits * `bool` with 8 bits * `str` with 8*n* bits Unlike with many computing libraries, there are no global variables corresponding to the available types. Instead, data types can simply be instantiated as needed. """ def __init__(self, kind: type, bits: int = 8): """ Args: kind: Python type, one of `(bool, int, float, complex, str)` bits: number of bits per element, a multiple of 8. """ assert kind in (bool, int, float, complex, str, object) if kind is bool: assert bits == 8 elif kind == object: bits = int(np.round(np.log2(sys.maxsize))) + 1 else: assert isinstance(bits, int) self.kind = kind """ Python class corresponding to the type of data, ignoring precision. One of (bool, int, float, complex, str) """ self.bits = bits """ Number of bits used to store a single value of this type. See `DType.itemsize`. """ @property def precision(self): """ Floating point precision. Only defined if `kind in (float, complex)`. For complex values, returns half of `DType.bits`. """ if self.kind == float: return self.bits if self.kind == complex: return self.bits // 2 else: return None @property def itemsize(self): """ Number of bytes used to storea single value of this type. See `DType.bits`. """ assert self.bits % 8 == 0 return self.bits // 8 def __eq__(self, other): return isinstance(other, DType) and self.kind == other.kind and self.bits == other.bits def __ne__(self, other): return not self == other def __hash__(self): return hash(self.kind) + hash(self.bits) def __repr__(self): return f"{self.kind.__name__}{self.bits}" @staticmethod def as_dtype(value: 'DType' or tuple or type or None) -> 'DType' or None: if isinstance(value, DType): return value elif value is int: return DType(int, 32) elif value is float: from phi.math import get_precision return DType(float, get_precision()) elif value is complex: from phi.math import get_precision return DType(complex, 2 * get_precision()) elif value is None: return None elif isinstance(value, tuple): return DType(*value) elif value is str: raise ValueError("str DTypes must specify precision") else: return DType(value) # bool, object # --- NumPy Conversion --- def to_numpy_dtype(dtype: DType): if dtype in _TO_NUMPY: return _TO_NUMPY[dtype] if dtype.kind == str: bytes_per_char = np.dtype('<U1').itemsize return np.dtype(f'<U{dtype.itemsize // bytes_per_char}') raise KeyError(f"Unsupported dtype: {dtype}") def from_numpy_dtype(np_dtype) -> DType: if np_dtype in _FROM_NUMPY: return _FROM_NUMPY[np_dtype] else: for base_np_dtype, dtype in _FROM_NUMPY.items(): if np_dtype == base_np_dtype: return dtype if np_dtype.char == 'U': return DType(str, 8 * np_dtype.itemsize) raise ValueError(np_dtype) _TO_NUMPY = { DType(float, 16): np.float16, DType(float, 32): np.float32, DType(float, 64): np.float64, DType(complex, 64): np.complex64, DType(complex, 128): np.complex128, DType(int, 8): np.int8, DType(int, 16): np.int16, DType(int, 32): np.int32, DType(int, 64): np.int64, DType(bool): np.bool_, DType(object): np.object, } _FROM_NUMPY = {np: dtype for dtype, np in _TO_NUMPY.items()} _FROM_NUMPY[np.bool] = DType(bool) def combine_types(*dtypes: DType, fp_precision: int) -> DType: # all bool? if all(dt.kind == bool for dt in dtypes): return dtypes[0] # all int / bool? if all(dt.kind in (bool, int) for dt in dtypes): largest = max(dtypes, key=lambda dt: dt.bits) return largest # all real? if all(dt.kind in (float, int, bool) for dt in dtypes): return DType(float, fp_precision) # complex if all(dt.kind in (complex, float, int, bool) for dt in dtypes): return DType(complex, 2 * fp_precision) # string if any(dt.kind == str for dt in dtypes): largest = max([dt for dt in dtypes if dt.kind == str], key=lambda dt: dt.bits) return largest raise ValueError(dtypes)
# Author: Abhi Patel # Date: 12/25/17 # Purpose: To implement an algorithm of Arnold's Cat Map. import cv2 import numpy as np def run(): img = cv2.imread('img/dexter.png') for i in range (1,26): img = transform(img, i) def transform(img, num): rows, cols, ch = img.shape if (rows == cols): n = rows img2 = np.zeros([rows, cols, ch]) for x in range(0, rows): for y in range(0, cols): img2[x][y] = img[(x+y)%n][(x+2*y)%n] cv2.imwrite("img/iteration" + str(num) + ".jpg", img2) return img2 else: print("The image is not square.") if __name__ == "__main__": run()
import numpy as np N=int(input()) marksheets=[] names=[] for i in range(0,N): # name=input() marks=float(input()) marksheets.append(marks) # print(marksheets) marksheets_array=np.array(marksheets) # print(np.unique(marksheets_array)) sorted_array=np.sort(marksheets_array) print(sorted_array[1]) ''' n = int(input()) marksheet = [] for _ in range(0,n): marksheet.append([input(),float(input())]) sechigh=sorted(list(set(marks for name, marks in marksheet)))[1] print("\n".join([a for a,b in sorted(marksheet) if b == sechigh])) '''
# Python program to swap two variables x = 5 y = 10 # To take inputs from the user #x = input('Enter value of x: ') #y = input('Enter value of y: ') # create a temporary variable and swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) # Python program to display universal hello program.! print('Hello World') # Find square root of real or complex numbers # Importing the complex math module import cmath num = 1+2j # To take input from the user #num = eval(input('Enter a number: ')) num_sqrt = cmath.sqrt(num) print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag)) # ########
#age 18-60 entires=int(raw_input("number of entires:")) file_out = open("details.csv","w") header = "name,age,salary\n" file_out.write(header) for x in range(entires): name=raw_input("enter name:") age=int(raw_input("enter age:")) if age>60 or age<18: print "please enter valid age." age = int(raw_input("enter age:")) sal = float(raw_input("enter salary:")) line = "%s,%s,%s\n"%(name,age,sal) print line file_out.write(line) file_out.close()
import sys def add(no1,no2): return no1+no2 no1 = int(sys.argv[1]) no2 = int(sys.argv[2]) sum = add(no1,no2) print "The sum: ",sum
"""year=2017 if (year%4)==0: print "leaf year".format(year) else: print "no leaf year ".format(year) """ import sys year=int(sys.argv[1]) if year%4==0: print "leaf year" else: print "not leaf year"
l = [1,2,3,1,2,"rama","rama"] print l l1 = set(l) print l1 for i in l1: print i new_l = list(l1) print new_l print "Types" print type(l) print type(l1) print type(new_l) print type(100) print type("Ram")
class Cal: def __init__(self,x,y): self.x=x self.y=y def add(self): return self.x+self.y def mul(self): return self.x*self.y obj=Cal(10,20) add=obj.add() mul=obj.mul() print add,mul class Cal1(Cal): def sub(self): return self.x-self.y def div(self): return self.x/self.y obj=Cal1(20,30) sub=obj.sub() add=obj.add() mul=obj.mul() div=obj.div() print add,mul,sub,div
time="30" y=time.split(":") if len(y)==3: hr=int(y[0])*60*60 min = int(y[1]) * 60 elif len(y)==2: hr=0 min = int(y[1]) * 60 else: hr=0 min=0 sec=int(y[-1]) t=hr+min+sec print t
import os,tarfile, glob import shutil string_to_search=input("Enter the string you want to search : ") all_files = [f for f in os.listdir('.') if os.path.isfile(f)] #all_files holds all the files in current directory for current_file in all_files: if (current_file.endswith(".tgz")) or (current_file.endswith("tar.gz")): tar = tarfile.open(current_file, "r:gz") file_name=os.path.splitext(current_file)[0] #file_name contains only name by removing the extension if os.path.exists(file_name): shutil.rmtree(file_name) #remove if already exists os.makedirs(file_name) #make directory with the file name output_file_path=file_name #Path to store the files after extraction tar.extractall(output_file_path) #extract the current file tar.close() #--------------Following code is to find the string from all the files in a directory-------- path1=output_file_path + r'\nvram2\logs' all_files=glob.glob(os.path.join(path1,"*")) for my_file1 in glob.glob(os.path.join(path1,"*")): if os.path.isfile(my_file1): # to discard folders with open(my_file1, errors='ignore') as my_file2: for line_no, line in enumerate(my_file2): if string_to_search in line: print("String is found in " + my_file1 + "; Line Number = " + str(line_no)) if os.path.exists(file_name): shutil.rmtree(file_name) #remove after extraction and search done
import os, glob string_to_search=input("Enter the string you want to search : ") path='nvram2\logs\*.txt' files=glob.glob(path) for current_file in files: with open(current_file) as f2: for line in f2: if string_to_search in line: print(current_file) #print file name which contains the string print(str(line)) #print the line which contains the string
class Solution: # 全排列 def permute(self, nums: List[int]) -> List[List[int]]: res = [] if not nums: return res else: self.fun(arr=[], others=nums, res=res) return res def fun(self, arr, others, res): if others == []: res.append(arr) for item in others: arr2 = arr[:] arr2.append(item) others2 = others[:] others2.remove(item) self.fun(arr2, others2, res)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: ''' 两个孩子树同时进行镜像比较 ''' def isMirror(left, right): if not left and not right: return True elif left and right: return left.val == right.val and isMirror(left.left, right.right) and isMirror(left.right, right.left) else: return False if not root: return True else: return isMirror(root.left, root.right)
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ #对于链表,分成前后两部分 #对于后一半部分,先利用头插法进行逆序 #最后再利用双指针进行合并 #pring the link def print_link(head): head = head.next if not head: return while head: print(head.val, end=',') head = head.next if not head: return head length = 0 h1 = head while h1: length += 1 h1 = h1.next h2 = head for i in range(length // 2): h2 = h2.next # new a empty head2 tmp = ListNode(0) tmp.next = h2 h2 = tmp # reverse the behind link # new another link2 link2 = ListNode(0) mark_link2 = link2 while h2.next: p = h2.next h2.next = p.next # take the p to link2 p.next = link2.next link2.next = p # print the link2 # print_link(mark_link2) # two order link h2 = mark_link2 # new a ans link h3 = ListNode(0) p3 = h3 h1 = ListNode(0) h1.next = head p, q = h1, h2 while h1.next and h2.next: if h1.next: p = h1.next h1.next = p.next p3.next = p p3 = p3.next if h2.next: q = h2.next h2.next = q.next p3.next = q p3 = p3.next p3.next = None return h3.next
# Python program to insert into a sorted linked list class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def sortedInsert(self, new_node): if self.head is None: new_node.next = self.head self.head = new_node elif self.head.data >= new_node.data: new_node.next = self.head self.head = new_node else: current = self.head while(current.next is not None and current.next.data < new_node.data): current = current.next new_node.next = current.next current.next = new_node def push(self, new_node): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while (temp): print temp.data, temp = temp.next llist = LinkedList() new_node = Node(5) llist.sortedInsert(new_node) new_node = Node(10) llist.sortedInsert(new_node) new_node = Node(7) llist.sortedInsert(new_node) new_node = Node(8) llist.sortedInsert(new_node) print "Create LinkedList" llist.printList()
print("Enter the values:" ) value_1=input("value 1: ") value_2=input("value 2: ") value_3=input("value 3: ") list1=[value_1,value_2,value_3] list1.sort() median=list1[1] print(median)
'''Pre-2018 Template Before 2018, solutions were submitted in text files with the extention `.out`. Download the approprite input files from the problem description and put them in the problem folder, then change the FILENAME variable appropriately. ''' FILENAME = "tests" def main(): with open(FILENAME + ".in") as in_file, open(FILENAME + ".out", 'w') as out_file: # Input and output filenames are determined by FILENAME variable. T = int(read(in_file)) # First line of input is the number of test cases. for i in range(1, T + 1): n, m = [int(s) for s in read(in_file).split(" ")] # Get input as specified by the problem. result = solve_problem(n, m) # Solve problem for given input. out_file.write("Case #{}: {}".format(i, result)) # Print result to output file. def read(in_file): return in_file.readline().strip() def solve_problem(a, b): return a + b if __name__ == "__main__": main()
class SkipIterator: def __init__(self, iterator): self.iterator = iterator self.skip = {} self.cursor = None self.seekCursor() # holds value which would be returned in next subsequent call def hasNext(self): return self.cursor!=None #Time Complexity: O(1) #Time Complexity: O(1) def next(self): element = self.cursor self.seekCursor() return element #Time Complexity: O(n) #Space Complexity: O(n) def Skip(self, num): if self.cursor == num: self.seekCursor() else: if num not in self.skip.keys(): self.skip[num] = 1 else: self.skip[num] = self.skip[num]+1 #Time Complexity: O(n) #Space Complexity: O(n) def seekCursor(self): self.cursor = None hasNext = next(self.iterator,None) while self.cursor == None and hasNext != None: element = hasNext if element not in self.skip: self.cursor = element break else: self.skip[element] -=1 if self.skip[element] == 0: del self.skip[element] hasNext = next(self.iterator,None) itr = SkipIterator(iter([2, 3, 5, 6, 5, 7, 5, -1, 5, 10])) # type: SkipIterator print(itr.hasNext()) # true print(itr.next()) # returns 2 itr.Skip(5) print(itr.next()) # returns 3 print(itr.next()) # returns 6 because 5 should be skipped print(itr.next()) # returns 5 itr.Skip(5) itr.Skip(5) print(itr.next()) # returns 7 print(itr.next()) # returns -1 print(itr.next()) # returns 10 print(itr.hasNext()) # returns false print(itr.next())
from steganography.steganography import Steganography from datetime import (datetime) from new import add_status # from new file import the add_status function from userdetail import Spy,chatmessage,spy,user_friend friends=["juhi","davi","savita","jyoti","sudiksha","anu","swati"]# list of friends def add_friend(): # define function for add new friend # new_friend={ # "name":" ", # "salutation":" ", # "age":0, # "rating":0.0 #} #make a dictionary for add new friend new_friend = Spy('', '', 0, 0.0) new_friend.name=raw_input("please add your friend name:") if len(new_friend.name) > 0: new_friend.salutation=raw_input("are they MR. or MS. ?:") if(new_friend.salutation.upper()) == "MR" or (new_friend.salutation.upper()) == "MS": new_friend.name=new_friend.salutation+" "+new_friend.name new_friend.age=int(raw_input("age:")) if new_friend.age > 12 and new_friend.age<50: new_friend.rating=float(raw_input("enter your rating:")) if type(new_friend.rating)==float: print("your friend name is %s and age is %s with the rating %s") %(new_friend.name,new_friend.age,new_friend.rating) friends.append(new_friend) return len(friends) else: print("sorry ! invalid entry.we can't add spy with detail you provided") return len(friends) else: print("please enter valid age") else: print("please enter the valid salutation") else: print("enter the name please") #if len(new_friend['name']) > 0 and (new_friend['age'] > 12 and new_friend < 50): # friends.append(new_friend) #return len(friends) #else: # print("sorry ! invalid entry.we can't add spy with detail you provided") # return len(friends) def select_friend(): #define function for add new friend item_number=0 for temp in friends: print ('%d %s' %((item_number+1),temp)) item_number=(item_number+1) friend_choice=int(raw_input("choice from your friends\n")) if len(friends)>=friend_choice: friend_choice_position=int(friend_choice)-1 return friend_choice_position else: print("please choose the friend again") #new_chat = { #create dictionary # "message": 'text', # "time": datetime.now(), # "send_by_me": True # } def send_message():# define function for send secrect message to friend friend_choice = select_friend() original_image = raw_input(" what is the name of the image?") output_path="output.jpg"#image with image extension text = raw_input("what do you want to say?") Steganography.encode(original_image,output_path, text) new_chat=chatmessage(text,True) user_friend.append(new_chat) print("your secret message has been ready!") def read_message():# define function to read a secrect message send by another person to the user sender=select_friend() file_n = raw_input("Enter File Name:") file_e = raw_input("Enter File extension without .") full_path = ("%s.%s") % (file_n, file_e) secret_text = Steganography.decode(full_path) print("%s Mesaage in image named: ") % (full_path) print secret_text # new_chat = { # "message": secret_text, # "time": datetime.now(), # "send_by_me": False #} new_chat=chatmessage(secret_text,False) user_friend.append(new_chat) print("your secret message has been saved!") def read_chat_history():#define function to read history of the chat read_for = select_friend() print '\n6' for chat in user_friend[read_for].chats: if chat.sent_by_me: print("[%s]%s:%s"%(chat.time.strftime("%d %B %Y"),"you said :",chat.message)) else: print("[%s]%s said:%s"%(chat.time.strftime("%d %B %Y"),user_friend.name,chat.message)) def start_chat(): #start_chat function define menu=("what do you want to do \n 1.add a status update \n 2.add a friend \n 3.select a friend \n 4.send a message \n 5.read a message \n 6.read chat history \n") menu_choice=int(raw_input(menu)) #take input from user if(menu_choice)==1: #if-elif condition are apply add_status(current_status_message) #calling add_status function elif(menu_choice)==2: add_friend() #calling the add_friend function elif(menu_choice)==3: select_friend() #calling the select_friend function elif(menu_choice)==4: send_message() #calling the send_message function elif(menu_choice)==5: read_message() #calling the read_message function elif(menu_choice)==6: read_chat_history() #calling the read_chat_history else: print("try again later") current_status_message = None #start_chat function end
import pygame import gamemode class AttractMode(gamemode.GameMode): """ Attract Mode - get the player excited to play our game """ def __init__(self, screen, game, message="Street Chase"): super().__init__(screen, game, message) # calls constructor of base class #1 self.name = "AttractMode" self.message = message def enter(self): self.active = True def update(self): #self.intro_sprite_list.update() pass def draw_frame(self): self.screen.fill([0,0,0]) pygame.display.flip() def exit(self): self.active = False
""" Python 3 solution to the Exercism exercise 'largest-series-product' """ from functools import reduce def largest_product(series, size): """ return the largest product of `size` consecutive digits fron `series` """ if size < 0: raise ValueError def product(digits): """ return the product of the numbers in a string of `digits` """ return reduce(lambda x, y: x * int(y), digits, 1) def generate_slice(): """ generate substrings of `series` that are `size` digits long """ ii = len(series) - size while ii >= 0: yield series[ii : ii + size] ii -= 1 return max(product(slice) for slice in generate_slice()) ## ## Seems simple and straight forward enough. ## ## Clever solutions were in one line with max around reduce-with-lambda being ## fed from a list comprehension based on a range. ## ## The variation went as a far as a double for loop with no library functions. ## One solution even used temporary storage. ## ## None separated the product out into a simple, clear, one line routine. ## None used a generate function as I did. ## None worked backwards through the input. ## ## None separated the three simple ideas so they could be present clearly. ##
""" Python 3 solution to the Exercism 'series' exercise """ def slices(series, length): """ return the 'set' of length n 'substrings' The tests cases require a list of lists of integers. """ result = [] if len(series) < length or length < 1: raise ValueError while len(series) >= length: result.append([int(x) for x in list(series[:length])]) series = series[1:] return result ## ## Trivial exercises but the test cases are inconsistent with the read me. ##
""" Python 3 solution to the Exercism 'rotational cypher' exercise """ LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz" UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def rotate(text, key): """ return text encrypted using key and the rotational cypher method """ key = key % 26 lower = LOWER_ALPHA[key:] + LOWER_ALPHA[:key] upper = UPPER_ALPHA[key:] + UPPER_ALPHA[:key] table = str.maketrans(LOWER_ALPHA + UPPER_ALPHA, lower + upper) return text.translate(table) ## ## New iteration that uses the translate table support of the string type. ## Someone liked this. So do I: straight line code. ##
#!/usr/bin/python3 """ an example of recursive programming Provides a script/function to calculate terms of the Fibonacci series. This example of the power of recursion has log(n) time complexity. It takes advantage of the identities: F(2n-1) = F(n) * F(n) + F(n-1) * F(n-1) F(2n) = (2 * F(n-1) + F(n)) * F(n) Deriving higher order terms by multiplication of lower order terms instead of by addition implies better than linear performance. """ __author__ = """New Forester <NewForester@users.noreply.github.com> MIT Licence @ https://opensource.org/licenses/MIT""" import sys # ------------------------------ def _internal (nth): """ Internal calculation of the nth term of the Fibonacci series Parameters - nth (integer) - the term to calculate Return - (integer, integer) - the nth and nth-1 terms """ odd = nth % 2 if nth == 1: acc = (0, 1) elif odd: acc = _internal((nth - 1) / 2) else: acc = _internal(nth / 2) acc = acc[0]*(acc[0]+2*acc[1]), acc[0]*acc[0]+acc[1]*acc[1] if odd: acc = acc[0]+acc[1], acc[0] return acc def fibonacci (nth): """ Calculate the nth term of the Fibonacci series Parameters - nth (integer) - the term to calculate Return - (integer) - the nth term """ if nth >= 1: return _internal(nth)[0] else: return 0 # ------------------------------ if __name__ == '__main__': if len(sys.argv) > 1: # Print the nth Fibonacci number calculated using recursion print(fibonacci(int(sys.argv[1]))) else: # Print the first few Fibonacci numbers using a loop nn, mm = 1, 0 while nn < 100: print(nn, end=" ") nn, mm = nn+mm, nn print(nn) # EOF
L = [1, 1, 1, 1, 4] n = 2 def getSublists(L, n): megaList = [] while len(L) > 0: if len(L[:n]) < (n // 2): sub = sub[:(n // 2)] + L[:n] else: sub = L[:n] megaList.append(sub) del L[:n] return megaList print(getSublists(L, n))
x = 24 ab = abs(x) epsilon = .01 numGuesses = 0 isNeg = False low = 0.0 high = max(1.0, ab) ans = (high+low)/2.0 while abs(ans**2 - ab) > epsilon: numGuesses += 1 if ans**2 < ab: low = ans else: high = ans ans = (high+low)/2.0 if x < 0: print('numGuesses =', str(numGuesses)) print('-' + str(ans), 'is close to the square root') else: print('numGuesses =', numGuesses) print( str(ans), 'is close to the square root')
d=int(input()) ti=0 fot=d while(fot>0): fet=fot%10 ti=ti+(fet**3) fot=fot//10 if(d==ti): print("yes") else: print("no")
# Autor: Rubén Villalpando Bremont, A01376331, grupo 4 # Descripcion: Programa que le pregunta al usuario la velocidad a la que viaja un auto y le devuelve unos datos específicos. # Escribe tu programa después de esta línea velocidad = int(input("Escriba la velocidad a la que va un vehículo en km/h: ")) distancia_7horas = velocidad*7 distanciaCuatroHorasYMedia = velocidad*4.5 tiempoQueTarda = 791/velocidad print("La distancia recorrida en 7 horas es: ", distancia_7horas, "km") print("La distancia recorrida en 4.5 horas es: ", distanciaCuatroHorasYMedia, "km") print("El tiempo que se tarda en recorrer 791km. es de ", tiempoQueTarda, "horas")
# 3. Put a # (octothorpe) character at the beginning of a line. What did it do? Try to find out what this character does. #print("Hello World!") print("Hello Again") print("I like typing this.") print("This is fun.") print('Yay! Printing.') print("I'd much rather you 'not'.") print('I "said" do not touch this.') # The octothorpe character prevents the line from being executed. This character is used to disable lines and add comments to code.
cat = "cat" tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = f"I'm \\ a \\ {cat}." fat_cat = """ I'll do a list: \t* {} food \t* Fishies \t* {}nip\n\t* Grass """ print(tabby_cat) print(persian_cat) print(backslash_cat) print(fat_cat.format(cat, cat)) print('A \'single\' quote in a single quote') print("A \"double\" quote in a double quote") print("An ASCII bell is this: \a") print("I maded an error. It should be, \"I maded\b an error.\"") print("Form\f feed") print("ASCII\nlinefeed") print("Carriage\rReturn") print("A 16-bit hex value character: \uFFFF") print("A 32-bit hex value character: \U00000001") print("I have no idea what \v (vertical tab) does") print("octal value \333") print("8 bit hex value: \xAA")
my_set = {1,3,5} my_dict ={'name':'Jose', 'age':90, 'grades':[13, 45, 66, 23, 22]} another_dict {1:15, 2:75, 3:150} #dictionary horse = { 'name': 'Tuffy', 'age': '24' } lottery_player = [ { 'name': 'Rolf', 'numbers': (13, 45, 66, 23, 22) }, { 'name': 'James', 'numbers': (14, 56, 80, 23, 22) } ] #list of dictionaries universities = [ { 'name': 'NMU', 'location': 'Michigan' }, { 'name': 'UW', 'location': 'Washington' } ] #a dictionary stores data, but does not have any methods #sum(lottery_player[0]['numbers']) #lottery_player['name'] = 'John'
class Persona: def __init__(self, nombre): self.nombre = nombre def anvanza(self): print('Ando caminando') class Ciclista(Persona): def __init__(self, nombre): super().__init__(nombre) def anvanza(self): print('Ando pedaleando') class Nadador(Persona): def __init__(self, nombre): super().__init__(nombre) def anvanza(self): print('Ando nadando') def run(): persona = Persona('Cesar') persona.anvanza() ciclista = Ciclista('Tom') ciclista.anvanza() nadador = Nadador('Michael') nadador.anvanza() if __name__ == '__main__': run()
#!/usr/bin/env python3 def security_tax(): global social_security global income_tax global after_tax global after_tax1 social_security = salary1*(0.08+0.02+0.005+0+0+0.06) if salary1 <= 3500: after_tax = salary1 - social_security elif salary1 > 3500: taxable = salary1 - social_security - 3500 if taxable <= 1500: income_tax = taxable*0.03 elif 1500 < taxable <= 4500: income_tax = taxable*0.1 - 105 elif 4500 < taxable <= 9000: income_tax = taxable*0.2 - 555 elif 9000 < taxable <= 35000: income_tax = taxable*0.25 - 1005 elif 35000 < taxable <= 5500: income_tax = taxable*0.3 - 2755 elif 55000 < taxable <= 80000: income_tax = taxable*0.35 - 5505 elif taxable > 80000: income_tax = taxable*0.45 - 13505 after_tax = salary1 - social_security -income_tax after_tax1 = format(after_tax,".2f") import sys results = [] for arg in sys.argv[1:]: salary = arg.split(':') try: salary1 = int(salary[1]) except: print("Parameter Error") else: security_tax() num_income = salary[0] + ":"+ str(after_tax1) results.append(num_income) for result in results: print(result)
# AUTHOR: GILBERT # this class is a child class of the parent class called Task # contains the objects and instance variable of the sub task a user # might want to enter from Task_class import * class Sub_task(Task): # define init function that takes in arguments def __init__(self, my_date,task_name, location, time_start_sub): super().__init__(task_name, location) self.sub_task_name = task_name self.sub_location = location self.time_start_sub = time_start_sub self.my_date=my_date # this prints out the info of the sub # task the user will enter def __str__(self): return 'Your task entered is to' + \ self.sub_task_name + 'at:' + self.sub_location + ' from' + \ ' ' + 'your spending' + 'to' + ' ' + self.time_start_sub
# -*- coding: utf-8 -*- def odd_val(n=100): a = 0; while a<=n: if a % 2 == 0: print(a,end=", ") a += 1 odd_val() print('') odd_val(10) print('') odd_val()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 9 17:20:32 2017 @author: mindovermiles262 Codecademy Python Define a new class named "Car". For now, since we have to put something inside the class, use the pass keyword. """ class Car(object): pass
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 07:14:09 2017 @author: mindovermiles262 Codecademy Python Set the variable my_variable equal to the value 10. Click the Save & Submit button to run your code """ # Write your code below! my_variable = 10
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 07:27:40 2017 @author: mindovermiles262 Codecademy Python Assign the variable total to the sum of meal + meal * tip on line 8. Now you have the total cost of your meal! """ # Assign the variable total on line 8! meal = 44.50 tax = 0.0675 tip = 0.15 meal = meal + meal * tax total = meal + meal * tip print("%.2f" % total)
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 09:39:29 2017 @author: mindovermiles262 Codecademy Python In the example above, we define a function called first_item. It has one argument called items. Inside the function, we print out the item stored at index zero of items. After the function, we create a new list called numbers. Finally, we call the first_item function with numbers as its argument, which prints out 2. """ def list_function(x): return x[1] n = [3, 5, 7] print(list_function(n))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 7 19:09:56 2017 @author: mindovermiles262 Codecademy Python Define a function called flip_bit that takes the inputs (number, n). Flip the nth bit (with the ones bit being the first bit) and store it in result. Return the result of calling bin(result). """ def flip_bit(number, n): mask = (0b1 << n-1) result = number ^ mask return bin(result)
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 09:14:28 2017 @author: mindovermiles262 Codecademy Python On line 18, define a new function called grades_variance() that accepts one argument, scores, a list. First, create a variable average and store the result of calling grades_average(scores). Next, create another variable variance and set it to zero. We will use this as a rolling sum. for each score in scores: Compute its squared difference: (average - score) ** 2 and add that to variance. Divide the total variance by the number of scores. Then, return that result. Finally, after your function code, print grades_variance(grades). """ grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def print_grades(grades): for grade in grades: print (grade) def grades_sum(grades): total = 0 for grade in grades: total += grade return total def grades_average(grades): sum_of_grades = grades_sum(grades) average = sum_of_grades / float(len(grades)) return average def grades_variance(scores): average = grades_average(scores) variance = 0 for i in scores: variance += (average - i)**2 variance = variance / (float(len(scores))) return variance print(grades_variance(grades))
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 09:37:45 2017 @author: mindovermiles262 Codecademy Python Define a function called add_function that has 2 parameters x and y and adds them together. """ m = 5 n = 13 # Add add_function here! def add_function(x, y): return x + y print(add_function(m, n))
# -*- coding: utf-8 -*- """ Created on Tue Jan 10 08:50:06 2017 @author: mindovermiles262 Codecademy Python Iterate over my_list to get each value Use my_file.write() to write each value to output.txt Make sure to call str() on the iterating data so .write() will accept it Make sure to add a newline ("\n") after each element to ensure each will appear on its own line. Use my_file.close() to close the file when you're done. """ my_list = [i**2 for i in range(1,11)] my_file = open("output.txt", "r+") # Add your code below! for i in my_list: my_file.write(str(i)+ "\n") my_file.close()
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 09:13:20 2017 @author: mindovermiles262 Codecademy Python Define a function grades_average(), below the grades_sum() function that does the following: Has one argument, grades, a list Calls grades_sum with grades Computes the average of the grades by dividing that sum by float(len(grades)). Returns the average. Call the newly created grades_average() function with the list of grades and print the result. """ grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def grades_sum(scores): total = 0 for i in scores: total = total + i return total def grades_average(grades): x = float(len(grades)) avg = grades_sum(grades)/x return avg print(grades_average(grades))
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 08:37:56 2017 @author: mindovermiles262 Codecademy Python This time we'll give the expected result, and you'll use some combination of boolean operators to achieve that result. Remember, the boolean operators are and, or, and not. Use each one at least once! """ # Use boolean expressions as appropriate on the lines below! # Make me false! bool_one = (2 <= 2) and "Alpha" == "Bravo" # We did this one for you! # Make me true! bool_two = True # Make me false! bool_three = False # Make me true! bool_four = True # Make me true! bool_five = True
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 07:44:08 2017 @author: mindovermiles262 Codecademy Python Create a new variable brian and assign it the string "Hello life!". """ # Set the variable brian on line 3! brian = "Hello life!"
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 9 17:34:21 2017 @author: mindovermiles262 Codecademy Python Inside the Car class, add a method named display_car() to Car that will reference the Car's member variables to return the string, "This is a [color] [model] with [mpg] MPG." You can use the str() function to turn your mpg into a string when creating the display string. Replace the individual print statements with a single print command that displays the result of calling my_car.display_car() """ class Car(object): condition = "new" def __init__(self, model, color, mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): return ("This is a %s %s with %s MPG." % (self.color, self.model, self.mpg)) my_car = Car("DeLorean", "silver", 88) print(my_car.display_car())
# -*- coding: utf-8 -*- """ Created on Wed Jan 4 12:35:20 2017 @author: mindovermiles262 Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed. For example: anti_vowel("Hey You!") should return "Hy Y!". Don't count Y as a vowel. Make sure to remove lowercase and uppercase vowels. """ def anti_vowel(text): text = str(text) vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] for i in text: for j in vowels: if i == j: text = text.replace(j,"") return text
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 08:49:39 2017 @author: mindovermiles262 Codecademy Python Use and to add a second condition to your if statement. In addition to your existing check that the string contains characters, you should also use .isalpha() to make sure that it only contains letters. Don't forget to keep the colon at the end of the if statement! """ print('Welcome to the Pig Latin Translator!') try: original = raw_input("Enter a Word: ") except NameError: original = input("Enter a Word: ") if len(original) > 0 and original.isalpha(): print(original) else: print("empty")
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 10:03:12 2017 @author: mindovermiles262 Codecademy Python Use the print command to display the contents of the board list. """ board = [] #initalize board for i in range(0,5): board.append(["O"] * 5) print(board)
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 09:11:16 2017 @author: mindovermiles262 Codecademy Python Define a function on line 3 called print_grades() with one argument, a list called grades. Inside the function, iterate through grades and print each item on its own line. After your function, call print_grades() with the grades list as the parameter. """ grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def print_grades(grades): for i in grades: print i print_grades(grades)
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 09:33:55 2017 @author: mindovermiles262 Codecademy Python Append the number 4 to the end of the list n. """ n = [1, 3, 5] # Append the number 4 here n.append(4) print (n)
# -*- coding: utf-8 -*- """ Created on Wed Jan 4 12:29:36 2017 @author: mindovermiles262 Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number's digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.) """ def digit_sum(n): n = str(n) count = 0 for i in n: count = count + int(i) return count
# -*- coding: utf-8 -*- """ Created on Wed Jan 11 07:16:26 2017 @author: mindovermiles262 Codecademy Python Try it and see! Change the value of my_int from 7 to 3 in the editor """ # my_int is set to 7 below. What do you think # will happen if we reset it to 3 and print the result? my_int = 7 # Change the value of my_int to 3 on line 8! my_int = 3 # Here's some code that will print my_int to the console: # The print keyword will be covered in detail soon! print(my_int)
from IPython.display import clear_output import random # this function prints grid and all instances of objects def makeGrid(rows, cols, monsters, player, egg, door): for y in range(rows): print(' ---'*cols) for x in range(cols): monster_created = False for monster in monsters: if monster.coords == [x, y] and x == cols - 1 and monster_created == False: print('| m |', end='') monster_created = True elif monster.coords == [x, y] and monster_created == False: print('| m ', end='') monster_created = True if player.coords == [x, y] and x == cols - 1 and monster_created == False: print('| p |', end='') elif player.coords == [x, y] and monster_created == False: print('| p ', end='') elif egg.coords == [x, y] and x == cols - 1 and monster_created == False: print('| e |', end='') elif egg.coords == [x, y] and monster_created == False: print('| e ', end='') elif door.coords == [x, y] and x == cols - 1 and monster_created == False: print('| d |', end='') elif door.coords == [x, y] and monster_created == False: print('| d ', end='') elif x == cols - 1 and monster_created == False: print('| |', end='') elif monster_created == False: print('| ', end='') print() if y == rows - 1: print(' ---'*cols) class Monster(): def __init__(self, coords): self.coords = coords def initCoords(self, rows, cols): self.coords = [random.randint(0, cols-1), random.randint(0, rows-1)] def moveMonster(self, ans, rows, cols): if ans == 'up': if self.coords[1] + 1 >= rows -1: self.coords = [self.coords[0], 0] else: self.coords = [self.coords[0], self.coords[1] + 2] elif ans == 'down': if self.coords[1] - 1 <= 0: self.coords = [self.coords[0], rows -1] else: self.coords = [self.coords[0], self.coords[1] - 2] elif ans == 'left': if self.coords[0] - 1 <= 0: self.coords = [cols -1, self.coords[1]] else: self.coords = [self.coords[0] - 2, self.coords[1]] elif ans == 'right': if self.coords[0] + 1 >= cols -1: self.coords = [0, self.coords[1]] else: self.coords = [self.coords[0] + 2, self.coords[1]] class Player(): def __init__(self, coords, eggs_collected=0): self.coords = coords self.eggs_collected = eggs_collected def initCoords(self, rows, cols, monsters): # initialize first coords self.coords = [random.randint(0, cols-1), random.randint(0, rows-1)] # check and loop until coords are not same as monster for monster in monsters: while monster.coords == self.coords: self.coords = [random.randint(0, cols-1), random.randint(0, rows-1)] def movePlayer(self, monsters, rows, cols): ans = input('Where would you like to move? ') if ans == 'up': if self.coords[1] - 1 < 0: self.coords = [self.coords[0], rows -1] else: self.coords = [self.coords[0], self.coords[1] - 1] elif ans == 'down': if self.coords[1] + 1 > rows - 1: self.coords = [self.coords[0], 0] else: self.coords = [self.coords[0], self.coords[1] + 1] elif ans == 'left': if self.coords[0] - 1 < 0: self.coords = [cols -1, self.coords[1]] else: self.coords = [self.coords[0] - 1, self.coords[1]] elif ans == 'right': if self.coords[0] + 1 > cols -1: self.coords = [0, self.coords[1]] else: self.coords = [self.coords[0] + 1, self.coords[1]] for monster in monsters: monster.moveMonster(ans, rows, cols) def checkEgg(self, egg): if self.coords == egg.coords: self.eggs_collected += 1 egg.coords = [-1, -1] class Egg(): def __init__(self, coords): self.coords = coords def initCoords(self, rows, cols): self.coords = [random.randint(0, cols-1), random.randint(0, rows-1)] class Door(): def __init__(self, coords): self.coords = coords def initCoords(self, rows, cols): self.coords = [random.randint(0, cols-1), random.randint(0, rows-1)] # create a game over function def game_over(player, monsters, door, num_eggs): for monster in monsters: if player.coords == monster.coords: return 1 if player.coords == door.coords and num_eggs == player.eggs_collected: return 2 return False # initialize game over flag flag = False level = 0 # main outer initializing loop while True: # size of grid rows = 10 cols = 10 level += 1 # objects for game monsters = [Monster([0, 0]) for i in range(level)] player = Player([1, 1]) egg = Egg([2, 2]) door = Door([3, 3]) # randomly initiating coordinates for start for monster in monsters: monster.initCoords(rows, cols) player.initCoords(rows, cols, monsters) egg.initCoords(rows, cols) door.initCoords(rows, cols) # main game loop while True: clear_output() # show grid makeGrid(rows, cols, monsters, player, egg, door) # move player and monster player.movePlayer(monsters, rows, cols) # monster.moveMonster() player.checkEgg(egg) # check game_over flag = game_over(player, monsters, door, 1) if flag == 1: print('You were eaten by the monster!') level -= 1 break elif flag == 2: print('Congrats you beat this level!') break ans = input('Would you like to play again? ') if ans == 'no': break
# This class provides methonds for filling in data between known [x,y] points using linear interpolation. # method interp_x returns an [x,y] point at a desired x which lies between two given [x,y] points # method interp_nSpaced returns a list of n number of [x,y] points that are evenly spaced between two given [x,y] points class linear_interpolation: # takes two points [x,y] and calculates the y value for any given x using linear interpolation, then returns the new [x,y] point # given points must be in ascending x values # x value must be between the two given points def interp_x(self,x_new, point1, point2): # checks that given points are in ascending order if point1[0] > point2[0]: print("coordinates not in ascending order") # checks that desired x is between the two givne points if x_new < point1[0] or x_new > point2[0]: print("target x coordinate outside of scope") else: x_left = point1[0] x_right = point2[0] y_left = point1[1] y_right = point2[1] slope = (y_right - y_left)/(x_right - x_left) intercept = y_left - slope * x_left y_new = slope * x_new + intercept # y = mx + b return [x_new,y_new] # calculates n-number of evenly spaced points between two given [x,y] points # number of desired points must be a positive whole number greater than 0 # returns evenly spaced points as a list of [x,y] values def interp_nSpaced(self, n, point1, point2): #check that n is whole number greater than 0 if n < 1 or n - int(n) != 0 : print("n must be a positive interger greater than 0") else: # calculates the x-axis spacing of the desired points spacing = (point2[0] - point1[0]) / ( n + 1 ) # list of new x values to interpolate y values for x_new = [] #adds the first x value to x_new x_new.append(point1[0]+spacing) #adds the rest of x values if n > 1 for i in range(n - 1): x_new.append(x_new[-1] + spacing) new_points = [] for i in x_new: new_points.append(self.interp_x(i,point1,point2)) return new_points # creates instance of linear_interpolation class and names it data data = linear_interpolation() # returns [x,y] values at x = 5 between points [1,1] and [10,10] print(data.interp_x(5,[1,1],[10,10])) # returns 8 evenly spaced [x,y] points between [10,10] and [100,100] print(data.interp_nSpaced(8,[10,10],[100,100]))
from copy import copy class Human: def __init__(self, first, last, age): self.first = first self.last = last self.age = age def __repr__(self): return f"Human named {self.first} {self.last} aged {self.age}" def __len__(self): # len() function will return age of an object return self.age def __add__(self, other): # When you add two humans together...you get a newborn baby Human! if isinstance(other, Human): return Human(first='Newborn', last=self.last, age=0) return "You can't add that!" def __mul__(self, other): # When you multiply a Human by an int, you get clones of that Human! if isinstance(other, int): return [copy(self) for i in range(other)] return "CANT MULTIPLY!" j = Human("John", "Smith", 35) k = Human("Kate", "Adams", 30) print(j) # Human named John Smith aged 35 print(k) # Human named Kate Adams aged 30 print(len(j)) # 35 print(len(k)) # 30 print(j + k) # Human named Newborn Smith aged 0 print(j * 3) # [Human named John Smith aged 35, Human named John Smith aged 35, Human named John Smith aged 35]
import re text = "Last night Mrs. Daisy and Mr. white murdered Ms. Chow" regex = r'(Mr.|Mrs.|Ms.) ([a-z])[a-z]+' #Using sub method on Regular Expression Object # pattern = re.compile(regex, re.I) # result = pattern.sub("\g<1> \g<2>", text) #Using sub method on re module result = re.sub(regex, "\g<1> \g<2>", text, flags=re.I) #\g<1> - refers to a first group, \g<2> - to the second print(result) # Last night Mrs. D and Mr. w murdered Ms. C
cards_arr = [w[0] for w in list(input().split(' '))] strength = 1 # count occurance of every card in the list for i in range(5): same_cards = cards_arr.count(cards_arr[i]) strength = same_cards if same_cards > strength else strength print(strength)
import csv from tweet import Tweet tweets = [] top_count = 10 filename = 'tweet_activity_metrics.csv' def main(): with open(filename, 'rb') as csvfile: csvfile.readline() reader = csv.reader(csvfile) for row in reader: t = Tweet( row[0], row[1], row[2], row[3], row[4], row[5], row[6], int(row[7]), int(row[8]), int(row[9]) ) tweets.append(t) top_retweets = sorted(tweets, key = lambda t: t.get_retweets(), reverse=True) top_replies = sorted(tweets, key = lambda t: t.get_replies(), reverse=True) top_favs = sorted(tweets, key = lambda t: t.get_favs(), reverse=True) data = [top_retweets, top_replies, top_favs] print "Welcome to the Twitter Metrics Parser" print "1) Top RTs" print "2) Top Replies" print "3) Top Favs" print "" selection = int(raw_input("Please select what data you are interested in: ")) print "" while selection > len(data) or selection < 1: print "*** That is not a valid selection ****" selection = int(raw_input("Please select what data you are interested in: ")) lst = data[ selection - 1 ] for i in range(top_count): print "--- #" + str(i+1) + " ---" print lst[i] if __name__ == "__main__": main()
class Argument(object): """ This is a class for passing arguments """ def __init__(self): self.arglist = {} # empty dict def insert(self, argname): """ insert an argname with no argval (True) """ self.insert(argname, True) def insert(self, argname, argval): """ insert an arg dict entry {argname:argval} """ self.arglist[argname] = argval def remove(self, argname): del self.arglist[argname] def get(self,argname): """ no argname -> None otherwise, return the argval """ return self.arglist[argname] def has(self, argname): """check if contain an argname """ if (self.arglist[argname] == None): return False return True def __repr__(self): str = '' for argname in self.arglist: str = str + "[%s: %s]\n" % (argname, self.arglist[argname]) return str # test test_args = Argument() test_args.insert('id', 5) test_args.insert('parent', 'John') print(test_args)
''' Alessia Pizzoccheri Wholesale Test Case #1 3 pies crusts, 4 potatoes, 3 packages of meat, 1 pack of corn Test Case #2 1 pies crusts, 23 potatoes, 5 packages of meat, 2 pack of corn Test Case #3 5 pies crusts, 42 potatoes, 5 packages of meat, 8 pack of corn Test Case #4 2 pies crusts, 6 potatoes, 12 packages of meat, 1 pack of corn Test Case #5 0 pies crusts, 8 potatoes, 3 packages of meat, 4 pack of corn ''' def main(): crusts = int(input('How many pie crusts do you have? ')) potatoes = int(input('How many potatoes do you have? ')) meat = int(input('How many packs of meat do you have? ')) corn = int(input('How many packs of corn do you have? ')) # check if there are enough ingredients to make pies pies_from_crusts = crusts // 1 pies_from_potatoes = potatoes // 6 pies_from_meat = meat // 2 pies_from_corn = corn // 2 # calculate the max number of pies Kiki can make max_pies_possible = min(pies_from_crusts, pies_from_potatoes, pies_from_meat, pies_from_corn) # determine leftovers for each ingradient based on how many pies Kiki made leftover_crusts = crusts - (max_pies_possible * 1) leftover_potatoes = potatoes - (max_pies_possible * 6) leftover_meat = meat - (max_pies_possible * 2) leftover_corn = corn - (max_pies_possible * 2) print('Kiki made ', max_pies_possible, ' pies for the NSKS') print('You have donated the following leftover ingredients:') print(leftover_crusts, ' crust(s)') print(leftover_potatoes, ' potato(es)') print(leftover_meat, ' pack(s) of meat') print(leftover_corn, ' corn pack(s)') main()
''' Alessia Pizzoccheri - CS 5001 02 Haversine function parameters distance = haversine(latitude1, longitude1, latitude2, longitude2) Test Case #1 Boston Test Case #2 Miami Test Case #3 Seattle, 47.6062, 122.3321 7118.43 nautical miles ''' from haversine import haversine def main(): # predefined latitude and longitude for Dorian, Boston and Miami DORIAN_LATITUDE = 27.1 DORIAN_LONGITUDE = -78.4 BOSTON_LATITUDE = 42.361145 BOSTON_LONGITUDE = -71.057083 MIAMI_LATITUDE = 25.761681 MIAMI_LONGITUDE = -80.191788 # Ask users to pick a location print('This is a hurricane tracker based upon the Haversine approach.') origin = input('Pick one of the choices below to activate the radar\n' + 'A. Boston\n' + 'B. Miami\n' + 'C. I want to pick a different city\n' ).upper() # If users choose Boston, run Boston coordinates through Haversine script and calculate distance if origin == 'A': nautical_miles = haversine(BOSTON_LATITUDE,BOSTON_LONGITUDE,DORIAN_LATITUDE,DORIAN_LONGITUDE) print('On September 3, 2019 Hurrican Dorian was {:.2f}'.format(nautical_miles),' nautical miles from Boston.') if nautical_miles < 150: print('WARNING! Seek shelter!') else: print('You are safe.') # If users choose Miami, run Miami coordinates through Haversine script and calculate distance elif origin == 'B': nautical_miles = haversine(MIAMI_LATITUDE,MIAMI_LONGITUDE,DORIAN_LATITUDE,DORIAN_LONGITUDE) print('On September 3, 2019 Hurrican Dorian was {:.2f}'.format(nautical_miles),' nautical miles from Miami.') if nautical_miles < 150: print('WARNING! Seek shelter!') else: print('You are safe.') # If users choose a different city, ask users to manually enter coordinates elif origin == 'C': print('To check a different city, enter name of the city, the latitude and the longituted.') city = input('What is the name of the city? ') latitude = float(input("What is the city's latitude? ")) longitude = float(input("What is the city's longitude?" )) # Output final results nautical_miles = haversine(latitude,longitude,DORIAN_LATITUDE,DORIAN_LONGITUDE) print('On September 3, 2019 Hurrican Dorian was {:.2f}'.format(nautical_miles),' nautical miles from ',city) if nautical_miles < 150: print('WARNING! Seek shelter!') else: print('You are safe.') main()
########################## # object oriented programming ########################## # programming paradigm based on the concept of objects # objects = data structures containing data (or attributes) and methods (or procedures) # create your own data types -> object definitions known as classes # class = definition of a particular kind of object in terms of its component features # and how it is constructed or implemented in the code # object = specific instance of the thing which has been made according to the class definition # => everything that exists in Python is an object # common principle of OOP is that class definition # -> makes available certain functionality # -> hides internal information about ho a specific class is implemented # => encapsulation and information hiding (but Python quite permissive) # Class definition class Sequence: <statements> # Common practice: save each class into specific files, then from Sequence import Sequence # Inheritance class MultipleSeq(Sequence): <statements> #-> inherits methods from superclass #-> classes can have >1 superclass # Class functions # -> functions are defined within the construction of a class # -> defined in the same way as ordinary functions # -> first argument is special: the object called from (self) # -> accessed from the variable representing the object via 'dot' syntax myseq = Sequence(...) name = myseq.getName() #getName() defined in Sequence class class Sequence: def getName(self): return (self.name) def getCapitalisedName(self): name = self.getName() if name: return (name.capitalize()) else: return (name) # order of the functions does not matter # if function definition appears more than once, the last instead replaces the previous one class MultipleSeq(Sequence): def getMSA(self): <statements> def getSeqID(self): <statements> msa = MultipleSeq(...) # can call msa.getMSA() as usual # can also call msa.getName() because of inheritance # Attributes # -> attributes hold information useful for the object and its functions # -> e.g. associate a variable storing sequence name in Sequence objects # Object attributes: # -> specific to a particular object # -> defined inside class functions # -> use the self keyword to access it # Class attributes: # -> available to instance of a class # -> defined outside all function blocks # -> usually used for variables that do not change # -> access directly using the variable name # -> bare function names are also class attributes class Sequence: type = "DNA" # class attribute def setSeq(self, l): self.length = l def getSeqLength(self): return(self.length) myseq = Sequence() print(myseq.type) # variable type can be accessed from the object [not use () to access variable] print(Sequence.type) # access through the class itself getSeqFunc = Sequence.getSeqLength getSeqFunc(myseq) # same as myseq.getSeqLength() length = myseq.length # error, length not yet set myseq.setSeq(541) length = myseq.length # returns now 541 myseq.getSeqLength() myseq.l = 541 # create new attributes on the fly # Object life cycle: # creation of object handled in a special function called constructor # removal handle by a function called destructor # Python has automatic garbage collection (usually no need to define a destructor) # Class constructor: # called whenever the corresponding object is created # special name: __init__ # first argument is the object itself (self) # any other arguments needed to create the object) # good idea: introduce key to uniquely identifies objects of a given class class Sequence: def __init__(self, name, type="DNA"): self.type = type try name: self.name = name except: print("Name must be set to sth") myseq = Sequence("opsin") myseq2 = Sequence("opsin", "AA") # When create attributes? # -> can be created in any class function (or directly on the object) # -> convention to create most of them in the constructor either directly # or through the call to a function # -> set it to None if it cannot be set at object creation # -> constructors are inherited by subclasses
# fruits.txt is in same directory as fileprocessing myfile = open("fruits.txt") print(myfile.read()) # this is a read method # another way to do it file = open("bear.txt") content = file.read() print(content) # close files myfile2 = open("fruits.txt") content2 = myfile2.read() #store in variable myfile2.close() # closes file print(content2) # another way to do it with open("fruits.txt") as myfile3: content = myfile3.read() print(content) #using file from different directory # another way to do it with open("C:/Users/blake/OneDrive/Full Stack Development/OtherDirectory/bear.txt") as myfile3: content = myfile3.read() print(content) # Writing txt to file. with open("C:/Users/blake/OneDrive/Full Stack Development/Python 10 Project MasterCourse/vegetables.txt","w") as myfile6: content = myfile6.write("Melina is cute") # another way with open("C:/Users/blake/OneDrive/Full Stack Development/Python 10 Project MasterCourse/vegetables2.txt","w") as myfile7: myfile7.write("Melina is cute\nlike really alot\n cool") myfile7.write("DOODIE") #print 90 characters of the content file = open("bear.txt") content = file.read() file.close() print(content[:30]) # define function that gets a single string character and a filepath as parameters and runs the number of occurances of that character in the file def foo5(character, filepath="bear.txt"): file = open(filepath) content = file.read() return content.count(character) print(foo5("e","bear.txt")) # create a file with name file.txt and write a text snail with open("file.txt", "w") as file: file.write("snail") # create a file first text that gets the first 90 characters of the bear file with open("bear.txt") as file: content = file.read() with open("first.txt", "w") as file: file.write(content[:90]) # This appends okra to the previous file of fruits with open("C:/Users/blake/OneDrive/Full Stack Development/Python 10 Project MasterCourse/fruits.txt","a") as myfile8: myfile8.write("Okra") print(content) # This appends okra to the previous file of fruits and writes with open("C:/Users/blake/OneDrive/Full Stack Development/Python 10 Project MasterCourse/fruits.txt","a+") as myfile8: myfile8.write("Okrazzz") myfile8.seek(0)# moves the cursor back to the first position content= myfile8.read() print(content) # append the text of bear1.txt in otherwears and bear 2 should contain text and the text of bear1 after that with open("bear1.txt") as file: content = file.read() with open("bear2.txt", "a") as file: file.write(content) # open data.txt and append with open("data.txt", "a+") as file: file.seek(0) content = file.read() file.seek(0) file.write(content) file.write(content) # more file processing with open("file.txt") as file: content = file.read() # write with open("file.txt", "w") as file: content = file.write("Sample text") # append with open("file.txt", "a") as file: content = file.write("More sample text") # apend and read with open("file.txt", "a+") as file: content = file.write("Even more sample text") file.seek(0) content = file.read()
def is_prime(x): for i in range(2, x): if x % i == 0: return False return True #--------main--------- while True: n = eval(input('n=')) for n1 in range(n, 1, -1): if is_prime(n1): Max = n1 break if Max == n1: print('biggest',Max) nlist = list(Max) print(nlist)
class library: Booker={} List_of_Books=[] def __init__(self,Books1,library_name): for i in list(Books1): self.Books=library.List_of_Books.append(i) self.library=library_name def Display(self): print("List Of Books in our library:") for i in enumerate(library.List_of_Books,start=1): print(i) def Lend(self): Book_name=input("Tell The Book Name:") lender=input("Tell Your name:") library.Booker[Book_name]=lender if Book_name in library.List_of_Books: print("Have the Book") print(library.Booker) library.List_of_Books.remove(Book_name) else: print("xyz Already Have this book") def Add(self): Book_add=input("Name of Book:") username = input("Enter Your Name:") print(f"{username} has added the book {Book_add}") library.List_of_Books.append(Book_add) def Return(self): Name_Of_book=input("Enter Book name:") username1=input("Enter Your Name:") try: del library.Booker[Name_Of_book] library.List_of_Books.append(Name_Of_book) except KeyError: print("This Book is not in our register") print("Thank You For returning the Book") # x=input("Enter Your Library name:") # libbooks=list(input("Enter the books You have:")) # y=x+"Library" # y=library(libbooks,x) A=library(["rat","cat","fat"],"Akshay") y=A while True: print("Choose From the Following\n" "1:Display All Books\n" "2:Lend the books\n" "3:Add the Books\n" "4:return the Book") choice=int(input("Enter Yours Choice:")) if choice==1: y.Display() elif choice==2: y.Lend() elif choice==3: y.Add() elif choice==4: y.Return() elif choice==0: print("Quiting...") break else: print("Enter valid choice") continue print("-------------------------------------------")
def large_x_one(numbers, n): digits = list(str(numbers)) result = 0 digits.reverse() for i, digit in enumerate(digits): result += n*int(digit)*10**i return result def multiply_large_number(num1, num2): num2_digits = list(str(num2)) result = 0 num2_digits.reverse() for i, digit in enumerate(num2_digits): result += large_x_one(num1, int(digit))*10**i return result
import numpy as np ''' * Execution of this function happens in 3 steps * 1) We choose a random pivot * 2) We put the array into a set less than the pivot * and a set greater than the pivot * 3) ''' def quicksort(arr=None): if arr is None: # If no array is passed, initialize a random array arr = np.random.randint(0,200,10) if len(arr) == 1 or len(arr) == 0: return arr # Randomly pick a pivot i = np.random.randint(len(arr)) pivot = arr[i] # compare the elements to the pivot to get the elements smaller less_than = [element for element in arr if element < pivot] # the pivots pivots = [element for element in arr if element == pivot] # and greater than the pivot greater_than = [element for element in arr if element > pivot] return quicksort(less_than) + pivots + quicksort(greater_than) if __name__ == '__main__': array = [101, 100, 22, 97, 204, 42] print("Array before sort : {}".format(array)) sorted_array = quicksort(array) print("Array after sort : {}".format(sorted_array))
# Crie uma função que recebe como parâmetros dois valores e retorna o menor valor def menor_valor(valor1, valor2): if (valor1 < valor2): return valor1 else: return valor2 entrada_1 = int(input('digite um valor ')) entrada_2 = int(input('digite um valor ')) print('O menor valor digitado foi ', menor_valor(entrada_1, entrada_2))
# Elaborar um programa que efetue a leitura de três valores inteiros (variáveis A, B, C) # e apresente como resultado final o valor do quadrado da soma var_A = int(input('Digite o primeiro valor ')) var_B = int(input('Digite o primeiro valor ')) var_C = int(input('Digite o primeiro valor ')) soma = var_A + var_B + var_C soma_quadrado = soma * soma print('O quadrado da soma dos valores digitados he ' + str(soma_quadrado))
def signos(dia, mes): JANEIRO = 1 FEVEREIRO = 2 MARCO = 3 ABRIL = 4 MAIO = 5 JUNHO = 6 JULHO = 7 AGOSTO = 8 SETEMBRO = 9 OUTUBRO = 10 NOVEMBRO = 11 DEZEMBRO = 12 if(dia >= 21 and mes == MARCO) or (dia <= 20 and mes == ABRIL): return 'Aries' elif(dia >= 21 and mes == ABRIL) or (dia <= 20 and mes == MAIO): return'Touro' elif(dia >= 21 and mes == MAIO) or (dia <= 21 and mes == JUNHO): return 'Gemeos' elif(dia >= 21 and mes == JUNHO) or (dia <= 21 and mes == JULHO): return'Cancer' elif(dia >= 22 and mes == JULHO) or (dia <= 22 and mes == AGOSTO): return'Leao' elif(dia >= 23 and mes == AGOSTO) or (dia <= 22 and mes == SETEMBRO): return 'Virgem' elif(dia >= 23 and mes == SETEMBRO) or (dia <= 22 and mes == OUTUBRO): return 'Libra' elif(dia >= 23 and mes == OUTUBRO) or (dia <= 21 and mes == NOVEMBRO): return 'Escorpiao' elif(dia >= 22 and mes == NOVEMBRO) or (dia <= 21 and mes == DEZEMBRO): return 'Sagitario' elif(dia >= 22 and mes == DEZEMBRO) or (dia <= 20 and mes == JANEIRO): return 'Capricornio' elif(dia >= 21 and mes == JANEIRO) or (dia <= 19 and mes == FEVEREIRO): return'Aquario' elif(dia >= 20 and mes == FEVEREIRO) or (dia <= 20 and mes == MARCO): return 'Peixes' dia_nascimento = int(input('Digite o dia de seu nascimento ')) mes_nascimento = int(input('Digite o mês de seu nascimento ')) print('Seu signo é ', signos(dia_nascimento, mes_nascimento))
# Elaborar um programa que efetue a leitura de quatro valores inteiros (variáveis A, B, C e D). # Ao final o programa deve apresentar o resultado do produto (variável P) do primeiro com o terceiro valor, # e o resultado da soma (variável S) do segundo com o quarto var_A = int(input('Digite o primeiro valor ')) var_B = int(input('Digite o segundo valor ')) var_C = int(input('Digite o terceiro valor ')) var_D = int(input('Digite o quarto valor ')) var_P = var_A * var_C var_S = var_B + var_D print('Produto do primeiro com o terceiro ' + str(var_P)) print('Soma do segundo com o quarto ' + str(var_S))
def palindrome(n): n = str(n) i = 0 res = True while i<((len(n))/2): if n[i] != n[-(i+1)]: return False i += 1 return print(palindrome(1000021))
def word_jumble(): scrambled_word = raw_input('Enter a word to scramble: ') matching_words = [] scrambled_word_length = len(scrambled_word) dictionary = import_dictionary('dictionary.txt') dictionary.sort(key = len) for word in dictionary: if len(word) > scrambled_word_length: if scrambled_word in matching_words: matching_words.remove(scrambled_word) break if matching_word(word, scrambled_word): matching_words.append(word) return matching_words def import_dictionary(file): dictionary_file = open(file) dictionary = dictionary_file.read().splitlines() dictionary_file.close() return dictionary def matching_word(word, scrambled_word): characters = list(scrambled_word) for letter in word: if letter in characters: characters.remove(letter) else: return False return True print word_jumble()
# parses text-wiki format and outputs each word at separate line # input has a wiki article per line: "title tab string-escaped article content" import string import sys for line in sys.stdin: line = line.split("\t")[1].decode("string-escape").lower().replace("\n","").replace("."," ").split() for word in line: print filter(str.isalnum,word)
class Ttype(object): def displayNumType(num): print num,'is', if isinstance(num, (int, float,long,complex)): print 'a number of type:',type(num).__name__ else: print 'not a number at all!!'
class Person(): def __init__(self,name): self.name=name def Sayhello(self): print "hello,my name is",self.name def __del__(self): print "%s says bye",self.name
class myDecorator(object): def __init__(self, f): print "inside myDecorator.__init__()" def f(self,name): self.name=name return self.name # Prove that function definition has completed def __call__(self): print "inside myDecorator.__call__()" @myDecorator def aFunction(): print "inside aFunction()" print "Finished decorating aFunction()"
a = [] a = input("Enter a string for processing") print "maximum of the string is",max(a) print "minimum of the string is",min(a) print "length of the string is",len(a)
''' Условие Условие Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс. Если она встречается два и более раз, выведите индекс её первого и последнего появления. Если буква f в данной строке не встречается, ничего не выводите. При решении этой задачи не стоит использовать циклы. ''' #************************************************** s =input() a=len(s) b=s.count('f') if b==0: print() elif b==1: print(s.find('f')) else: d=s[::-1] print(s.find('f')," ",s.rfind('f'))
''' Условие Дана строка, в которой буква h встречается как минимум два раза. Разверните последовательность символов, заключенную между первым и последним появлением буквы h, в противоположном поря ''' #************************************************** s =input() start=s.find('h') stop=s.rfind('h') print(s[:start+1]+s[stop-1:start:-1]+s[stop:])
''' Условие По данному натуральному n ≤ 9 выведите лесенку из n ступенек, i-я ступенька состоит из чисел от 1 до i без пробелов. ''' #************************************************** n=int(input()) c="" for i in range(1,n+1): c+=str(i) print(c)
''' Формула всего ''' #************************************************** import math #print(8.9//3) x=0 y=17 a=math.floor(((y//17)*(2**(-17*math.floor(x)-math.floor(y)//17)))//2) #def f(x,y): # return ((y//17)//(1 << (17*x+(y%17))))%2 #a=f(x,y) print(a)
''' Условие Процентная ставка по вкладу составляет P процентов годовых, которые прибавляются к сумме вклада. Вклад составляет X рублей Y копеек. Определите размер вклада через год. Программа получает на вход целые числа P, X, Y и должна вывести два числа: величину вклада через год в рублях и копейках. Дробная часть копеек отбрасывается. ''' #************************************************** p=int(input()) x=int(input()) y=int(input()) after=(x*100+y)*(100+p)/100 print(int(after//100)) print(int(after%100))
''' Условие Последовательность состоит из натуральных чисел и завершается числом 0. Определите, сколько элементов этой последовательности равны ее наибольшему элементу. ''' a=[] b=0 while True: d=int(input()) if d==0: break a.append(d) for i in range(len(a)): if max(a)==a[i]: b+=1 print(b)
''' Условие Последовательность состоит из натуральных чисел и завершается числом 0. Определите, сколько элементов этой последовательности больше предыдущего элемента. ''' a=[] c=0 while True: d=int(input()) if d==0: break a.append(d) for i in range(1,len(a)): if a[i]>a[i-1]: c+=1 print(c)
''' Условие Шахматный слон ходит по диагонали. Даны две различные клетки шахматной доски, определите, может ли слон попасть с первой клетки на вторую одним ходом. ''' #************************************************** x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if abs(x1-x2)==abs(y1-y2): print("YES") else: print("NO")
''' Условие Последовательность Фибоначчи определяется так: φ0 = 0, φ1 = 1, φn = φn−1 + φn−2. По данному числу n определите n-е число Фибоначчи φn. Эту задачу можно решать и циклом for. ''' a=int(input()) b=[0,1] if a==0: print(0) else: for i in range(2,a+1): b.append(b[i-1]+b[i-2]) c=0 print(max(b))
''' Условие В первый день спортсмен пробежал x километров, а затем он каждый день увеличивал пробег на 10% от предыдущего значения. По данному числу y определите номер дня, на который пробег спортсмена составит не менее y километров. Программа получает на вход действительные числа x и y и должна вывести одно натуральное число. ''' #************************************************** x = input() y = input() prob=int(x) i=1 while prob<int(y): prob*=1.1 i+=1 print(i)
''' Условие Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента. ''' a = input().split() for i in range(len(a)): a[i] = int(a[i]) for i in range(1,len(a)): if a[i]>a[i-1]: print(a[i],end=' ')
''' Условие Дано число n. С начала суток прошло n минут. Определите, сколько часов и минут будут показывать электронные часы в этот момент. Программа должна вывести два числа: количество часов (от 0 до 23) и количество минут (от 0 до 59). Учтите, что число n может быть больше, чем количество минут в сутках. ''' #************************************************** n = int(input()) days=n//1440 hours=(n-1440*days)//60 minutes=n-1440*days-60*hours print(hours) print(minutes)
#!/usr/bin/env python3 import sys def to_exit(jumps, offset_adjustment): """Count the number of steps to the exit, following the jump protocol.""" steps, i = 0, 0 while 0 <= i < len(jumps): offset = jumps[i] jumps[i] += offset_adjustment(offset) i += offset steps += 1 return steps def part1(jumps): return to_exit(jumps, offset_adjustment=lambda x: 1) def part2(jumps): return to_exit(jumps, offset_adjustment=lambda x: -1 if x >= 3 else 1) if __name__ == '__main__': jumps1 = [int(x) for x in sys.stdin] jumps2 = list(jumps1) print(part1(jumps1)) print(part2(jumps2))
# https://practice.geeksforgeeks.org/problems/minimum-cost-path/0 def minCost(arr, n): tempCost = [[0 for i in range(n)] for j in range(n)] tempCost[0][0] = arr[0][0] for i in range(1, n): tempCost[0][i] = tempCost[0][i-1] + arr[0][i] for i in range(1, n): tempCost[i][0] = tempCost[i-1][0] + arr[i][0] for i in range(1, n): for j in range(1, n): tempCost[i][j] = min(tempCost[i-1][j], tempCost[i][j-1]) + arr[i][j] return tempCost[n-1][n-1] if __name__=="__main__": t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) matrix = [[arr[j+n*i] for j in range(n)] for i in range(n)] print(minCost(matrix, n))
def longestEvenOddSubarray(arr, n): res = 1 curr = 1 for i in range(1, n): if((arr[i-1]%2 == 0 and arr[i]%2 != 0) or (arr[i-1]%2 != 0 and arr[i]%2 == 0)): curr += 1 res = max(res, curr) else: curr = 1 return res if __name__=="__main__": t = int(input()) while(t): t -= 1 arr = list(map(int, input().split())) print(longestEvenOddSubarray(arr, len(arr)))
import random class Cell: def __init__(self, coords): self.num_adjacent_mines = 0 self.is_mine = False self.revealed = False self.flagged = False self.coords = coords def get_visual_representation(self): if self.flagged: return "[F]" if not self.revealed: return "[ ]" elif self.is_mine: return "[*]" else: return "[{}]".format(self.num_adjacent_mines) def __str__(self): return str(self.coords) def __repr__(self): return self.__str__() class Game: def __init__(self, num_rows=8, num_cols=8, num_mines=10): # TODO: Throw exception when num_mines >= num_cells or set num_mines to be one less than the product. self.num_rows = num_rows self.num_cols = num_cols self.num_mines = num_mines self.board = [] self._make_board() def play(self): self._print_board() while True: user_input = self._get_input() cell = user_input['cell'] if not cell: print('Bye!') break if user_input['flag']: cell.flagged = not cell.flagged else: cell.revealed = True if cell.is_mine: self._print_board() print('AHHH! You exploded.') break else: if cell.num_adjacent_mines == 0: self._reveal_cells_around_zero(cell) self._print_board() if self._won(): print('YOU WIN!!!') break def _make_board(self): all_cells = [] for row_index in range(self.num_rows): row = [] self.board.append(row) for col_index in range(self.num_cols): cell = Cell((row_index, col_index)) row.append(cell) all_cells.append(cell) for cell in random.sample(all_cells, self.num_mines): cell.is_mine = True for row_index in range(len(self.board)): for col_index in range(len(self.board[row_index])): cell = self.board[row_index][col_index] if cell.is_mine: continue adjacent_cells = self._get_adjacent_cells(cell) cell.num_adjacent_mines = sum(cell.is_mine for cell in adjacent_cells) def _won(self): won = True for row in self.board: for cell in row: if not cell.revealed and not cell.is_mine: won = False return won def _reveal_cells_around_zero(self, cell): adjacent_cells = self._get_adjacent_cells(cell) for adjacent_cell in adjacent_cells: was_revealed_before = adjacent_cell.revealed adjacent_cell.revealed = True if adjacent_cell.num_adjacent_mines == 0 and not was_revealed_before: self._reveal_cells_around_zero(adjacent_cell) def _get_input(self): coord_string = input( 'Coordinates, please! x,y format, starting with 0,0. To flag, put "f" first: f0,0. (q to quit)\n' ) while True: flag = False try: if coord_string == 'q': return None else: if coord_string[0] == 'f': flag = True coord_string = coord_string[1:] coords = [int(i.strip()) for i in coord_string.split(',')] cell = self.board[coords[0]][coords[1]] if cell.flagged and not flag: coord_string = input('Can\'t reveal a flagged cell. Try again.\n') elif cell.revealed and flag: coord_string = input('Can\'t flag a revealed cell. Try again.\n') else: return {'cell': self.board[coords[0]][coords[1]], 'flag': flag, 'coords': coords} except: coord_string = input('INVALID COORDINATES. Try again.\n') def _print_board(self): for row_index, row in enumerate(self.board): if row_index == 0: print(' ' + ' '.join(str(i) for i in range(len(row)))) print('{} {}'.format(row_index, ''.join([cell.get_visual_representation() for cell in row]))) def _get_adjacent_cells(self, cell): adjacent_cells = [] for row_diff in [-1, 0, 1]: for col_diff in [-1, 0, 1]: target_cell_coords = (cell.coords[0] + row_diff, cell.coords[1] + col_diff) # Don't look outside of the board. if (target_cell_coords[0] < 0 or target_cell_coords[0] >= self.num_rows or target_cell_coords[1] < 0 or target_cell_coords[1] >= self.num_cols): continue # Skip current cell. if row_diff == 0 and col_diff == 0: continue adjacent_cells.append(self.board[target_cell_coords[0]][target_cell_coords[1]]) return adjacent_cells Game(num_rows=8, num_cols=8, num_mines=10).play()
#Day 1: Chronal Calibration #Given a file containing frequency inputs, calculate the resulting frequency after all the changes in frequency have been applied. #Open the file. This file comes from https://adventofcode.com/2018/day/1/input. Inputs differ per user. frequency_inputs = open('input.txt') #Read each line of the file and save to a variable. frequencies_raw = frequency_inputs.readlines() #Initialize the total variable to zero. frequency_total = 0 #Loop through the list of frequencies. For each frequency, remove the new line char and convert to an integer. Add the resulting integer to the total. for f in frequencies_raw: cleaned = int(f.strip('\n')) frequency_total += cleaned #Return the total print(frequency_total)