text
stringlengths
5
121k
"""Program that Given a pile of coins of different values, determine the fewest number of coins needed to meet a given amount total""" def makeChange(coins, total): """Function that Given a pile of coins of different values, determine the fewest number of coins needed to meet a given amount total""" if t...
from exceptions import * from settings import player_lives from random import randint from datetime import datetime class Enemy: def __init__(self, lives, level = 1): self.level = level self.lives = lives @staticmethod def select_attack(): return randint(1, 3) def decrease_...
def asciiSum(li): l = [] for i in range(len(li)): summ = 0 for i in li[i]: summ += ord(i) l.append(summ) return l li = ['HELLOW', 'hellow'] print(li) print(asciiSum(li))
from app.db import Base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import validates import bcrypt salt = bcrypt.gensalt() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), nullable=False) email = Column(String(50),...
""" Decorators with (optional) arguments """ import functools def add(extra_n): def _add(function): @functools.wraps(function) def __add(n): return function(n + extra_n) return __add return _add @add(extra_n=1) def eggs(n): return 'eggs' * n print(eggs(1)) pr...
import asyncio async def sleeper(delay): await asyncio.sleep(delay) print('Finished sleeper with delay: %d' % delay) print('Start program') loop = asyncio.get_event_loop() tasks = (sleeper(1), sleeper(3), sleeper(2)) results = loop.run_until_complete(asyncio.wait(tasks)) print('End program') """ Even t...
""" `A generator` is a specific type of iterator taht generates values through a function. While traditional methods build and return a `list` of iterms, ad generator will simply `yield` every value separately at the moment when they are requested by the caller. Pros: - Generators pause execution completely u...
""" The 'functools' library is a collection of functions that return callable objects. Some of these functions are used as decorators. partial - no need to repeat all arguments every time reduce - combining pairs into a single result(Mostly use in the recursive function) """ import collections import functools impo...
from enum import Enum, auto class Directions(Enum): right = auto() left = auto() up = auto() down = auto() def move(direction): if not isinstance(direction, Directions): raise ValueError('Cannot move in this direction') return f'Moving {direction.name}' if __name__ == "__main__": ...
def divisao(n1, n2): if n2 == 0: return return n1 / n2 divide = divisao(8,2) if divide: print(divide) else: print('Conta Invalida') def divisao(n1, n2): if n2 == 0: return return n1 / n2 divide = divisao(60,4) if divide: print(divide) else: print('Conta Invalida...
class Pessoa: ano_atual = 2020 def __init__(self, nome, idade): self.nome = nome self.idade = idade def get_ano_nascimento(self): print(self.ano_atual - self.idade) @classmethod def por_ano_nascimento(cls, nome, ano_nascimento): idade = cls.ano_atual - ano_nascimento ...
from datetime import datetime today = datetime.now() fileDate = today.strftime('%Y-%m-%d-%H-%M-%S') print("Select starting integer: ", end = '') start = input() start = int(start) num = 0 calculating = True log = open("{0}_working.log".format(fileDate), "w") while True: now = datetime.now() timeCode = now.st...
from functions import create_new_passwords, view_passwords, random_password, logout, get_user_id class Password_manager: def __init__(self): self.username = '' self.id = 0 def menue(self): print('1. Add new site and password') print('2. View existing sites and password...
from turtle import Turtle, Screen from random import choice, randint drawer = Turtle(shape ='circle') drawer.color('red') drawer.width(10) drawer.speed(15) screen = Screen() color = ['cornsilk', 'aquamarine2', 'firebrick2', 'DodgerBlue4', 'green3', 'DeepPink4', 'orange', 'DeepSkyBlue4', 'gold1'] for x in range(3000):...
from turtle import Turtle, Screen from random import choice drawer = Turtle(shape ='circle') drawer.color('red') drawer.width(3) screen = Screen() drawer.up() drawer.goto(0, -200) drawer.down() color = ['black', 'red', 'blue', 'green', 'purple', 'orange', 'darkblue'] for x in range(3, 40): drawer.color(choice(col...
def sumar(op1,op2): print ("El resultado de la suma : ",op1," + ",op2," = ",op1+op2) def restar(op1,op2): print ("El resultado de la resta : ",op1," - ",op2," = ",op1-op2) def multiplicar(op1,op2): print ("El resultado de la multiplicacion : ",op1," x ",op2," = ",op1*op2) def dividir(op1,op2): print ("...
tupla1=("Hola","Mi",25,"nombre",25) print("Elemento en la posicion 2 : ",tupla1[2]) print("///////") lista=list(tupla1) print("Tupla convertirda en lista\n",lista) print("///////") tuplar=tuple(lista) print("Lista convertida en tupla\n",tuplar) print("///////") print("Hola" in tupla1) print("///////") pr...
def mergeSort(lista): if len(lista) <= 1: return lista medio = len(lista) / 2 izquierda = lista[:medio] derecha = lista[medio:] izquierda = mergeSort(izquierda) derecha = mergeSort(derecha) return merge(izquierda, derecha) def merge(listaA, listaB): lista_nueva = [] a = 0...
""" Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If not two numbers sum up to the target sum, the function should return an empty...
def spellcheck(inputfile): filebeingchecked=open(inputfile,'r') spellcheckfile=open("words.txt",'r') dictionary=spellcheckfile.read().split() checkedwords=filebeingchecked.read().split() for word in checkedwords: low = 0; high=len(dictionary)-1 while low <= high: ...
def main(): n = 42 s = "This is a %s string" % n print (s) if __name__ == '__main__': main()
def catalan(n): if n <=1: return 1 ress = 0 for i in range(0,n): ress+=catalan(i)*catalan(n-i-1) return ress def catalan_dynamic(n,res): for i in range(2,n): res[i] = 0 for j in range(0,i): res[i]+=res[j]*res[i-j-1] return res[n-1] n = int(input('Enter the value of n')) res = [0] * (n+1) res[0]...
def max_sum(array,n): till_this = 0 except_this = 0 for i in array: new_except = except_this if except_this > till_this else till_this till_this = except_this+i except_this = new_except return(except_this if except_this > till_this else till_this) t = int(input()) res = [] for i in range(t): size = int(in...
def palindromeIndex(s): s_r = s[::-1] len1 = len(s) if s == s_r: return -1 else: i = 0 s_ar = list(s) while i < len1//2: if s_ar[i] != s_ar[len1-1-i] : if s_ar[i+1] == s_ar[len1-1-i] and s_ar[i+2]==s_ar[len1-1-i]: return i ...
from turtle import Turtle, Screen from random import randint, choice don = Turtle() don.color('purple3') don.speed('fastest') screen = Screen() screen.colormode(255) def random_color(): """ Returns a random R, G, B color. :return: Three integers. """ r = randint(0, 255) g = randint(0, 255)...
from turtle import Turtle FONT = ('Courier', 24, 'normal') class Score(Turtle): def __init__(self): super().__init__() self.penup() self.pencolor('black') self.hideturtle() self.score = 0 self.score_print() def score_print(self): self.goto(0, 300) ...
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { ...
from turtle import Turtle, Screen from states import States from score import Score screen = Screen() screen.title("U.S. State Game") image = 'blank_states_img.gif' screen.addshape(image) screen.tracer(0) screen.setup(width=900, height=900) states_map = Turtle(image) states = States() score = Score() while score.sco...
def signo(dia:int, mes:int): if mes == 1: if dia>=1 and dia<=20: print("Tu signo es capricornio.") elif dia>=21 and dia<=31: print("Tu signo es acuario.") else: print("Introduce un dia valido para este mes.") elif mes == 2: if dia>=1 and dia<=...
class Vector: def __init__(self, d): if isinstance(d, int): self.coords = [0]*d if isinstance(d, list): self.coords = d def __len__(self): return len(self.coords) def __getitem__(self, j): return self.coords[j] def __setitem__(self,...
def intersection_list(lst1, lst2): maximum_len = max(max(lst1), max(lst2)) length = maximum_len + 1 lst = [None] * length for index in range(len(lst1)): lst[lst1[index]] = lst1[index] intersection_list = [] for index in range(len(lst2)): if lst[lst2[index]] != None: ...
class ArrayStack: def __init__(self): self.data = [] def __len__(self): return len(self.data) def is_empty(self): return len(self) == 0 def push(self, val): self.data.append(val) def top(self): if (self.is_empty()): raise Empty("...
import os import csv uploading_file = os.path.join("Resources\election_results.csv") saving_file = os.path.join("analysis", "election_analysis.txt") total_votes = 0 candidates = [] candidate_votes = {} winning_candidate = "" winning_count = 0 winning_percentage = 0 with open(uploading_file) as...
try: value = 10/0 number = int(input("Enter a number: ")) print(number) except ValueError as err: print(err) except ZeroDivisionError as zero: print(zero)
def validate_base_sequence(base_sequence, RNAflag): """Return TRUE if the string base_sequence contains only upper- or lowercase T (or U if RNAflag), C, A, and G characters, otherwise FALSE""" seq = base_sequence.upper() return len(seq) == (seq.count('U' if RNAflag else 'T') + seq.count('C') + seq.count('A') + ...
from graphics import * import random def genRandomPoints(amount, winWid, winLen): pointsSet = [] for i in range(amount): x = random.randint(0, winWid) y = random.randint(0, winLen) point = {"x": x, "y": y} pointsSet.append(point) return pointsSet def drawPointsSet(pointsSet, color, window): ...
def get_output(number: int) -> str: """ Return the correct string to print for the number, following FizzBang rules """ output = "" if number % 3 == 0: output += "Fizz" if number % 5 == 0: output += "Buzz" if not output: output = str(number) return output if ...
def linear_search(arr, target): for item in range(0, len(arr)): if arr[item] == target: return item return -1 def binary_search(arr, target): start = 0 end = len(arr) - 1 while start...
def fast_mul(x,y): if (x == 0 and y == 0): return 0 xlist = div2(x) ylist = mul2(y, len(xlist)) sum = 0 for i in range(len(xlist)): if (xlist[i] % 2 != 0): sum += ylist[i] return sum def div2(num): resList = [num] while num > 0: temp = num // 2 ...
def transpose(x): return [list(i) for i in zip(*x)] a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(transpose(a))
""" 날찌 : 2021/04/30 이름 : 김승용 내용 : 파이썬 최대값 / 최소값 연습문제 """ scores = [62, 82, 76, 88, 54, 92] max = scores[0] min = scores[0] for score in scores: if max < score: max = score if min > score: min = score print('최대 값 : ', max) print('최소 값 : ', min)
""" 날짜 : 2021/04/27 이름 : 김승용 내용 : 교재 실습 p52 """ oneLine = 'this is one line string' print('t 글자 수 : ', oneLine.count('t')) print(oneLine.startswith('this')) print(oneLine.startswith('that')) print(oneLine.replace('this', 'that')) multiLine = """ this is multi line string """ sent = multiLine.split('\n') ...
""" 날짜 : 2021/05/13 이름 : 김승용 내용 : 사전평가 """ scores = [] while True: print('0 : 종료', '1 : 입력') result = input('입력 : ') if result == '0': break score = int(input('점수입력 : ')) scores.append(score) print('입력한 점수 확인') print(scores) sum = 0 for score in scores: sum += score print('리스트 총...
name1 = "Lee" name2 = "Greg" name3 = "Rudy" print("{:>30}{:>30}{:>30}".format(name1, name2, name3)) name4 = input("Submit another for the sacrifice: ") print("{:>30}".format (name4))
import numpy as np import pandas as pd import pandas import matplotlib.pyplot as plt data = pandas.read_excel('sampledata.xlsx') print(data.shape) data.head() X = data['lift1_True'].values Y = data['lift2_Predict'].values mean_x = np.mean(X) mean_y = np.mean(Y) m = len(X) numer = 0 denom = 0 ...
import numpy as np def simpsonsrule(f, x0, xf, n): if n & 1: print ("Error: n is not a even number.") return 0.0 h = float(xf - x0) / n integral = 0.0 x = float(x0) for i in range(0, n / 2): integral += f(x) + (2.0 * f(x + h)) x += 2 * h integral = (2.0 *...
hole = [ 1, 0, 0, 0, 1, 0, 1, 0, 2, 1 ] def count_holes(num): try: int(num) except (TypeError, ValueError): return print ('error') else: str(num) if num[0] == '0': numers = int(num[1:]) else: numers = int(num) holes = 0 while (numers > 0) : ...
""" Write a Python program to check if a given positive integer is a power of two """ def isInt(x): x = abs(x) if x > int(x): return False else: return True def check_if_power_of_two(value): if value >= 1: if value == 1 or value == 2: return True el...
import time import datetime import calendar def timing(f): def wrap(*args): time1 = time.time() ret = f(*args) time2 = time.time() print('{} function took {} ms'.format(f.__name__, (time2-time1)*1000.0)) return ret return wrap def printProgressBar (iteration, total, pre...
print("hello") a = 1 print("a = %d"%a) a = 1 print("a = %d"%a,end="") a = 1
""" @version: Python 3.6 @author: Admin @license: Apache Licence @contact: yang.hu@live.com @software: PyCharm @file: class.py @time: 2017/3/7 10:07 类的初始化 """ """ class dog: def __init__(self,name): print("Hello Dog!") self.Name = name def sayname(self): print("Hello My name is Ba...
""" @version: Python 2.7 @author: Admin @license: Apache Licence @contact: yang.hu@live.com @software: PyCharm @file: Querying Data mysql.py @time: 2017/1/17 14:10 """ import datetime import mysql.connector config = { 'user': 'root', 'password': '123456', 'host': '127.0.0.1', 'database': 'db1', 'raise_...
""" In this project you will implement two encryption/decryption systems, one using AES in CBC mode and another using AES in counter mode (CTR). In both cases the 16-byte encryption IV is chosen at random and is prepended to the ciphertext. For CBC encryption we use the PKCS5 padding scheme discussed in the lecture (1...
import math def net_degree(degree): net = degree%360 return net def degree_to_radian(degree): tt = 180/degree radian = math.pi/tt return radian def sin(degree,count): degree = net_degree(degree) radian = degree_to_radian(degree) alpha = 1 test = 1 result = 0 ...
'''Negative base''' class NegativeBase(): '''Super class for negative bases base <= -2''' str_digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __init__(self, base, n): if not base < -1: raise ValueError('Base should be "base <= -2"') self.base = base self.num =...
'''Prime Checker''' def is_prime(n): '''check if interger n is a prime''' n = abs(int(n)) if n < 2: return False elif n == 2: return True elif not n & 1: return False else: for x in range(3, int(n ** .5) + 1, 2): if n % x == 0: ...
from graphics import * from random import randint def textbox(center, text, width, height, win): p1 = Point(center.getX() - width/2, center.getY() - height/2) p2 = Point(center.getX() + width/2, center.getY() + height/2) box = Rectangle(p1, p2) box.draw(win) text = Text(center,...
import re ''' creating a regex object. ''' phoneNumRegex = re.compile(r"\d{3}-\d{3}-\d{4}") ''' searching the string for any regex object match ''' mo = phoneNumRegex.search('My number is 415-555-4242 , 415-555-4244, 415-555-4222.') ''' returning the actual matched regex. ''' print("The phone no. is"...
''' Checking weather a chess board is valid or not. Created: May 30, 2021 Creator: Nishkant ''' goats = ["pawn", "rook", "bishop", "king", "queen", "knight"] piece_names = ["bpawn", "brook", "bbishop", "bking", "bqueen", "bknight" , "wpawn", "wrook", "wbishop", "wking", "wqueen"...
''' How often does a streak of 6 heads/tails occur in flipping a coin 100 times ??? Code to calculate the number of streaks in an experiment of flipping a coin 100 times and repeating it 10000 times to calculate a decent average of percentage of streaks. Created: 27 may, 2021 Some commen...
from collections import Collection from typing import Union, Tuple def to_tuple(x, length=2): if isinstance(x, Collection): assert len(x) == length return tuple(x) else: return (x,) * length IntOrTuple = Union['IntOrTuple', int, Tuple[int, int]]
def average_numbers(num_list): avg = sum(num_list)/float(len(num_list)) return avg my_avg = average_numbers([1, 2, 3, 4, 5, 6]) print(my_avg) list = [1, 2] matrix = [[1, 2, 3, 4], [5, 6, 7, 8]] print(matrix)
C=input("Enter the temperature in Celsius:") F=9/5*float(C)+32 print (str("F="),F)
""" Created on Thu May 31 22:28:29 2018 @author: perso """ def print_max(a,b): if a>b: print(a, 'is maximum') elif a==b: print(a, 'is equal to', b) else: print(b, 'is maximum') print_max(3,4) x=5 y=7 print_max(x,y)
try: import Tkinter as tk except ImportError: import tkinter as tk class DragDropListbox(tk.Listbox): """ A Tkinter listbox with drag'n'drop reordering of entries. """ def __init__(self, master, brain, li, **kw): self.brain = brain self.made_change = False kw['selectmode'] = ...
from typing import List, Set question_groups: List[List[str]] = [] group_numbers: List[int] = [] with open("data/6") as f: temp: List[str] = [] num_in_group: int = 0 for l in f: if l != "\n": for x in l[:-1]: temp.append(x) num_in_group += 1 else: ...
''' A list rotation consists of taking the first element and moving it to the end. For instance, if we rotate the list [1,2,3,4,5], we get [2,3,4,5,1]. If we rotate it again, we get [3,4,5,1,2]. Write a Python function rotatelist(l,k) that takes a list l and a positive integer k and returns the list l after k rotatio...
import random from time import sleep class ActionAffirmitiveNegative(): def __init__(self): self.action = "action_affirmative_negative" def makeAffirmativeNegative(self, intent): positive_response = ["I'm Impressed", "Thanks you find it useful", "Glad to hear that", "Great it did help"] negative_response = ["...
x = 2 n = 4 multiply=x*n print(x<<n)
import os def readlines(filename): """Return contents of text file as a list of lines.""" with open(filename) as file: return file.readlines() def index_and_count_lines(dirname, root_path_length): filenames = os.listdir(dirname) for filename in filenames: path = dirname + "\\" + file...
def output(parameter1, parameter2): parameter1_str = str(parameter1) parameter2_str = str(parameter2) print(parameter1_str + parameter2_str) number1_str = input(" First number: ") number1 = int(number1_str) number2_str = input("Second number: ") number2 = int(number2_str) operation = input("Operation [+...
print("Justified decimals") print("|" + format(123.456789, "8.2f") + "|") print("|" + format(123, "8.2f") + "|") print("|" + format(123.456789, "<8.2f") + "|") print("|" + format(123, "<8.2f") + "|") print() print("Justified integers") print("|" + format(123, "8") + "|") print("|" + format(123, "<8") + "|") print() pri...
from turtle import * i=0 def line_and_angle(x,y) : forward(x) left(y) while i<3: line_and_angle(100,120) i=i+1
response = input("Are you generally happy with COMP1753? ") if response.strip().lower().startswith("yes"): print("Good! Your response is '" + response + "'") response = response.strip() response = response.lower() if response.startswith("yes"): print("Good! Your response is '" + response + "'") print() inp...
from random import randint def print_list(items, header=None): if header != None: print(header) for item in items: print(str(item)) print() def get_min_v1(items): items.sort() return items[0] def get_min_v2(items): smallest = items[0] for item in items[1:]: if i...
from tkinter import * window = Tk() window.geometry("350x200") window.title("COMP1753 GUI") input_txt = Entry(window, width=10) input_txt.focus() input_txt.grid(column=0, row=0) def clicked(): res = "Hello " + input_txt.get() output.set(res) btn = Button(window, text="Click Me", command=clicked) btn.grid...
def input_and_convert(prompt, conversion_fn): """ this function prompts the user for some input then it converts the input to whatever data-type the programmer has requested and returns the value """ string = input(prompt) number = conversion_fn(string) return number def output(par...
name = input("What is your name? ") course = "COMP1753" print("Hello " + name + " - welcome to " + course) print() input("Press return to continue ...")
import urllib.request url = input("Enter an URL for a file: ").strip() infile = urllib.request.urlopen(url) content = infile.read().decode() print(content) print() input("Press return to continue ...")
from random import randint name = input("what is your name ?: ") year = input("what is your year of birth?: ") minimum = int(year) maximum = int(year)+70 lucky = randint(minimum, maximum) lucky = str(lucky) print() print("hello " + name + " your lucky number is " + lucky) input("press enter to end")
n_lines = int(input("How many lines? ")) for counter in range(1, n_lines+1): if counter == 3: break print("This is line " + str(counter)) print() input("Press return to continue ...")
from Crypto.PublicKey import RSA from decimal import Decimal, getcontext def extended_euclidean(a, b): if a == 0: return (b, 0, 1) else: g, y, x = extended_euclidean(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = extended_euclidean(a, m) return x %...
from random import sample, randint def select_balls(): red_balls = [x for x in range(1, 34)] sele_balls = [] sele_balls = sample(red_balls, 6) sele_balls.sort() sele_balls.append(randint(1, 16)) return sele_balls def display(balls): for index, ball in enumerate(balls): if...
from abc import abstractmethod, ABCMeta class Employee(object, metaclass=ABCMeta): def __init__(self, name): self.__name = name @property def name(self): return self.__name @abstractmethod def getSalary(self): pass class Manager(Employee): def getSalary(se...
for i in range(4): print (i) for i in range(3,-1,-1): print (i) for i in range(8,0,-2): print(i)
from getpass import getpass def main(): print('Welcome to Word Up') secret_word = getpass('Enter the secret word') current_list = ["_"] * len(secret_word) letter_bank = [] guess = "" while "_" in current_list: print_board(current_list) get_letter(guess, letter_bank) ...
def cigar_party(cigars, is_weekend): if is_weekend and cigars >= 40: return True else: return 40 <= cigars <= 60 if 40 <= int(cigars) <= 60: return True else: return False print(cigar_party(30, True))
def is_abecedarian(word): n = 0 a = word[n] b = word[n+1] while n < len(word): if a > b: ...
import random def bubble_sort(nums): for i in range(len(nums)-1): for j in range(len(nums)-i-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] print(nums) return random.choice([nums, None, 10]) if __name__ == '__main__': print(bubble_sort([3, ...
numcomp = int(input()) maxsum = 0 maxsumname = "" secondsum = 0 secondsumname = "" testarr = [] for _ in range(0,numcomp,1): string = str(input()) name,ram,cpu,disk = string.split(" ") ram = int(ram) cpu = int(cpu) disk = int(disk) sum = ram*2+cpu*3+disk if sum > maxsum: testarr = ...
print('\n******Start Line******\n') i =5 print(i) i = i + 1 print(i) s = '''This is a multi-line string. This is the second line.''' print(s) a = 'hello'; print(a) b = \ 5 print(b) print('\n*******End Line*******\n')
T= 0 while T<=100: print("Print", T, "Times table.") A=0 while A<=10: print(T, "x", A, "=", (A*T)) A+=1 T+=1 print("__________________")
FileRead=open("data.txt", "r") FileWrite= open("data2.txt", "w") for line in FileRead: for letter in line: if letter=="e" or letter=="E": print("*", end="", file=FileWrite) else: print(letter, end="", file=FileWrite)
bill= int(input("what is the bill? ")) paid= int(input("what was paid? ")) change= paid-bill if change>=50: print(int(change/50), '50 pound notes') change= change%50 if change>=20: print(int(change/20), '20 pound notes') change= change%20 if change>=10: print(int(change/10), '10 pound notes') change= change%10 if...
s = raw_input("Enter a word: ") str = "" for i in s: str = i + str print (str)
print(' sqq is a good boy') timeStr = input() timeList = timeStr.split(':') hour = int(timeList[0]) min = int(timeList[1]) sec = int(timeList[2]) sec += 1 if sec == 60: min +=1 sec = 0 if min ==60: hour +=1 min = 0 if hour ==24: hour = 0 print('%d: %d:%d' % (hour, min, ...
import math import random random.random() number = math.ceil( random.random()*20 ) def gucessfun(num): global number print(num) print(number) if num > number: print('大了大了,再小点') if num < number: print('小了小了,再大点') count = 0 nums = 0 print(number) while count < 5: nums =...
def s_S(list): for i in list: if i[0]=="S" or i[0]=="s": print(i) s_S(["sana","ali","Sara"])
import sys def addConstraints(file): constraints = [] with open(file, 'rb') as f: inConstraint = False constraint = None for line in f: if not inConstraint: if "PRINTING" in str(line.strip()): inConstraint = True constr...
import numpy as np def rule_1(row): """Cell i becomes (or stays) black if one or more of the triad [i-1, i, i+1] is black; otherwise it stays (or becomes) white""" new_row = np.zeros(row.shape[0]) for i, cel in enumerate(row): if(row[i-1] + row[i] + row[(i+1) % len(row)] >= 1): new_row[i] = 1 else: ...