text
stringlengths
37
1.41M
import asyncio import time def fetch(url): """Make the request and return the results """ pass def worker(name, queue, results): """ A function to take the unmake requests from a queue and perform the work then add results to the results list.""" pass async def distribute_work(url, requests, concu...
# -*- coding: utf-8 -*- def twoNumber(): number1= raw_input("请输入第一个数字:") number2= raw_input("请输入第二个数字:") if number1>number2: print number1,"大于",number2 elif number2>number1: print number2,"大于",number1 else: print number1,"等于",number2 def threeNumber(): l = [] for i i...
sum1 = 0 for i in range(1, 101): sum1 = sum1 + i*i print('sum1', sum1) sum2 = 0 for j in range(1, 101): sum2 = sum2 + j print('sum2', sum2) sum3 = 0 sum3 = sum2 * sum2 print('sum3', sum3) diff = 0 diff = sum3 - sum1 print('difference', diff)
from datetime import datetime def get_collatz_sequence(num): collatz_sequence = [num] while num != 1: if num % 2 == 0: num = num//2 else: num = 3 * num + 1 collatz_sequence.append(num) return collatz_sequence num_seq_length_map = {} def get_collatz_sequen...
from collections import defaultdict class Graph: def __init__(self, graph): self.graph = graph self. ROW = len(graph) # Використання BFS як алгоритму пошуку def searching_algo_BFS(self, s, t, parent): visited = [False] * (self.ROW) queue = [] queue.append(s) ...
#test_爬取来自www.doutula.com的表情包 from urllib import request from urllib import parse import urllib import re import sys import os import time page=1 x=0 totolnum=0 sys.stdin.encoding def filename(keyword): path=os.path.abspath('.') newpath=path+'\\img\\'+keyword if(os.path.exists(newpath)==False): os...
#list_of_numbers = [0, 1, 2, 3, "blue", 5] #for loops #for elem in list_of_numbers: # print(elem) #for loops #for elem in list_of_numbers: # if type(elem) == str: # continue # print(elem) #range loop #for i in range(5, 20, 3): # print(i) #for i in range(5): # print(i) #i = 0 #while i<10: ...
import random def jogo_advinha(): print("*****************************") print("Bem vindo ao jogo de adivinha") print("*****************************") tentativas = 0 numero_usuario = 0 numero_aleatorio = 0 #while((tentativas < 3) & (numeroUsuario != 10) ): for tentativas in range(1, ...
import tkinter as tk root = tk.Tk() root.title('A simple entry') root.geometry('300x100+50+50') lb = tk.Label(root, text='Enter:') lb.pack(side='left', padx=10) e = tk.StringVar() # 创建StringVar字符串变量 ety = tk.Entry(root, width=30, textvariable=e) ety.pack(side='left', padx=10) e.set('This is an entry!') root.mainl...
import numpy as np import matplotlib.pyplot as plt def apply_linear_regression(data): X_train=data[:,0][:80] Y_train=data[:,1][:80] alpha=0.001 theta=np.array([1,1]) iterations=100 X_1=X_train for i in range(iterations): theta_0=theta[0]- alpha * (1/len(Y_train)) * np.sum([np.dot(X_train[i],theta...
#!/usr/bin/env python ''' Split Input: string and and character to split on Output: create list with the string split based on character submitted ''' def split(string, char=None): create_list = [] start,stop = 0,0 if char==None: char = '' for i, letter in enumerate(string): if letter...
#!/usr/bin/env python ''' Turn Matrix Input: 3x3 matrix of integers Output: Rotate the matrix by 90 degrees and return rotated matrix Example: 1 2 3 4 5 6 7 8 9 Switch to: 7 4 1 8 5 2 9 6 3 ''' #Set data structure as a list of coordinates def flip_matrix(mat): mid = int(len(matrix/6)) for i, coord in ...
list = [5,3,7,5,1,2,5,6] target = 10 def add(list, target): #make a dictionary of nums in the list #to make the lookup faster num_dict = {} for i, num in enumerate(list): if num not in num_dict: num_dict[num] = [i] else: num_dict[num].append(i) # now go through each number in the list for i, num in en...
#!/usr/bin/env python """ Sentence Sort Input: sentence Output: sort a sentence by length of words Example: Input: "This is a fun interview" Output: "a is fun this interview" Original problem/solution submission from jofusa """ def pythonic_approach(sentence): """ This utilize's python's first class f...
#!/usr/bin/env python ''' Depth First Search (DFS) Input: tree of names and search for existance of one name Output: true or false if the name is found ''' class Node(): def __init__(self, val): self.val = val self.left = None self.right = None def add(value): pass # handl...
class Vehicle: #vehicle class def _init_(self, number, make, model, year, vin, value, dealer): self.number = number self.make = make self.model = model self.year = year self.vin = vin self.value = value self.dealer = dealer m = [] #instanc...
#Resource: https://www.youtube.com/watch?v=EItlUEPCIzM #Resource: https://towardsdatascience.com/k-means-clustering-for-beginners-ea2256154109 #Resource: https://stackoverflow.com/questions/42169892/is-there-a-way-to-limit-the-amount-of-while-loops-or-input-loops #Some hints on how to start, as well as guidance on...
import pygame as pg from data.constants import * from gui.widgets.animated_widget import AnimatedWidget class TextWidget(AnimatedWidget): """Widget that stores text on multiple lines. """ def __init__(self, x, y, font, font_size, color, align=0, width_limit=9001, max_alpha=255): super().__init__() ...
import sys from math import floor, sqrt p = int(sys.stdin.read()) #A214526 #https://math.stackexchange.com/questions/163080/on-a-two-dimensional-grid-is-there-a-formula-i-can-use-to-spiral-coordinates-in def coords(n): # n steps m = floor(sqrt(n)) k = (m-1)/2 if m%2 !=0 else m/2 if n >= m*(m+1) else m/2-1 if 2*...
import sys def triangleinequality(t): s1, s2, s3 = t t1, t2, t3 = (False, False, False) if (s1 + s2 > s3): t1 = True if (s2 + s3 > s1): t2 = True if (s1 + s3 > s2): t3 = True return t1 and t2 and t3 count = 0 while(True): t = zip(*[map(int,sys.stdin.readline().split...
def add(x=0,y=0): #Default parameter is someting that if a user does not insert the second value #it will not show the error return print(x+y) a = int(input("Enter a value for addition : ")) b = int(input("Enter second value for addition :")) add(a)
x = ["Farhan","Shaikh","Faheem"] for i in x: if(i == "Shaikh"): continue print(i)
def average(marks = int(input("Enter the marks of the Student : "))): if (marks >= 90): print("You have been passed with A grade") elif (marks >= 65 and marks <= 89): print("You have been passed With B grade") elif (marks >= 45 and marks <= 64): print("You have been passed with C gra...
height=input("Enter your height in foot : ") inch=input("Enter your height in inchs : ") weight=input("Enter your weight in kg's : ") meter_of_foot = float(height)/3.281 meter_of_inch = float(inch)/39.37 meter = meter_of_foot + meter_of_inch result = float(weight)/(float(meter)*float(meter)) print("From given input's y...
import numpy as np x = np.arange(0,20) print(x) #Will print 0 to 19 print(x[8]) #Will print the value which is on the 8 position (8) print(x[1]) #Will print the value which is on the 1 position (1) print(x[:10]) #Will print the numbers which are before 10 print(x[10:]) #Will print the numbers which are after 9 print(...
Balance = 999 Pin = 1234 def Check(): Check = int(input("Welcome to CodingBook ATM Please Enter your pin : ")) #Checks for the pin if Check == Pin: options() else: print(" Invalid Pin Please try again ") #Dosent ask for another try. exit() def options(): print(" Choose an optio...
# Given a string, find the length of the longest substring without repeating characters. # Examples: # Given "abcabcbb", the answer is "abc", which the length is 3. # Given "bbbbb", the answer is "b", with the length of 1. # Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a s...
# Given an integer, write a function to determine if it is a power of three. # Example 1: # Input: 27 # Output: true # Example 2: # Input: 0 # Output: false # Example 3: # Input: 9 # Output: true # Example 4: # Input: 45 # Output: false # Follow up: # Could you do it without using any loop / recursion? def isPowe...
from selenium import webdriver #driver is a variable name whch holds the session of the url driver = webdriver.Chrome(executable_path='D:\Python\chromedriver_win32\chromedriver.exe') #maximum default time to wait for elements to load: driver.implicitly_wait(10) driver.get("https://translate.google.com/") #current url w...
# Question A # first = 7 # second = 44.3 # print (first + second) # print (first * second) # print (second / first) # # x = 1 # y = 2 # if x > y: # print ("BIG") # if x < y: # print("SMALL") # # # season = 1 # if season == 1: # print ("summer") # elif season == 2: # print ("winter") # elif season == 3: ...
#Problem statement: Supervised learning algorithm is applied by Simple Linear Regression model #where the dataframe is divided into traing and test data frame and plot a graph for it #libraries are imported import numpy as np import pandas as pd import matplotlib.pyplot as plt #data file is read dataset=pd.read_ex...
<<<<<<< HEAD def makes10(a, b): ======= def makes10(a, b): >>>>>>> ec863b8dfbbeba8f5506e1f29976ea8308fddd9e return(a==10 or b==10 or a+b==10)
<<<<<<< HEAD def front_back(str): if len(str) <= 1: return str mid = str[1:len(str)-1] return str[len(str)-1] + mid + str[0] ======= def front_back(str): if len(str) <= 1: return str mid = str[1:len(str)-1] return str[len(str)-1] + mid + str[0] >>>>>>> ec863b8dfbbeba8f5506e1f29976ea8308fddd9e ...
# GRADED FUNCTION: is_overlapping def is_overlapping(segment_time, previous_segments): """ Checks if the time of a segment overlaps with the times of existing segments. Arguments: segment_time -- a tuple of (segment_start, segment_end) for the new segment previous_segments -- a list of tuples ...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name ...
import unittest from Programm.Sword import Sword class TestSwordMethods(unittest.TestCase): def test_name(self): s = Sword() self.assertEqual(s.name, "Меч") self.assertNotEqual(s.name, "Лук") self.assertEqual(s.damage, 10) def test_attack(self): s = Sword() sel...
import re pat = '^[456]\d{3}-?\d{4}-?\d{4}-?\d{4}$' c = r'(.)\1{3,}' t = int(input()) for _ in range(t): s = input() if re.search(pat, s) and not re.search(c,s.replace('-','')): print('Valid') else: print('Invalid')
#Function to convert sparse matrix into orignal matrix def orignal_mat(sparse_mat): row = sparse_mat[0][0] column = sparse_mat[0][1] #Initializing original matrix. orig_mat = [[0 for i in range(column)]for j in range(row)] #filling the orignal matrix with non zero terms from sparse matrix ...
""" Alogorithm to delete the middle node of the Linked_List 1). Declare 3 pointers slow_temp,temp,prev_temp. 2). Traverse the Linked List. 3). Move temp by two and slow_temp by one and while traversing track of previous of slow_temp storing it in prev_temp. 4). When temp reaches end of the Linked List, slow_temp r...
class Node: def __init__(self,value): self.left = None self.right = None self.value = value def insert(root,node): if root is None: root = node else: if root.value > node.value: if root.left is None: root.left = node else: ...
""" Algorithm:- To implement stack using one queue. 1. Create a class Queue. 2. Define methods enqueue, dequeue, is_empty and get_size inside the class Queue. 3. Create a class Stack with instance variable q initialized to an empty queue. 4. Pushing is done by enqueuing data to the queue. 5. To pop, the queue is ...
class Node: def __init__(self,data): self.value = data self.left = None self.right = None class Tree: def __init__(self): self.head = None def insert(root ,node): if root is None: root = node else: if root.value > node.value: if root.left is...
"""Algorithm 1. Scan the infix expression from left to right. 2. If the scanned character is an operand, output it. 3. Else, …..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty or the stack contains a ‘(‘ ), push it. …..3.2 Else, P...
class Node: def __init__(self,value): self.left = None self.right = None self.value = value def insert(root, value): if root == None: return Node(value) elif value < root.value: root.left = insert(root.left , value) elif value > root.value: ...
""" Algorithm to implement Queue using Stack:- 1.Take 2 Stacks, stack1 and stack2. 2.stack1 will be used a back of the Queue and stack2 will be used as front of the Queue. 3.Push() operation will be done on stack1, and pop() operations will be done on stack2. 4.When pop() are called, check is stack2 is empty, if ...
#Creating the function for merge_sort def merge_sort(a): # we will split the the list to left and right if there is more than one element in it. if(len(a)>1): mid = len(a)//2 #left half contain element from starting till one less than the middle element left = a[:mid] #R...
""" Z function of string s ia and array z, where z[i] value is amount of numbers from ith position in string s which are the same with first z[i] characters of string s """ def z_function_naive(s): z = [0 for _ in range(len(s))] for i in range(1, len(s)): j = 0 k = i while k < len(s)...
""" Given an array of numbers, segregate odd and even numbers Example: 3, 4, 1, 9, 5, 2 4, 2, 1, 3, 9, 5 """ def segregate(arr): tail = 0 for i in range(len(arr)): if arr[i] % 2 == 0: arr[tail], arr[i] = arr[i], arr[tail] tail += 1 arr[tail], arr[i] = arr[len(a...
""" Given an 2d array with numbers - prices, you can move from (0, 0) to (n, m) only right or down, find path of maximum cost. """ def prepare_array(arr): for i in range(1, len(arr[0])): arr[0][i] += arr[0][i - 1] for j in range(1, len(arr)): arr[j][0] += arr[j - 1][0] def find_path(arr): ...
""" Check whether linked list has loop """ from python.linked_list import Node def has_loop(head): fast, slow = head.next, head while fast is not None and \ fast.next is not None \ and fast != slow: fast = fast.next.next slow = slow.next return slow == fas...
""" Implement Aho-Corasik algorithm """ class Node(object): def __init__(self, char, is_root=False): self.char = char self.suffix_link = None self.children = {} self.is_root = is_root def build_trie(text): root = Node(char='', is_root=True) parent = root for c in tex...
""" Check whether sting is rotation of another """ def is_rotation(s1, s2): s1s1 = s1 + s1 return s1s1.find(s2) != -1 if __name__ == "__main__": s1 = "waterbootle" s2 = "ootlewaterb" print(is_rotation(s1, s2))
""" Given a stack, sort it values using an additional stack only. Operations like push, pop, peel and is_empty permitted. """ class Stack(object): def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): return self.stack.pop() def p...
""" Given a set of strings, print all anagrams together """ def collect_anagrams(words): d = {} for w in words: index = ''.join(sorted(w)) if index in d: d[index].append(w) else: d[index] = [w] return d if __name__ == "__main__": words = {"cat", "do...
""" Given an array with elements from 1 to n, but one is missing. Find missing element. """ def find_missing_arithm(arr, n): total_sum = n * (n + 1)/2 return total_sum - sum(arr) def find_missing_xor(arr, n): total = 0 actual = 0 for i in range(1, n + 1): total ^= i for v in arr: ...
""" There are n-pairs and therefore 2n people. everyone has one unique number ranging from 1 to 2n. All these 2n persons are arranged in random fashion in an Array of size 2n. We are also given who is partner of whom. Find the minimum number of swaps required to arrange these pairs such that all pairs become adjacent t...
""" The text is given. Each word of this text is scrambled(letters are permuted) Whitespaces are removed. The problem is to restore original text from scrambled if dictionary of words is given. Input: dict: {"world", "hello", "apple", "pear"} text: "ehlololwrd" Output: hello...
""" Convert sorted ddl to binary search tree """ class Node(object): def __init__(self, value): self.value = value self.next = None self.prev = None def find_mid(left, right): slow = left fast = left while fast != right: fast = fast.next if fast == right: ...
""" Print reverse of string recursive """ def print_reverse(s): if s: print_reverse(s[1:]) print(s[0]) if __name__ == "__main__": print_reverse("hello")
nom = input("quel est votre nom?") age = 0 while age == 0: age_str = input("quel age avez vous?") try: age = int(age_str) except: print("Entrez numero uniquement pour l'age") # print("fin de la boucle") print("mon nom est " + nom + "," + "j'ai " + str(age) + " ans.") print("l'age prochain e...
def func(): for i in range(a, b+1): if i % c == 0: X.append(i) if __name__ == '__main__': X = [] a = int(input('Введите первое число -> ')) b = int(input('Введите второе число -> ')) c = int(input('Введите третье число -> ')) func() val = ','.join(map(str, X)) prin...
import re def func(text): if text.isalpha(): result = ''.join([i for i in text if not i.isdigit()]) print('Букв -> ', len(''.join(c for c in result if c not in '?:!/; '))) elif text.isdigit(): x = re.findall('(\d+)', text) print('Цифр -> ', len(x[0])) elif text.isalnum(): ...
''' Use a Player class that provides attributes that store the first name, last name, position, at bats, and hits for a player. The class constructor should use these five attributes as parameters. This class should also provide a method that returns the full name of a player and a method that returns the batting a...
# Listのスライス nums = range(5) # rangeは整数範囲を作成する組み込み型関数です print(nums) nums = range(5, 10) # 5, 6, 7, 8, 9 print(nums) nums = range(0, 10, 3) # 0, 3, 6, 9 print(nums) nums = range(-10, -100, -30) # -10, -40, -70 print(nums) nums = range(1, 5, 1) print(nums) nums = range(5) print(num...
def bubble_sort (array , order = True) : # length = len (array) if order == True : for i in range (len(array)) : for j in range (0,len(array)-i-1) : if array[j] > array [j+1] : (array[j],array[j+1]) = (array[j+1],array[j]) return array elif or...
from gamelibwillh2 import* import random #this code will give us a cover and lets us click space to start def start(): game = Game(800,800,"Pacman") cover=Image("PacMan_Files\\cover.png",game) cover.resizeTo(800,800) while not game.over: game.processInput() cover.draw() ...
# Napisz klasę Python o nazwie Koło skonstruowaną za pomocą # promienia i dwóch metod, które obliczą obszar i obwód koła class Kolo(): def __init__(self, promien1): self.promien = promien1 def obszar(self): pi = 3.14 obszar1 = pi * self.promien ** 2 return obszar1 def obwo...
import numpy as np class Agent(object): # Constructor of the Agent class # <Params name="name" type="string">The name of the agent</Params> def __init__(self, name): super(Agent, self).__init__() self.name = name self.game_played=0 self.results=np.array([0,0,0,0,0], dtype=n...
import random word_bank = ['Do', "yOu", "KnOw", "dE", "wAY", "hOmE", "My", "BrOtHeR", "cLiCk", "ClIcK"] print(word_bank) the_word = random.choice(word_bank) print(the_word) guess_taken = '' letters_guessed = [] while guess_taken != 'quit': guess_taken = input("Guess a letter: ") guess_taken (10)
#!/usr/bin/python3 ''' Python script that, using this REST API, for a given employee ID, returns information about his/her TODO list progress. You must use urllib or requests module The script must accept an integer as a parameter, which is the employee ID The script must display on the standar...
has_food = False has_clothes = False from sys import exit import time def song(): print("""I'll be your dream, I'll be your wish, I'll be your fantasy. I'll be your hope, I'll be your love, be everything that you need. I love you more with every breath, truly madly deeply do I will be strong, ...
import socket class Resolver: def __init__(self): self._cache = {} def __call__(self, host): """__call__ makes instances of this class callable like a function e.g. resolver = Resolver() resolver("myhost") -- note this invokes the __call__ method The instruct...
import numpy from chainer import backend from chainer import initializer from chainer import utils # Original code forked from MIT licensed keras project # https://github.com/fchollet/keras/blob/master/keras/initializations.py class Orthogonal(initializer.Initializer): """Initializes array with an orthogonal sy...
import random import time #Players can create their name def newName(): print('>>>Please create a name for your player.<<<') global username username=input() print('***Name changed to >', username,'<***') print('\n\n') time.sleep(3) newName() #Intro scene one Note: Add more stories/le...
words = ['one', 'two', 'three', 'four', 'five'] x = 0 while(x < 5): print(words[x]) x += 1
def unflatten_dict(d): result = {} for key, value in d.items(): key_parts = key.split(".") rdict = result for part in key_parts[:-1]: if part not in rdict: rdict[part] = {} rdict = rdict[part] rdict[key_parts[-1]] = value return result ...
# the return values of key functions are checked instead of the original list def unique(a_list, key = lambda x: x): unique_elements = [] temp_list = [key(i) for i in a_list] for i in range(0,len(temp_list)): if temp_list[i] not in temp_list[i+1:]: unique_elements.append(temp_list[i]) ...
def is_pref(pref, Str): if(len(pref) > len(Str)): return False if(pref != Str[0:len(pref)]): return False return True def search(a, b): queue = [] reminder_a = set() reminder_b = set() for i in range(0, len(a)): for j in range(0, len(b)): i...
# unit testing for card class import unittest import card class TestCardFunctions(unittest.TestCase): def setUp(self): self.validValues = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Ace', 'King', 'Queen', 'Jack'] self.validSuits = { 1 :'Spades', 2 : 'Clubs', 3 : 'Hearts', 4 : 'Diamonds'} self.cardValue ...
class Card: suits = {1 : 'Spades', 2 : 'Clubs', 3 : 'Hearts', 4 : 'Diamonds',} def __init__(self, value, suit): self.suit = suit self.value = value def get_value(self): return self.value def __repr__(self): return str(self.value...
import abc import random class ShuffleStrategy(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def shuffle(self, deck): return class RandomShuffleStrategy(ShuffleStrategy): def shuffle(self, deck): return random.shuffle(deck) class AppendShuffleStrategy(ShuffleStrategy...
#9. Palindrome Number #https://leetcode.com/problems/palindrome-number/ class Solution: def isPalindrome(self, x: int) -> bool: y=str(x) if x>=0: a=int(y[::-1]) else: a=int(y[:0:-1]) return bool(x==a)
#Import the argv variable from the sys package from sys import argv #Set script and filename equal to the first and second arguments script, filename = argv #Print out the file name and give users instructions print("We're going to erase %r." %filename) print("If you don't want that, hit CTRL-C (^C).") print("If you ...
def fibo(n): if n < 0: raise ValueError, "argument must be positive" if n == 0: return 0 if n == 1: return 1 return fibo(n-1) + fibo(n-2)
import re from collections import Counter, defaultdict from typing import Dict # re maintains internal cache of recent compiled expression, but we're compiling and storing it for clarity anyway word_re = re.compile('[a-zA-Z]+') # will eat all the memory if the file is a huge single line def process(file: str) -> Dic...
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10, 10) # arg1 = start, arg2 = end, arg3 = number of points y = np.sin(x) plt.plot(x, y) plt.show() # Add some labels plt.xlabel("Time") plt.ylabel("Some function of time") plt.title("My cool chart") plt.show()
import numpy as np from pandas import DataFrame from patsy import dmatrices import dataframe as ka_df def predict(test_data, results, model_name): """ Return predictions of based on model results. Parameters ---------- test_data: DataFrame should be test data you are trying to predict ...
#!/usr/bin/env python3 input = open('day03.txt').read().strip().split('\n') def consider(numbers, position, criteria): bits = [x[position] for x in numbers] if criteria == 'most': return '1' if bits.count('1') >= bits.count('0') else '0' elif criteria == 'least': return '0' if bits.count(...
#!/usr/bin/env python3 import re input = open("day10.txt").read().strip() class CPU: def __init__(self, program: str) -> None: self.instructions = program.split("\n") self.X = 1 self.V = 0 self.cycle = 0 self.index = 0 self.command = None self.remaining = ...
#!/usr/bin/env python3 input = open("day08.txt").read().strip() map = [[int(c) for c in r] for r in input.split("\n")] def part1(): visible = 2 * len(map) + 2 * len(map[0]) - 4 for r in range(1, len(map) - 1): for c in range(1, len(map[r]) - 1): given = map[r][c] directions ...
#!/usr/bin/env python3 class Day9: def __init__(self, inputs): self.numbers = [int(x) for x in inputs.split('\n')] def check(self, preamble, number): length = len(preamble) for i in range(length - 1): for j in range(i + 1, length): if preamble[i] != preambl...
#!/usr/bin/env python3 NORTH = 'N' SOUTH = 'S' EAST = 'E' WEST = 'W' LEFT = 'L' RIGHT = 'R' FORWARD = 'F' class Ship1: def __init__(self): self.face = EAST self.position = [0, 0] def handle(self, instruction): action = instruction[0] value = instruction[1] if action =...
#!/usr/bin/env python3 def six_digit(digits): return len(digits) == 6 def same_adjacent_digits(digits): for i in range(len(digits) - 1): if digits[i] == digits[i + 1]: return True return False def not_part_of_larger(digits): # [i-1] != [i] == [i+1] != [i+2] for i in range(len(...
#!/usr/bin/env python3 rucksacks = [x for x in open("day03.txt").read().strip().split("\n")] def get_prioritie(item): if "a" <= item <= "z": return ord(item) - 96 elif "A" <= item <= "Z": return ord(item) - 38 return 0 def part1(): priorities = [] for items in rucksacks: ...
a = 10 b = 2 try: print('resource open') print(a/b) k = int(input('Enter a number')) print(k) except ZeroDivisionError as e:# not even e you can use another.... print('You cannot divide a number by zero',e) except ValueError as e: print('Invalid Input',':',e) except Exception as e: print...
def count_construct(target,word_bank=[]): table_size=len(target)+1 table=[] for i in range(table_size): table.append(0) #initialize table[0] with 1 as there is ONE way to create an empty string table[0]=1 #now iterate through the indices of the table for i in range(table_si...
m = [9,15,24] def modify(k): k.append(39) print(f'k = {k}') modify(m) f = [14,23,37] def replace (g): g = [17,28,45] print(f'g = {g}') replace(f) print(f'f = {f}') #The original f list is still the same and g is a new list #To replace f by g, we need to modify the contents like this: def replace_c...
import math print(math.sqrt(81)) print(math.factorial(5)) print(math.factorial(6)) n = 5 k = 3 print((math.factorial(5))/((math.factorial(3))*math.factorial(n-k))) #Since we know it will always return an integer, we can change it to integer division by addin double slashes instead of one print((math.factorial(5))...
import unittest import os def analyze_text(filename): number_of_lines=0 number_of_chars = 0 with open(filename, mode='rt', encoding='utf-8') as f: for line in f: number_of_lines = number_of_lines+1 number_of_chars+=len(line) print(f"Number of lines is {number_of_lines}")...
from typing import List, Any Fruits = ["apple", "orange", "pear"] print(Fruits) Fruits[1] = "Bannana" print(Fruits) Fruits[2]=7 print(Fruits) emptyList=[] print(emptyList) emptyList.append(1.5) print(emptyList) emptyList.append(2) print(emptyList) charList= list("characters") print(charList)