text
stringlengths
37
1.41M
""" diaper pattern example (This is how you should NOT build your try.. except clauses) """ def fibonacci(n): """Returns the n-th number from the Fibonacci series.""" try: a = 0 b = 1 while n > 0: temp = a+b a = b b = temp n -= 1 ...
import math input = open("input.txt", "r") input = input.read() inputList = input.split('\n') count = 0 def findFuel(input): num = math.floor(input / 3) - 2 if(num > 6): num = num + findFuel(num) return num for i in range(len(inputList)): inputList[i] = int(inputList[i]) count = count...
import matplotlib.pyplot as plt def plot_result(x,y,ordering,iteration_history, energy_history,kT_history): """ Plots the results of simulated annealing from metropolis_function """ plt.subplot(1, 2, 1) plt.plot(x[ordering], y[ordering], 'k') #plot([x[ordering[-1]], x[ordering[0]]], [y[orde...
""" Модуль pickle: Преимущества: 1. Реализует эффективную сереализацию и десериализацю объектов Python в поток байтов. Недостатки: 1. Плохо защищен. Необходимо быть уверенным в том, какие данные распаковываются. 2. Формат, в котором записываются объекты, не читаем для человека. """ import pic...
def merge(iter1, iter2): try: buf1 = next(iter1) except StopIteration: yield from iter2 return try: buf2 = next(iter2) except StopIteration: yield buf1 yield from iter1 return while True: if buf1 < buf2: yield buf1 ...
from copy import deepcopy class Polynomial(object): def __init__(self, *coeff): if len(coeff) == 1: coeff = coeff[0] if type(coeff) == int or type(coeff) == float: self.coeff = [coeff] elif type(coeff) == str: self.coeff = list(map(Polynomial.num, coeff....
#! /usr/bin/env python3 # # Reference: Python Crash Crouse, 2nd Edition # Author: Samuel A WINFUL """Ask the user for their name and write it to guest.txt""" filename = 'guest.txt' mode = 'w' with open(filename, mode) as file_object: response = input("What is your name? ") file_object.write(response)
# Reference: Python Crash Crouse, 2nd Edition # Author: Samuel A WINFUL class Restaurant: """Basic restaurant class.""" def __init__(self, restaurant_name, cuisine_type): self.name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def increment_number_serve...
""" Check if Palindrome - Checks if the string entered by the user is a palindrome. That is that it reads the same forwards as backwards like "racecar" """ string = raw_input('Enter a string: ').lower() if string == string[::-1]: print '%s is a palindrome' % string else: print '%s is not a palindro...
""" Pig Latin - Pig Latin is a game of alterations played on the English language game. To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules. """ ...
import time, sys indent=0 #how many spaces to indent indentincreasing= True #whether the indentation is increasing or not try: while True: print(' '*indent,end='') print('*******') time.sleep(0.2) if indentincreasing: #increasing the number of spaces....
# for i in range(1,20): # if i==4 or i==13: # print(f"{i} is UNLUCKY!!") # elif i%2!=0: # print(f"{i} is odd") # else: # print(f"{i} is even") # for i in range(1,11): # print("\U0001f600"*i) # i=1 # while i<11: # print("\U0001f600"*i) # i+=1 ...
#!/usr/bin/python idade = input("Digite a sua idade ") if (idade >= 18): print("Pode dirigir") else: print("Nao pode dirigir")
# 剑指 Offer 55 - I. 二叉树的深度 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 def dfs(root,deep): if not r...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :59_I.py @IDE :PyCharm @Author :无名 @Date :2021/5/4 23:09 ''' from typing import List class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: n = len(nums) left,right = 0,0 ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode878.py @IDE :PyCharm @Author :无名 @Date :2021/5/2 22:59 ''' # 878. 第 N 个神奇数字 类似 1201 from typing import List from math import gcd class Solution: def nthMagicalNumber(self, n: int, a: int, b: int) -> int: ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :336.py @IDE :PyCharm @Author :无名 @Date :2021/4/26 17:02 ''' from typing import List class Solution: def squre_test(self,nums=8): if not nums: return -1 for i in range(1,nums): if i**2 == nums: return i ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :66.py @IDE :PyCharm @Author :无名 @Date :2021/4/29 16:28 ''' # 剑指 Offer 66. 构建乘积数组 from typing import List class Solution: # 超出时间限制,卡在最后一个测试用例上了 def constructArr(self, a: List[int]) -> List[int]: if not a :...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode503.py @IDE :PyCharm @Author :无名 @Date :2021/5/3 13:26 ''' # 503. 下一个更大元素 II from typing import List class Solution: # def nextGreaterElements(self, nums: List[int]) -> List[int]: # if not nums: retur...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode137.py @IDE :PyCharm @Author :无名 @Date :2021/4/30 22:05 ''' from typing import List import collections # class Solution: # def singleNumber(self, nums: List[int]) -> int: # nums_count = collections.Co...
# 剑指 Offer 40. 最小的k个数 # 输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。 from typing import List class Solution: def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: arr.sort() return arr[:k]
# 39. 组合总和 # 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 # candidates 中的数字可以无限制重复被选取。 from typing import List class Solution: # def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: # ans = set() # def dfs(now,nowlist): # if now=...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :39.py @IDE :PyCharm @Author :无名 @Date :2021/4/30 17:17 ''' from typing import List class Solution: def majorityElement(self, nums: List[int]) -> int: n = len(nums) nums.sort() return nums[:n//...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode563.py @IDE :PyCharm @Author :无名 @Date :2021/4/24 0:01 ''' # 563. 二叉树的坡度 # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): ...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode1365.py @IDE :PyCharm @Author :无名 @Date :2021/5/3 23:52 ''' from typing import List import collections class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: nn = sorted(nu...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode1201.py @IDE :PyCharm @Author :无名 @Date :2021/5/1 20:52 ''' # 1201. 丑数 III from typing import List from math import gcd # // 求最大公因数 # long gcd(long x, long y){ # return !y ? x: gcd(y, x % y); # } # # // 就最小公倍数 #...
#!/usr/bin/env python # -*- coding: UTF-8 -*- ''' @Project :algorithm_homework @File :leetcode554.py @IDE :PyCharm @Author :无名 @Date :2021/5/2 16:48 ''' from typing import List from collections import defaultdict class Solution: def leastBricks(self, wall: List[List[int]]) -> int: prefixSum = ...
s = input("請輸入您心裡所想的數字") n = input("請輸入參與遊戲的人數") s = int(s) n = int(n) x = [] for i in range(n): line = input() name = line[:2] num = [3:2] x.append([name,num])
#!/usr/bin/python3 import socket from termcolor import colored host = str(input(colored("[*] Enter the IP Address: ", 'blue'))) r = int(input(colored("[*] Number of Ports to Scan: ", 'blue'))) # Remove the comment to scan a specific port # p = int(input("[*] Enter the Port to Scan: ")) def port_scanner...
from . import functional as F __all__ = ["Levenshtein", "SegmentErrorRate"] class Levenshtein: """levenshtein distance returns number of deletions, insertions, or substitutions required to convert source string into target string. Parameters ---------- source, target : str Returns -...
"""functions for making spectrogram filters adapted from SciPy cookbook https://scipy-cookbook.readthedocs.io/items/ButterworthBandpass.html spectrogram adapted from code by Kyle Kastner and Tim Sainburg https://github.com/timsainb/python_spectrograms_and_inversion """ import numpy as np from scipy.signal import butt...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): res = ListNode(0) head = res carry = 0 p = l1 q = l2 while (p != None or q != None): x = p.val if (p != None) else 0 ...
import time from numba import jit import numpy as np @jit(nopython=True) def sum2dimensional(np_array): array_rows, array_columns = np_array.shape result = 0.0 for i in range(array_rows): for j in range(array_columns): result += np_array[i,j] return result def main(): np_array = ...
import sys class Solution: def isRobotBounded(self, instructions: str) -> bool: # Position is a tuple (X, Y) and directions are: # 0 - North # 1 - East # 2 - South # 3 - West position, direction = (0, 0), 0 # Execute all steps and compute final position ...
import sys # Function for nth Fibonacci number def fibonacci(n): # Check if input is 0 then it will return null if n < 0: return None # Check if n is 0 then it will return 0 elif n == 0: return 0 # Check if n is 1 or 2 it will return 1 elif n == 1 or n == 2: return 1...
# -*- coding:utf-8 -*- class Solution: def reOrderArray(self, array): # write code here n = len(array) num1 = [] num2 = [] for i in range(0, n): if array[i] % 2 == 0: num2.append(array[i]) else: num1.append(array[i]) ...
#coding=utf-8 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): root = TreeNode(pre[0]) mid = tin.index(pre[0]) tin_left = tin[0:mid] ti...
import round # instance of game class, containing objects like score, lives, etc.... class Game: def __init__(self, font): """ new game instance """ self.paused = False self.playing = True self.round = round.Round() self.timer = 260 self.font = ...
import sys sys.path.insert(0,'..') from advent_lib import * # Node class to represent values from input data class Node(): def __init__(self, v): self.next = None self.v = v def __str__(self): return f"v: {self.v}" def __repr__(self): return self.__str__() # Gets the correc...
word = 'brontosaurus' d = dict() for c in word: if c not in d: d[c] = 1 else: d[c] = d[c] + 1 print(d) # get method automatically handles the case where a key is not in a dictionary word = 'brontosaurus' d = dict() for c in word: d[c] = d.get(c,0) + 1 print(d)
def findIntersection(StrArr): output = [] # StrArr = sorted(StrArr) lisA = StrArr[0] lisB = StrArr[1] lisA = lisA.split(", ") lisB = lisB.split(", ") for i in range(0, len(lisA)): a = lisA[i] for c in range(0, len(lisA)): b = lisB[c] if a ...
#program a = int(input("Enter the Number!")) b = int(input(" enter the number")) if(a > b): print("a is greater number") if(b > a): print("b is greater than a") if(a == b): print("They are equal")
input = open("../sample_data/networkroute.dat", "r") lines = input.readlines() computers = [] names = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4} source = 0 dest = 0 for line in lines: parts = line.split() if line.startswith('MESSAGE'): source = names[parts[0][-1]] dest = names[parts[1].strip()] ...
#!/usr/bin/env python3 import sys import numpy as np def select(S, k): N = len(S) if len(S) == 1: return S[0] L, V, R = [], [], [] v = S[np.random.randint(N)] for i in range(N): if S[i] < v: L.append(S[i]) elif S[i] > v: R.append(S[i]) els...
# create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI', 'Massachusetts': 'MA', 'Nevada': 'NV' } # create a basic set of states and some cities in them cities = { 'CA': 'San Francisco', 'MI': ...
# All Three Combined """ Inheritance or Composition: 1. Avoid multiple inheritance at all costs, as it’s too complex to be reliable. If you’re stuck with it, then be prepared to know the class hierarchy and spend time finding where everything is coming from. 2. Use composition to package code into modules that are us...
# Modules, Classes, and Objects ''' mystuff = {'apple': "I AM APPLES!"} print(mystuff['apple']) # this goes in mystuff.py def apple(): print("I AM APPLES!") # this is just a variable tangerine = "Living reflection of a dream" import mystuff mystuff.apple() print(mystuff.tangerine) mystuff['apple'] # get apple ...
# this line defines my function to take two parameters. def cheese_and_crackers(cheese_count, boxes_of_crackers): # This print statement prints the parameters passed in by the function calls. print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man ...
import numpy as np a = np.array([ [5, 1, 3], [1, 1, 1], [1, 2, 1] ]) b = np.array([1,2,3]) # print (a @ b) # print (a * b) # print (np.dot(a,b)) p =(4, 'frog', 9, -3.1) print(9 in p) print('dog' not in p) s = input("enter an integer:") try: i = int(s) print("valid integer extered:", i) except ValueError ...
import matplotlib.pyplot as plt import numpy as np # https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule def n_bins(column): q25, q75 = np.percentile(column, [.25, .75]) bin_width = 2 * (q75 - q25) * len(column) ** (-1 / 3) bins = round((column.max() - column.min()) / bin_width) return bins ...
i = -2 if i > 0: print 'positive i' i = i + 1 elif i == 0: print 'i is 0' i = i * 10 else: print 'negative i' i = i - 1 print 'new i:', i i = 5 if i > 1: print 'i bigger than 1' print 'good' if i > 2: print 'i bigger than 2' print 'even better'
import speech_recognition as sr import pyttsx3 #initializing the recognizer r = sr.Recognizer() def SpeakText(command): #initialize the engine engine = pyttsx3.init() engine.say(command) engine.runAndWait() # Loop while(1): try: #use the microphone for input with...
from math import sqrt, floor def is_prime(num): # numbers smaller than 2 cannot be primes if num <= 2: return False # even numbers cannot be primes if num%2==0: return False # we have already checked numbers < 3 # finding primes up to N we just have to check numbers up to sqrt(N) ...
import math import pandas as pd import numpy as np class ValidateData(object): """Data Validation methods takes in a Pandas Table and does the following: -> checks for row and column duplicates -> % ratio of null in a dataframe -> data types in a Series -> info report on dataframe/Series -...
import pandas as pd import matplotlib.pyplot as plt import numpy as np def read_csvdataset(): #Read_CSV with column_names crime_data=pd.read_csv(r"D:\PPD_Crime_Incidents_2012-2014.csv",names=['District','PSA','Dispatch_Date','DC_number','Location','UCR_Code','Crime_Category','Co_ordinates']) #Creati...
# sets unordered mutable no duplicates. myset={"hello"} print(myset) myset=set("hello") print(myset) setnum =set()#empty set must rpresent like this. setnum.add(1) setnum.add(2) setnum.add(3) #we we use remove function then there would be an error coz 4 element was not in the set. setnum.discard(4)...
# Simple plots with legend import numpy as np import matplotlib.pyplot as plt # Compute the x and y coordinates for points on sine and cosine curves x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # Plot the points using matplotlib plt.plot(x, y_sin) plt.plot(x, y_cos) plt.xlabel('x axis label')...
import sys def print_chess_board(board): for x in board[::-1]: for y in x: sys.stdout.write(y) sys.stdout.write("\n") def calculate_next_move(distance_to_end): # One move to finish! if(distance_to_end[0] == 2 and distance_to_end[1] == 1): return (2, 1) elif(distance_to_end[0] == 1 and dis...
# Escribir un programa que almacene las asignaturas de un curso (por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista, # pregunte al usuario la nota que ha sacado en cada asignatura, # y después las muestre por pantalla con el mensaje En <asignatura> has sacado <nota> donde <asignatura> es cada una...
# Escribir un programa que muestre el eco de # todo lo que el usuario introduzca hasta que el usuario escriba “salir” que terminará. v_palabra = str('frase') while v_palabra != '': v_palabra = str(input("Ingrese palabra: ")) print(v_palabra) if v_palabra == 'salir': print("eso es todo") br...
"""Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un curso {'Matemáticas': 6, 'Física': 4, 'Química': 5} y después muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene <créditos> créditos, donde <asignatura> es cada una de las asignaturas del cur...
# Escribir un programa que cree un diccionario de traducción español-inglés. # El usuario introducirá las palabras en español e inglés separadas por dos puntos, # y cada par <palabra>:<traducción> separados por comas. # El programa debe crear un diccionario con las palabras y sus traducciones. # Después pedirá una fras...
# Haz que un usuario introduzca dos números enteros positivos. Comprueba si el primer número introducido # por el usuario es mayor o igual que el segundo número introducido por el usuario. Devuelve por pantalla el # resultado en cada caso. v_x = int(input('Ingrese el valor de X: ')) v_y = int(input('Ingrese el valor d...
"""Escribir una función reciba un diccionario con las asignaturas y las notas de un alumno y devuelva otro diccionario con las asignaturas en mayúsculas y las calificaciones correspondientes a las notas aprobadas.""" # Sol 1 """" def califica(n): if n < 5: return 'SS' elif n < 7: return 'AP'...
v_cant_invertir = float(input("Ingrese cantidad a invertir : ")) v_interes = float(input("Ingrese interes anual : ")) v_anos = int(input("Ingrese el numero de años : ")) print("Capital obtenido es: " + str(round(v_cant_invertir * (v_interes / 100 + 1) ** v_anos, 1)))
# Escribir un programa que pregunte al usuario su edad y muestre por pantalla todos los años que ha cumplido (desde 1 hasta su edad). v_in_edad = int(input("Ingrese su edad: ")) for i in range(v_in_edad): print("Usted cumplio: " + str(i + 1))
"""Escribir una función que pida un número entero entre 1 y 10, lea el fichero tabla-n.txt con la tabla de multiplicar de ese número, donde n es el número introducido, y la muestre por pantalla. Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello""" # Sol 1 """n = int(input('Ingrese un núm...
# Escriba un programa que pida la cantidad de números positivos que se tienen que escribir y a continuación pida números # hasta que se haya escrito la cantidad de números positivos indicada. ######################################################################################################################## print(...
# Con la función input(), indícale al usuario que introduzca la ciudad en la que vive y guárdala en la variable # llamada ciudad. v_ciudad = input('Introduzca la ciudad donde vive: ') print(v_ciudad)
# Haz que un usuario introduzca una palabra y comprueba si dicha palabra empieza por mayúscula. Devuelve # por pantalla el resultado en cada caso. v_palabra = str(input('Ingrese palabra: ')) print('la primera letra empieza con mayúscula') if v_palabra[0] == v_palabra[0].upper() else print('la primera letra NO empieza...
"""Escribir una función que reciba una muestra de números y devuelva los valores atípicos, es decir, los valores cuya puntuación típica sea mayor que 3 o menor que -3. Nota: La puntuación típica de un valor se obtiene restando la media y dividiendo por la desviación típica de la muestra.""" from statistics import mean...
"""Escribir una función reciba un diccionario con las asignaturas y las notas de un alumno y devuelva otro diccionario con las asignaturas en mayúsculas y las calificaciones correspondientes a las notas.""" # Sol 1 '''def califica(n): if n < 5: return 'SS' elif n < 7: return 'AP' elif n <...
'''Escribir una función que reciba un DataFrame con el formato del ejercicio anterior, una lista de meses, y devuelva el balance (ventas - gastos) total en los meses indicados.''' import pandas as pd def df_datos(diccionario): df = pd.DataFrame(diccionario) bal = df.Ventas - df.Gastos df['Balance'] = pd....
'''Escribir un programa para gestionar un listín telefónico con los nombres y los teléfonos de los clientes de una empresa. El programa incorporar funciones crear el fichero con el listín si no existe, para consultar el teléfono de un cliente, añadir el teléfono de un nuevo cliente y eliminar el teléfono de un cliente....
v_num = int(input("ingrese numero: ")) while v_num < 10 and v_num > 0: v_num -= 1 # v_num = v_num - 1 print("bucle: " + str(v_num)) print(v_num)
# Con la función input(), indícale al usuario que introduzca su nombre y guárdalo en la variable llamada # nombre v_nombre = input('introduzca su nombre: ') print(v_nombre)
# Escribir un programa que pida al usuario un número entero y muestre por pantalla un triángulo rectángulo como el de más abajo, # de altura el número introducido. v_num = int(input("Ingrese numero entero para la altura: ")) for i in range(v_num): for j in range(i + 1): print("*", end= " ") print("s"...
import os num=input("enter a number \n") fact=1 for i in range (1,num+1): fact=fact*i print "factorial is ", fact
# This library is used in Assignment3_Part3_CharRNN import tensorflow as tf from tensorflow.contrib import rnn import numpy as np # RNN model class definition # the class contains all the TF ops that define the recurrent neural networks computation class Model(): def __init__(self, args, training=True): # ...
todos = ['fuck ur mom', 'run around town', 'makin my way downtown', 'he got a map wha'] print(todos) first_item = todos[0] second_item = todos[1] # print("The first item is:", todos[1]) # What happens if I specify an invalid index? # Python considers it an error if you use an index that falls outside the range of a...
empty = 'empty' def is_link(s): return s == empty or (len(s) == 2 and is_link(s[1])) def link(first, rest): assert is_link(rest) return [first, rest] def first(s): assert is_link(s), "first only applies to linked lists." assert s != empty, "empty linked list has no first element"...
import string import sys def load_words(file_name): ''' file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may ta...
# Copyright: (c) David Enterprises Inc. # ArcGIS Version: 10.3 # Python Version: 2.7 # # Course: GEOS 455 - Assignment 3: Advanced Python # # Purpose: This script takes input features that may be impacted by impacting features (input), # and outputs a feature class including the input features th...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # apply the list to sort # def mergeTwoLists(self, l1, l2): # """ # :type l1: ListNode # :type l2: ListNode # :rtype: ListNode # ...
"""String parse wrapper functions to streamline common use cases""" import re from check import is_list, is_str, is_bool, is_str_not_empty, is_int_pos def str_split_size(s, n=None): """Split a string by length Args: s (str): The string to be divided. Value type is converted to string. n (int...
import random def bubbleSort(arr): if arr is None: return if len(arr) == 0: return if len(arr) == 1: return for (i,j) in [(i,j) for i in range(0,len(arr)) for j in range(i+1,len(arr))] : # print i,j,arr[i],arr[j] if (arr[i] > arr[j]): # print 'swap',i,j temp = arr[i] arr[i] = arr[j] arr[j] = t...
a = 1 while a < 101: if a // 10 == 7 or a % 7==0: a = a+1 continue else: print(a) a = a+ 1
#It has at least 6 characters and at most 20 characters. #It must contain at least one lowercase letter, at least one uppercase letter, and at least one # digit. #It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." # is strong, assuming other conditions are met pas="" ...
import random colorsToNumber = {'red': 0, 'blue': 1, 'green': 2, 'yellow': 3} total_numbers = 10 total_colors = 4 class Card: def __init__(self, number, color): self.number = number self.color = color def __str__(self): return f"[Number:{self.number}, Color: {self....
''' Major Scales Jan 17 2018 https://www.reddit.com/r/dailyprogrammer/comments/7hhyin/20171204_challenge_343_easy_major_scales/ Example Input: Enter a scale: C Enter a note: Do > C, Do -> C Scales: C, C#, D, D#, E, F, F#, G, G#, A, A#, B Notes: Do, Re, Mi, Fa, So, La, Ti ''' solfege = {"Do":0, "Re":...
''' 1000-digit Fibonacci number Problem 25 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? ''' if __name__ == "__main__": a = 1 b = 0 i = 1 t = ...
#{ #Driver Code Starts #Initial Template for Python 3 # } Driver Code Ends #User function Template for python3 # Function to sort using comparator def customSort(arr): # Your code here # Hint : Should be a return statement return arr[1], arr[0] #{ #Driver Code Starts. # Driver Code def main(...
def deleteFromArray(arr,n,idx): for i in range(idx,n-1): arr[i] = arr[i+1] arr[n-1] = 0 return #{ # Driver Code Starts #Initial Template for Python 3 #CONTRIBUTED BY RavinderSinghPB if __name__ == '__main__': tcs= int(input()) for _ in range(tcs): n=int(input()) idx=...
#{ #Driver Code Starts #Initial Template for Python 3 # } Driver Code Ends #User function Template for python3 # Function to count even and odd # c_e : variable to store even count # c_o : variable to store odd count def count_even_odd(N, arr): c_e = 0 c_o = 0 pair = list() for x in arr: ...
# -*- coding: utf-8 -*- """ Created on Wed Sep 2 15:30:37 2020 @author: velve """ from pygame import display, draw, Rect class Screen(object): def __init__(self, scale, c8): self.c8 = c8 self.height = 32 self.width = 64 self.scale = scale self.sur...
###Testing### ###Get recipes### ###Test the get_recipe function: Returning all 20 recipes in the collection. The expectation is that the expected 20 will match the actual 20.### ###This test has been failed for the purpose of testing.### def get_recipe(recipes): return 20 def test_are_equal(actual, expected)...
import numpy as np def trapz(func, a, b, N): """Input your function, lower limit, upper limit, and the number of trapezoids you wish. The function will return the integreal using the trapezoidal rule.""" h = (b-a)/N k = np.arange(1, N) I = h*(0.5*func(a) + 0.5*func(b) + func(a+k*h).sum()) retu...
''' Random choice is a kind of brute force method which generates a random sequence of job and then calculate the cost. ''' from geneticAlgorithm011 import get_energy_cost, get_failure_cost, read_price, read_job, select_jobs, read_maintenance from datetime import datetime import numpy as np import csv if __na...
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 21:23:43 2020 @author: edris """ # Short Circuiting - can be done using 'or' in if statements isFriend = True isUser = True if isFriend or isUser: print('Best friends forever')
# -*- coding: utf-8 -*- """ Created on Wed Aug 26 23:12:05 2020 @author: edris """ someList = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] duplicates = [] for item in someList: if someList.count(item) > 1: if item not in duplicates: duplicates.append(item) print(duplicates)