text
stringlengths
37
1.41M
# Display output using int / float to_round = [1/1, 1/2, 1/3, 5/2, 6/3] print("**** Numbers to round ****") print(to_round) print() print("**** Rounded Numbers ****") for i in to_round: if i % 1 == 0: print("{:.0f}".format(i)) else: print("{:.1f}".format(i))
import random NUM_TRIALS = 100 winnings = 0 cost = NUM_TRIALS * 5 for i in range(0, NUM_TRIALS): prize = "" round_wins = 0 for x in range(0, 3): prize_num = random.randint(1, 100) prize += " " if 0< prize_num <= 1: prize += "gold" round_wins ...
import random import math import matplotlib.pyplot as plt n = 10 omegaMax = 1200 N = 64 x = [] y = [] a = [] b = [] Dx = 0 Mx = 0 def Plot(): A = [] fi = [] for i in range(n): A.append(random.random()) fii = random.random() * omegaMax fi.append(fii) for i in range(N): ...
while True: try: n = int(input("Quantos termos o seu vetor: ")) x = [ ] for i in range(n): l = float(input("Digite o %d° do vetor : " % (i+1) )) x.append(l) print(x) except: print("Digite um numero!")
""" Solution to Return 0, 1 and 2 with equal probability using the specified function puzzle. """ from __future__ import print_function import random def get_a_random(): """ Get a random 1 or 0. Returns: int: 1 or 0 """ return random.randint(0, 1) def generate(): """ Return 0, ...
""" Given a string consisting of opening and closing parenthesis, find length of the longest valid parenthesis substring. """ def find_parenthesis(string): """ Find opening and closing parenthesis. Args: string (string): Input string to sarch in. Returns: string: Cleaned up version of ...
#!/usr/local/bin/python """ Find jumping numbers. """ def get_jumping_numbers(orgianl_number, input_int, results): """ Get all possible jumping numbers for a given integer. Args: orgianl_number (int): Orginal input numbers to search for jumping numbers in. input_int (int): Current int to ...
""" Solution to the Floyd Triangle puzzle. """ def get_user_input(): """ Get input from the user. Args: Returns: int: Number entered by the user. """ user_input = raw_input('Please enter the number of rows: ') try: return int(user_input) except ValueError: print...
# Списки и словари # Списки ''' Они являются упорядоченными коллекциями произвольных объектов Они поддерживают доступ по смещению Они имеют переменную длину, разнородны и допускают произвольно глубокое вложение Они относятся к категории "изменяемая последовательность" Они представляют собой массивы ссылок на объекты L...
import numpy as np import tensorflow as tf def softmax(x): """ Compute the softmax function in tensorflow. You might find the tensorflow functions tf.exp, tf.reduce_max, tf.reduce_sum, tf.expand_dims useful. (Many solutions are possible, so you may not need to use all of these functions). Recall also that m...
import numpy as np import random def softmax(x): """ Compute the softmax function for each row of the input x. It is crucial that this function is optimized for speed because it will be used frequently in later code. You might find numpy functions np.exp, np.sum, np.reshape, np.max, and numpy ...
#!/usr/bin/env python3 # """ # * Description: Find the Longest motif with at less 2 repeats: avoid overlapping motifs # * dna: a sequence of ATCG bp # * return: string # """ def longestMotif(dna): # unsure if DNA is in upper Cases dna = dna.upper() n = len(dna) ...
# The purpose of this program is to assist classmates understand the process of Gradient Descent # In order to use Gradient Descent, we will need various tools/formulas # A Pre-processed Training Set - Price per month of rent at apartment for X months # A way to Optimize the Training Set # Weights a,b respec...
import six import random import copy class HumanPlayer(object): ''' Initialize player with marker (X or O) ''' def __init__(self, marker=None): self.marker = marker def __str__(self): return 'Human player with marker : ' + self.marker def get_next_move(self, unoccuppied_places): ...
# 124. Binary Tree Maximum Path Sum # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # record in self.dp # key: TreeNode, value: [root.val, max(0, root...
def main(): edad = int(input("Ingresa tu edad: ")) edad >= 18 if edad ID = int(input("¿Tienes identificación oficial? (s/n): ")) if ID == s: print ("Trámite de licencia concedido") if ID == n: print ("No cum...
# global variable a = 1 b = 2 c = 3 def myFunction(): # local variable a = 5 print(a) # global variable global b b = 'global variable changed' print(b) # accessing global variable print(c) d = 'this will be deleted' del d # print(d) myFunction() print(a) print(b)
from collections import Counter a = Counter([1,2,3,1,2,5,3]) b={1:1,2:2,4:1} a.subtract(b) print (a) for (x,y) in a.items(): print (x,y)
# -*- coding: utf-8 -*- """ Unittest @author: Brennan Campbell """ import unittest from unittest.mock import Mock from Board import * class BoardTests(unittest.TestCase): def testPlacingMan(self): boardPoints = Mock() Board.placingMan(self, 0) Board.placingMan(self, 2) def testMoveMa...
class Node: def __init__(self): print("init node") def evaluate(self): return 0 def execute(self): return 0 class BlockNode(Node): def __init__(self, s): self.statements = [s] def execute(self): for statement in self.statements: statement.execu...
#!/usr/bin/env python import time import threading import multiprocessing class nothread(object): def foo(self): start=time.time() b=[] for i in range(1000000): b.append(i*i) print type(self),"Timing",str(time.time()-start)+'s' class threaded(nothread): def foo(sel...
# Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: # @param intervals, a list of Interval # @return a list of Interval def merge_two_intervals(self, x, y): if y.start > x.end: return None ...
# Uses python3 from sys import stdin def fibonacci_sum_squares_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current * current return sum % 10 def get_period_and_sum_sequ...
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd_euclid(a, b): if b == 0: return a elif a > b: if a % b != 0: return gcd_euclid(b, a%b) else: retur...
def partition(a,p,r): pivot = p for i in range(p+1,r+1): if(a[i]<a[pivot]): tmp = a[i] a[i] = a[pivot+1] a[pivot+1] = a[pivot] a[pivot] = tmp pivot = pivot + 1 return pivot def quickSort(a,p,r): if(r>p): q = partition(a, p, r)...
# python3 import sys def compute_min_refills(distance, tank, stops): # write your code here stops num_refills = 0 current_refill = 0 while current_refill <= len(stops)-2: last_refill = current_refill while current_refill <= len(stops)-2 and stops[current_refill+1]-stops[last_refill...
#problem1.py #Doing onenote problem1 that the teacher has given us #Jason Singh, 12 February import time def cardbalance(z,purchase,y,x): print("Intial Card Balance:{}".format(z)) time.sleep(1) print("Name of purchase: {}".format(purchase)) time.sleep(1) print("Cost of purchase: {}".format(round(y...
def drawStar(points,length): angle = 180-(180/points) import turtle turtle.begin_fill() turtle.clear() turtle.pendown() for i in range(0,points): turtle.forward(length) turtle.right(angle)
from random import randint, seed def merge(t1, s1, e1, t2, s2, e2, tout, s3, e3): i1 = s1 i2 = s2 for i in range(s3, e3): if i2 >= e2 or (i1 < e1 and t1[i1] <= t2[i2]): tout[i] = t1[i1] i1 += 1 else: tout[i] = t2[i2] i2 += 1 def _mergesort...
from simple_node import Node, tab2list from random import randint def count(p): n = 0 while p is not None: n += 1 p = p.next return n def insert_into_bucket(b, node): p = b q = b.next while q is not None and q.value > node.value: p = q q = q.next node.nex...
from sklearn.cluster import KMeans import pandas as pd class Cluster: """ Class for clustering data args: self.data_pts (numpy.matrix): coordinates for the data points self.data_ids (numpy.array): Unique identifiers for individual data pts self.number_of_clusters (int): number of cl...
# Create a list with the first ten triangular numbers # (see https://oeis.org/A000217) L = [ i*(i+1)/2 for i in range(10)] # Create a function to test if a number is prime def is_prime(n): """ Test if ``n`` is a prime. """ if n < 1: return "Input number is either negative or 0" elif n in ...
import random import sys dados_ataque = [0, 0, 0] dados_defensa = [0, 0, 0] fichas_ataque = 6 fichas_defensa = 4 simulaciones = 10000 vict_ataque = 0 vict_defensa = 0 cant_d_defensa = 0 cant_d_ataque = 0 def jugar(fatq, fdef): global cant_d_ataque global cant_d_defensa comparar = 3 while fatq > 1 and...
"""chạy vòng lặp while với với điều kiện i <6 tăng biến đếm i nếu không vòng lặp sẽ chạy vv với điều kiện """ i = 1 while i<6: print(i) i+=1 """dừng vòng lặp while khi điều kiện i==3 đúng với lệnh break""" i = 1 while i<6: print(i) if i==3: break i+=1 #tiếp tục chạy vòng lặp while in ra i khi cả...
#Tạo 1 class đơn giản class myclass: x="41" #gọi class vừa tạo p1 = myclass() print(p1.x) ## class Demo: def __init__(self,name, age): self.name = name self.age = age p1 = Demo("Bảo",23) p2 = Demo("Tùng",22) print(p1.name) print(p1.age) print(p2.name) print(p2.age) #...
# Following function "area" takes a float value as # radius of the circle and returns the area of that circle. def area(radius: float): print(f"\nThe radius of the circle is '{radius}'\nThe area " f"of the circle is '{(radius ** 2) * 3.14}'")
#!/usr/bin/env python3 # coding: utf-8 # """Print the commands in some ("my") directories of the ones listed in PATH These "my" directories are determined as: (1) Directories beginning with my home directory (for something like /home/me/bin) if this directory is not listed with a '-' sign at the beginning in t...
"""Exercise : Odd Tuples Write a python function oddTuples(aTup) that takes a some numbers in the tuple as input and returns a tuple in which contains odd index values in the input tuple""" def oddTuples(a_tup): ''' a_tup: a tuple returns: tuple, every other element of a_tup. ''' # Your C...
# coffee-machine.py #jetbrains academy project def start(): while True: global water_avl, milk_avl, beans_avl, cups_avl, money_avl take_action() def inventory(water=0,milk=0,beans=0,cups=0,money=0): global water_avl, milk_avl, beans_avl, cups_avl, money_avl, resources water_avl ...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # # # * | | vehicle 0 | vehicle 1 | ...... | vehicle n | vehicle n+1 | # * time0 | roadID0 | maxSpeed | lanes_no | x | v | a | l | x | v | a | l | .......| x | v | a | l | # * tim...
# is_raining = False # is_cold = True # print(type(is_raining)) # print(is_cold) # print(type(is_cold)) # print(is_raining) # print(not is_raining) # print(is_raining and is_cold) # print(is_raining and not is_cold) # print(is_raining) #F # print(not is_raining) #T # print(is_raining or is_cold) #T # print(is_raining...
chilli_wishlist = ["igloo", "chicken", "donut toy", "cardboad box"] # chilli_wishlist.append('dig mat') # chilli_wishlist.extend(['kong', 'tennis ball', 'crocodile toy']) # print(chilli_wishlist) # #indexing # print(len(chilli_wishlist)) # print(chilli_wishlist) # print(type(chilli_wishlist)) # print(chilli_wishlist...
ratstr=input('Enter a number: ') try: ival=int(ratstr) except: ival=-1 if ival>0: print('Nice work') else: print('Not a number')
index=-1 fruit = 'banana' while index < len(fruit): letter=fruit[index] print(letter) index=(index-1)
import csv row = ['2', ' Marie', ' California'] # with open('people.csv', 'r') as readFile: # reader = csv.reader(readFile) # lines = list(reader) # lines[2] = row # with open('people.csv', 'w') as writeFile: # writer = csv.writer(writeFile) # writer.writerows(lines) # readFile.close() # writeFile.close...
""" Data transformers. """ from itertools import islice class GeneratorPipeline: """Concatenates together a group of generators transforming original data into format ready for model's training. The pipeline makes two assumptions about generators passed into its constructor: 1) A `source` ge...
def matched(s): c=0 for i in range(len(s)): if s[i]=="(": c=c+1 if s[i]==")" : if c==0: return (False) else: c=c-1 if c==0: return(True) else: return(False)
from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: n=len(nums) low=0;mid=0;high=n-1 while(mid<=high): if nums[mid]==1: mid+=1 elif nums[mid]<1: nu...
__author__ = "Jonas Geduldig" __date__ = "June 8, 2013" __license__ = "MIT" import time class TwitterRestPager(object): """Pagination iterator for REST API resources""" def __init__(self, api, resource, params=None): """Initialize with an authenticated instance of TwitterAPI :param api: A TwitterAPI obje...
qtd_convidados = int(input("Quantidade de convidados: ")) if (qtd_convidados >= 5): print("O numero nao pode ser maior que 5") quit() print("\n--------------------\n") lista_convidados = [] for item in range(qtd_convidados): nome_convidado = input(f"Informe o nome do convidado número {item+1}: ") li...
import requests import json def search_movie(movie_name = 'interestellar'): try: response = requests.get('https://api.themoviedb.org/3/search/movie?api_key=20d0453e2b57cb10e3203c454698e785&language=en-US&query=' + movie_name) return json.loads(response.text) except Exception as e: prin...
""" ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits. If the function is passed a valid PIN string, return true, else return false. """ import re def validate_pin(pin): # return True or False pattern = r'^(\d{4})|(\d{6})' return re.fu...
""" Collection (array, set, etc.) helper methods and classes. """ from collections import defaultdict class AttrDict(dict): """ From http://code.activestate.com/recipes/576972-attrdict Uses __dict__ to subvert all __getattribute__ methods """ def __init__(self, *args, **kwargs): dict.__ini...
""" Inspection methods for generic Python constructs. """ def class_properties(klass): """ For a given class, return a tuple (name, property) of the properties of the class. For example, given this class: class Foo(object): def __init__(self, val): self._val = val @propert...
print("Winning Rules of Rock paper scissor game as: \n" + "Rock vs paper->paper wins \n" + "Rock vs scissors->Rock wins \n" + "paper vs scissors->scissors wins \n") user1=input("enter your choice(rock,paper,scissors):") user2=input("enter your choice(rock,paper,scissors):") print(f"\nuser1 chose {us...
# -*- coding: utf-8 -*- """ Created on Fri Mar 4 11:15:07 2016 @author: Madeleine LOLIMIT.py A helper function to test the lower limit of uncertainty for a sini to see whether it will yield a result. * lolimit(sini,siniu,inc= ) calculates the lower limit of a sini according to its calc'd uncertaint...
#!/usr/bin/env python import random from typing import List, Tuple Lists = List[List[int]] def binary_search_r( numb: int, left: int, right: int, a: list, step=0) -> Tuple[int, int]: """Recursive binary search algorithm :param numb: number for search :param left: left element :param right: r...
"""IMAGE PROCESSING, FIRST PART - LAB 1""" #!/usr/bin/env python3 from PIL import Image as Image # NO ADDITIONAL IMPORTS USED! ##PART 1 - DEFINE SOME HELPER FUNCTIONS def index_1d(image,x,y): """ Helper function. Converts image's 2d index into a 1d index """ w=image['width'] return w*y+x def black_image(image, v...
from __future__ import print_function # use python 3 syntax but make it compatible with python 2 from __future__ import division # '' import time # import the time library for the sleep function import brickpi3 # import the BrickPi3 drivers def main(): #Initialize components ...
import sqlite3 DB_FILE = "internetblogs.db" def init_db(): # create a database named backup cnt = sqlite3.connect(DB_FILE) cnt.execute('CREATE TABLE users(BLOG TEXT, EMAIL TEXT);') def create_connection(db_file=DB_FILE): conn = None try: conn = sqlite3.connect(db_file) except Except...
# -*- coding: utf-8 -*- import pygame import math import time from CarImage import * from CarObject import * import time class Iteration: def __init__(self): #Variables keeping the top two fitness scores of the car. #Calculation algorithm is detailed below. self.best = 0 self.second ...
#encoding:utf-8 #practice 24 print "Let's practice everything" print 'You\'d need to know \'bout escapes with \\that do \n newlines and \t tabs.' poem=""" \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere th...
#practice 6 x="There are %d types of people." %10 binary="binary" #binary- do_not="don't" y="Those who know %s and those who %s."%(binary,do_not) print x print y print "I said:%r."%x print"I also said:'%s'."%y #ΪʲôСһûУ hilarious=False #hilarious-ֵġdzġϲԽ joke_evaluation="Isn't that joke so funny?!%r" #evaluation-...
def checkIndex(key): """ is the key a acceptable index ? In order to be accepted, the key should be a non-negative integer. """ if not isinstance(key, (int, long)): raise TypeError if key < 0: raise IndexError class ArithmeticSequence: def __init__(self, start = 0, step = 1): """ ...
arr_len = 7 arr = [0,0,1,0,0,1,0] # this method finds out the jumping on the clouds #reference problem : https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup def jumping_on_clouds(arr,arr_len): position = 0 ...
n = int(input('Enter the number')) i = 0 while(i<=n): if n%5 == 0: if n%2 == 0: continue print(i, end = ' ') i+=1
import itertools class a4q3: """ Construct cartesian product for attacker * defender and return expected value of loss of attacker. Examples: Attacker rolls 2 dice and defender rolls 1 die. >>> battle1 = a4q3(2,1) >>> battle1.e_value() ...
import xlrd from collections import Counter workbook = xlrd.open_workbook('telegramLang.xlsx') worksheet = workbook.sheet_by_index(0) i = 0 list_of_user_languages = [] while i < 10002: list_of_user_languages.append(worksheet.cell(i, 0).value) i += 1 def lang_adder(input_lang_string, input_l...
import math from util import * from reverse import reverse def encode(key, message): result = '' for i in range(0, len(message), 3): eggs = message[i:i+3] eggs = string_to_decimal(eggs) for _ in range(0, 3): eggs = eggs ^ (key[eggs&0x3] << 8) # debug_egg(bin(e...
import turtle t=turtle.Turtle() t.shape("turtle") def shape(n): for i in range(n): t.forward(100) t.left(360/n) n=int(input("몇각형을 만들까욤?:")) shape(n) n=int(input("몇각형?")) shape(n) n=int(input("몇각형?")) shape(n)
def react(text): stack = [] for letter in text: if not stack: stack.append(letter) else: l = stack[-1] if letter != l and l.lower() == letter.lower(): stack.pop() else: stack.append(letter) return len(stack) d...
import csv import pandas as pd def gender_dict(): return {u'男香': 'Male', u'女香': 'Female', u'中性香': 'Unisex'} def brand_dict(): """Get brand name dictionary, Chinese names as key, English names as value""" reader = csv.reader(open('../cn_en/brand_names.csv', 'r')) brand_dict = {} for row in reader: ...
# Kivy Four Function calculator (35pts) # emulate the built in MACOS calculator app as best you can. # GENERAL LAYOUT (10pts) # Make a GridLayout with 6 rows # Place a text input for the display in the first row # Row 2 through 6 will be BoxLayouts which will contain buttons. # Make a custom button class to simplify y...
if __name__ == '__main__': ## creates the basis for how the program is going to intake and return data birthdays = { # creates the dictionary and labels it 'Quentin Tarantino': '03/27/1963', 'Kanye West': '06/08/1977', 'James Baldwin': '08/02/1924', 'Ingmar Bergman': '07/14/19...
import random def mover(start_pos,player,s_count): current_pos=start_pos die_role=random.randint(1,6) print(die_role) current_pos=current_pos + die_role if current_pos in [3,5,15,18,21,12,14,17,31,35]: print ("snake/ladder") if (current_pos in [12,14,17,31,35] and player==2 and s_count==0): s...
def format_name(first_name, last_name): if (first_name =="" and last_name == ""): string = "" elif first_name =="": string = "Name: " + last_name elif last_name =="": string = "Name: " + first_name else: string = "Name: " + last_name + ", " + first_name return string print(format_name("Ernest", "Hemingwa...
def rev(s): s = s[::-1] return s s = "reverse a string" print(rev(s))
n = int(input("enter number of alphabets : ")) sample = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i in range(n+1): for s in range(n): print(" ",end="") n=n-1 for c in range(i): print(f"{sample[i-1]}",end=" ") print("") ''' A B B C C C D D D D E E E E E F F F F F F G G G G G G G '''
#!/usr/bin/python3 num = int(input("enter the number")) x=num*2-1 for i in range(1,num+1): for m in range(x,0,-1): print(" ",end=("")) x=x-2 for j in range(1,i+1): print(j,end=(" ")) print("") ''' 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 '''
""" Class to create all Buttons. """ import pygame class Button(object): def __init__(self, screen, profile, colors, dimension, text=None, action=None, icon=None): self.screen = screen self.profile = profile self.colors = colors self.x = dimension['x'] self.y = dimension['y...
import sqlite3 # To open a connection with the database. conn = sqlite3.connect('employees.db') # To create a cursor object to perform operations on database. cur = conn.cursor() # code goes here # Using the cursor to create the database if the database does not exists cur.execute(""" CREATE TABLE IF NOT EXISTS emplo...
import numpy def sort_des(mass): for i in range(1,len(mass)): temp=mass[i] j=i; while(j>0 and mass[j-1]<temp): mass[j]=mass[j-1] j-=1 mass[j]=temp return mass def sort_as(mass): for i in range(1,len(mass)): temp=mass[i] j=i; whi...
#!/usr/bin/env python3 """ Computer-based immigration office for Kanadia """ __author__ = 'Anne Simon and Rana ElSafadi' __email__ = "anne.simon@mail.utoronto.ca and rana.elsafadi@mail.utoronto.ca" # imports one per line import re import datetime import json def decide(input_file, watchlist_file, countries_file):...
import RPi.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) #specifies that we are referring to the pins by the number of the pin printed on the board switch_in = [12,16,18] switch_out = [7,13,15,29,31] def switch_init(switch_in,switch_out): print("Output pins") for i in switch...
#!/usr/bin/env python # coding: utf-8 # # Introduction to Linear Regression # # In linear regression, we seek to determine: # # - the linear relationship between two variables $x$ and $y$ # # - the robustness of the relationship, i.e., how well the variations in $x$ explain the variations in $y. # # As we will see...
#!/usr/bin/env python # coding: utf-8 # # Example: Sensitivity of Standard Deviation to Sampling # # As you may have already realized, the sample mean and variance/standard deviation of our data often depend on the sample size of the data and how random the values in our sample are. Another important thing to note is...
#!/usr/bin/env python # coding: utf-8 # # Filtering in the Time Domain: Part I # # In this section, we will explore some simple techniques to filter time series in the *time domain*. To familiarize ourselves with the concept of filtering, we will take a look at a two common examples of filtering in the fields of clim...
#!/usr/bin/env python # coding: utf-8 # # Filtering in the Frequency Domain: Discrete Fourier Transform # # In the previous sections, we learned several methods of filtering and smoothing data in the time domain. A much more powerful way of filtering data is in the *frequency* domain. # # To work in the frequency d...
# Rock Paper Scissors Game by Brandon Dols # import random functions from random import seed from random import choice from random import shuffle # main function def main (): # seed random number generator seed(777) # prepare a weapon_range from 0 to 2 weapon_range = [i for i in range(3)] ...
# Given a string of words, you need to find the highest scoring word. # Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc. # You need to return the highest scoring word as a string. # If two words score the same, return the word that appears earliest in the original ...
import math # accum("abcd") -> "A-Bb-Ccc-Dddd" # accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" # accum("cwAt") -> "C-Ww-Aaa-Tttt" def accum(s): start = 1 final = [] for i in range(len(s)): new_list = [] alpha = s[i] for j in range(i + 1): if j == 0: ...
# -*- coding: utf-8 -*- """ Created on Fri Oct 5 21:07:29 2018 @author: njayj """ #TAATGCCATGGGATGTT def debruijn(str, k): edges = [] nodes = set() for i in range(len(str)-k+1): edges.append((str[i:i+k-1], str[i+1:i+k])) nodes.add(str[i:i+k-1]) nodes.add(str[i+1:i+k]) ...
# Dictionaries for inventory of a store Price = { 'Couch': 599, 'TV': 710, 'Coffee table': 70, 'Bed': 349, 'Table': 199 } Inventory = { 'Couch': 5, 'TV': 10, 'Coffee table': 19, 'Bed': 7, 'Table': 13 } # Calculated the value of the inventory value = 0 for key...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 24 17:43:46 2020 @author: timoschloemer """ def maintainMachine(machinesPerSite, C, P, first): counter = 0 if (first): machinesPerSite -= C while (machinesPerSite > 0): machinesPerSite-=P counter ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 29 18:35:53 2018 @author: root """ """ def even_odd(A): next_even , next_odd = 0, len(A) - 1 while next_even < next_odd: if A[ next_even ] % 2 == 0: next_even += 1 else: A[ next_even ], A[next_odd] = ...
""" Task to chek if the given number is mobile number or not without using a counter variable like count. Conditions to qualify for a number to be a mobile number: 1. Length must be 10 2. First digit of the number should start from 9, 8, or 7 Hints: 1. Formula to extract the first digit of the number. I used floor di...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 28 11:04:29 2018 @author: root """ """ 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 """ """ n = int(input('n-->')) for i in range(1, n+1): #iterations = 1, 2, 3, 4, 5 example n = 5 print('{:^30}'.format(' ')) for m in range(1,11): c = i * m ...
#!/usr/bin/env python #Program to sort the words in a given sentence without using the 'sort' function. n = input('Enter the value of n: ').lower() str_split = n.split() length = len(str_split) new_str = [] for i in range(0, length): m = min(str_split) #gets you the word according to the ASCII value ind = str...
n = input('Enter any string to check for palindrome: ') n1 = '' n2 = '' for i in n: n1 = n1+i print('='*20) for j in range(1, len(n)+1): # print('j is and xx: ',j, n[-j]) n2 = n2+n[-j] print('n1 is: ', n1) print('n2 is: ', n2) if n1 == n2: print('String is palindrome: ', n1) else: ...
lis=[x*x for x in range(10)] print(lis) print("Generator: ") gene_ex=(x*x for x in range(10)) print(gene_ex) for i in range(10): print(next(gene_ex)) def fib(max): n,a,b=0,0,1 while n<max: a,b=b,a+b n=n+1 print(a) return 'done' print(fib(10)) def fib1(max): n,a,b=0,0,1...