text
stringlengths
37
1.41M
def baseConverter(decNumber,base): digits = "0123456789ABCDEF" newString = "" while decNumber > 0: rem = decNumber % base decNumber = decNumber // base newString = digits[rem] + newString return newString print("Decimal to binary:", baseConverter(1001,2)) print("Decimal to hexadecimal:", baseConverter(100...
# Python3 program to find maximum difference # between node and its ancestor _MIN = -2147483648 _MAX = 2147483648 # Helper function that allocates a new # node with the given data and None left # and right poers. class newNode: # Constructor to create a new node def __init__(self, key): self.key ...
def partition(lst, start, end): pos = start # condition was obsolete, loop won't # simply run for empty range for i in range(start, end): # i must be between start and end-1 if lst[i] < lst[end]: # in ...
# Binary Tree Traversal: O(n) complexity class Node: def __init__(self ,key): self.data = key self.left = None self.right = None # Iterative Method to print the height of binary tree def printLevelOrder(root): # Base Case if root is None: return # Create an empty queue for level order traversal us...
#!/usr/bin/env python3 from inspect import signature def curry(fn): num_args = len(signature(fn).parameters) def init(*args, **kwargs): def call(*more_args, **more_kwargs): all_args = args + more_args all_kwargs = dict(**kwargs, **more_kwargs) if len(all_args) + len(...
#!/usr/bin/env python3 # Exercise # Using a generator expression, define a generator for the series: # (0, 2).. (1, 3).. (2, 4).. (4, 6).. (5, 7) # This is a "generator expression" g = ((a, b) for a, b in zip(range(0, 6), range(2, 8)) if a != 3) for i in g: print(i) # This is a "list comprehension"" g = [(a, b)...
#!/usr/bin/env python3 class Foo: def __init__(self, x=0, name=None): self.x = x self.name = name def __repr__(self): return '{} -> x = {}'.format(self.name, self.x) # AFAICT, the type annotations have no bearing at runtime. They # are only relevant to the static type checker, so returning # a float from a...
#!/usr/bin/env python2.7 from collections import namedtuple Thing = namedtuple('Thingy', ['one', 'two']) a = Thing('foo','bar') c, b = a print "a=", a # a is a Thingy print "b=", b # b is 'bar' print "c=", c # c is 'foo' print "a.one = ", a.one print "a.two = ", a.two # Note that the naming of the fields can a...
#!/usr/bin/env python3 import itertools a = (1, 2, 3, 4) b = ("a", "b", "c") # Stop when b is exhausted (similar to python2's itertools.izip) for i in zip(a, b): print(i) # Fill in short lists with NULL (in python3, this is izip_longest) for i in itertools.zip_longest(a, b): print(i) for i, (a, b) in enume...
#!/usr/bin/env python3 """ https://docs.python.org/3/glossary.html#term-sequence An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and...
#!/usr/bin/env python from operator import itemgetter # Sort tuple by 2nd index student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] # sort by .[2] a = sorted(student_tuples, key=lambda student: student[2]) print('sorted by age:') for x in a: print(x) # sort by .[1], then by .[2]...
""" THIS IS MEANT TO BE THE REVERSE OF bomb_baby.py's SOLUTION instead of starting from 1,1 and searching downwards, start from tm, tf and work backwards towards 1,1 If 1,1 is reachable, return the shortest number of moves to get there If 1,1 is NOT reachable, return "impossible" TUTORIALS USED: https://www.youtube.co...
import numpy as np x = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]) print(x.shape) y = np.expand_dims(x, axis=2) print(y.shape) print(y) z = np.concatenate([y] * 3, 2) print(z)
from datetime import * def date_converter(date_string): dates = date_string.split("-") date_item = [int(item) for item in dates] try: new_date = date(date_item[0],date_item[1],date_item[2]) return new_date except ValueError: return date(9030,12,30) def period_start_dates(last...
#!/usr/bin/env python3 def prime(n): i = 2; if n <= 1: return False while i * i <= n: if n % i == 0: return False i = i + 1 return True def main(): sum = 2 for i in range(3, 2000001, 2): if prime(i): # print(i) sum += i # ...
#!/usr/bin/env python3 # # $ python3 14.py |sort -k2 -nr|head # 837799 524 # 626331 508 # 939497 506 # 704623 503 # 927003 475 # 910107 475 # 511935 469 # 796095 467 # 767903 467 # 970599 457 # def count(num): c = 0 while True: if num <= 1: break if num % 2 == 0...
#################################################################################################### ## A simple feed forward network using tensorflow and some of its visualization tools ##Architecture ## 2 hidden layers 1 input and 1 output layers ## input layer : 10 neurons corresponding to season, mnth,holiday,weekd...
### Small: Single hotel # The goal of the small exercise is to get practice with the syntax for querying and manipulating the data in a single, nested dictionary. # Write functions to: # - is_vacant(which_hotel, '101') # - check if a room is occupied # - check_in('101', guest_dictionary) # - assign a person to a...
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): m=0 p=0 z=0 for i in arr: if i <0: m=m+1 elif i>0: p=p+1 else: z=z+1 sum=float(p+m+z) print(float(p/s...
import re import requests from bs4 import BeautifulSoup from requests import Response class GitHubConnector: """Class to access the GitHub API.""" def __init__(self, oauthToken: str = None) -> None: """Initalizes the class. Parameters: oauthToken (str): The persona...
# a = ['d', 's', 'a'] # b = ''.join(a) # print(b) # c = {1,2,3,4} # d = {4,5,6,7,8} # print(c & d) # a = [1,2,3,4,5,5,5,5,7] # b = set(a) # a = list(b) # print(a) # phone_book = {'서울': '02', '경기': '031', '인청': '032'} # print(phone_book.items()) # for i in range(2, 10): # print('{}단'.format(i)) # for j in r...
import numpy as np def get_n_click(bid, customer): """Function that returns a stochastic number of daily clicks of new users (i.e., that have never clicked before these ads) as a function depending on the bid""" alpha = 1 beta = 1 if customer == 1: alpha = 100 # 300 beta = 0.8 #...
# -*- coding: utf-8 -*- """ Created on Thu Jan 25 16:44:35 2018 @author: D16129083 """ coverPrice = input("What's the price of the cover book: ") numberOfCopies = input("How many copies do you need: ") discount = 0.4 initialShipping = 3.0 extraShipping = 0.75 totalCover = (float(coverPrice) - (float(coverPrice) *...
# -*- coding: utf-8 -*- """ Created on Mon Jan 29 15:30:30 2018 @author: D16129083 """ # This method checks if the value inputed by the user is a number, otherwise it # calls the method again def get_user_input(title): input_value = input(title) if isInt(input_value) or isFloat(input_value): return ...
'''WIDGETS AND GIZMOS''' w=int(input('Enter number of widgets = ')) g=int(input('Enter number of gizmos = ')) widget_weight=w*75 gizmos_weight=g*112 total_weight=widget_weight+gizmos_weight print(''' Widgets = %d Gizmos = %d Widget weight = %d Gizmos weight = %d ------------------------------------ Total we...
'''DISTANCE UNITS''' f=float(input('Enter the distance in feet: ')) i=f*12 y=f*0.333333 m=f*0.000189394 print(''' Distance in feets= %f Distance in inche= %f Distance in yard = %f Distance in miles= %f''' %(f,i,y,m))
'''REPALCING A WORD IN PYTHON ''' str='HELLO TO ALL PYTHON COMMUNITY' print('Original String : %s'%(str)) print('String after replacement : %s'%(str.replace('PYTHON','PYTHON 3.6')))
'''CELL PHONE BILL''' mint=int(input('Enter total minute:')) msg=int(input('Enter total message sent:')) print('Base charge = $15') amint=0 amsg=0 if mint>50: amint=(mint-50)*.25 print('Additional minute charge = $%.2f'%(amint)) if msg>50: amsg=(msg-50)*.15 print('Additional message charge = $%.2f'%(amsg...
'''input a number k and an array There is an array find all possible pairs of numbers which when added is divisible by the number k output count of successfully divisible pairs''' arr=[] divisible=[] count=0 print('Enter the array elements:') l=input() while l!='': arr.append(int(l)) l=input() k=int(inp...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data", one_hot = True) n_nodes_hl1= 500 n_nodes_hl2= 500 n_nodes_hl3= 500 num_class = 10 batch_size = 100 x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') def NN_model(dat...
#Write methods to implement the multiply, subtract, and divide operations for #integers. Use only the add operator. def multiply(a,b): result =0 count=0 while count<b: result=result+a count=count+1 return result
##Given a positive integer, print the next smallest and the next largest number ##that have the same number of 1 bits in their binary representation. def _getNext(n): """ Trick is to flip a 1 to 0 and a 0 to 1. To get the next biggest number, what you do is 1. Get the FIRST NON-TRAILING 0 when you read ...
##Write a method to replace all spaces in a string with'%20'. You may assume that ##the string has sufficient space at the end of the string to hold the additional ##characters, and that you are given the "true" length of the string. #Method1: Using built-in function def replace1(string): string=string.replace(" "...
##4.4 Given a binary tree, design an algorithm which creates a linked list of all the ##nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked ##lists). def BTtoLL(node): if node==None: return LL=[] current=LinkedList(node) while current.size()!=0: LL.append(cur...
##4.6 Write an algorithm to find the 'next'node (i.e., in-order successor) of a given node ##in a binary search tree. You may assume that each node has a link to its parent. def next_node(node): if node==None: return if node.right: return fetchLeftMost(node.right) cur=node par=cur.parent...
def countWaysBookWay(n): if n<0: return 0 elif n==0: return 1 else: return countWaysBookWay(n-1)+countWaysBookWay(n-2)+countWaysBookWay(n-3)
##9.3 A magic index in an array A [0. . .n-1] is defined to be an index such that A[i] ##= i. Given a sorted array of distinct integers, write a method to find a magic ##index, if one exists, in array A. """ Brute force would be to iterate through array and check index against value in array Since values are sorted and...
from barcode import EAN13 # a type of format from barcode.writer import ImageWriter #to save the barcode as a png file def barcode_create(file_name, digits): with open(file_name, 'wb') as f: #write in binary mode #numbers written in barcode where the last one is automatically generated EAN13(...
""" This script uses logistic regression to provide prediction probabilities to each individual entry """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import os class Classifier: def __init__(self, dataset, trainpath, testpath, x_train, y_train): """ ...
"""nombre = input("Cual es tu nombre?\n") print("Hola "+nombre) edad =int(input("Cuál es tu edad?\n")) edad = edad -10 print(edad) Mentira= False Verdad = True print(Mentira or Verdad)""" """Diccionario ={"paella":"comida"} print(Diccionario["paella"]) A=input("Entrada diccionario\n") B=input("Entrada descripción\n")...
from collections import deque antrian = deque([1,2,3,4,5]) print('data sekarang: ',antrian) # menambahkan data antrian.append(6) print('data masuk: ',6) print('data sekarang: ',antrian) # mengurangi data out = antrian.popleft() print('data keluar: ',out) print('data sekarang: ',antrian) out = antrian.popleft() pri...
from driveable import Driveable class Vehicle(Driveable): def __init__(self, gas_tank, engine, wheels): self.gas_tank = gas_tank self.engine = engine self.wheels = wheels.get_count() self.speed = 0 def get_wheels_count(self): if self.wheels == 0: print("Кора...
# https://www.codingame.com/ide/puzzle/codingame-sponsored-contest import sys import math def get_distance(pos1, pos2): distance = math.pow(pos1[0] - pos2[0], 2) + math.pow(pos1[1] - pos2[1], 2) print("{}{}:{}".format(pos1, pos2, distance), file=sys.stderr) return distance def get_closest_player(my_pos,...
def findMedianSortedArrays(nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ added = sorted(nums1 + nums2) added_len = len(added) half = added_len // 2 median = 0 if added_len % 2: median = added[half] else: median = 0.5 * (add...
import sys import math def print_debug(msg): print("{}".format(msg), file=sys.stderr) def list_to_str(list1): str_list = ' '.join(str(e) for e in list1[-2:]) return str_list class Graph(): def __init__(self, graph_dict=None): """ initializes a graph object If no dictionary or None...
# https://www.codingame.com/ide/puzzle/defibrillators import sys import math def distance(pos_a: tuple, pos_b: tuple) -> float: # pos is tuple (lon, lat) in degrees lon_a = math.radians(pos_a[0]) lat_a = math.radians(pos_a[1]) lon_b = math.radians(pos_b[0]) lat_b = math.radians(pos_b[1]) x = (...
import random import string import sys def get_letter(): alphabet = string.ascii_letters + " !'." return random.choice(alphabet) def create_chromosome(size): chromosome = "" for _ in range(size): chromosome += get_letter() return chromosome def get_answer(): answer = 'This is a rob...
# https://www.codingame.com/ide/puzzle/scrabble import sys import math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. def get_score(letter): scores = [ ("eaionrtlsu", 1), ("dg", 2), ("bcmp", 3), ("fhvwy", 4), ...
import sys def cal_next(r: int) -> int: for d in str(r): r += int(d) return r # r_1 = int(input()) # r_2 = int(input()) r_1 = 32 r_2 = 47 while r_1 != r_2: if r_1 > r_2: r_2 = cal_next(r_2) else: r_1 = cal_next(r_1) print("r1:{}".format(r_1), file=sys.stderr) print("r...
class Timer: def __init__(self, target, interval, time_func, sleep_func): self.start_time = time_func() self.end_time = self.start_time + target if target else None self.intermediate_time = self.start_time + interval self.interval = interval self.time_func = time_func self.sleep_func = sleep_func ...
perguntas = { 'Pergunta 1': { 'pergunta': 'Quanto é 2+2? ', 'respostas': {'a': '1', 'b': '5', 'c': '4'}, 'respostas_certa': 'c', }, 'Pergunta 2': { 'pergunta': 'Quanto é 20-7? ', 'respostas': {'a': '1', 'b': '5', 'c': '13'}, 'respostas_certa': 'c', }, ...
# Tipos de Dados """ str - string - textos int - inteiro - 123456789 -> 99999999 float - real/ponto flutuante - 10.50 1.5 - 10.99 bool - booleano/logico - True/False """ print('Marcelo', type('Marcelo')) print(True, type(True)) print(10, type(10)) print(10.1, type(10.1)) # type casting print('Marcelo', type('Marcelo'...
variavel = 'valor' def func(): print(variavel) # Não da pra alterar valor de variaveis globais de dentro da função def func2(): # global variavel -> Não é uma boa pratica de programação variavel = 'Outro valor' print(variavel) func() func2()
# While # while True: # Loop infinite # nome = input('Qual é o seu nome? ') # print(f'Olá {nome}') # break # x = 0 # while x < 10: # if x == 3: # x += 1 # continue # print(x) # x += 1 # x = 0 # while x < 10: # y = 0 # while y < 5: # print(f'X vale {x} e Y v...
from datetime import datetime import csv """ Converts time into datetime format """ def convert_time(time): return datetime.strptime(time, "%Y-%m-%d %H:%M:%S.%f") """ Calculates the difference in times in terms of seconds """ def time_diff(start, end): return (convert_time(end) - convert_time(start)).total_se...
""" This script generates a word cloud from the article words. Uploads it to Imgur and returns back the url. """ import os import random import numpy as np import requests import wordcloud from PIL import Image import config MASK_FILE = "./assets/cloud.png" FONT_FILE = "./assets/sofiapro-light.otf" IMAGE_PATH = "./...
# -*- coding: utf-8 -*- """ Created on Mon Nov 17 07:45:24 2014 @author: Dr. Olivier Wertz """ from __future__ import print_function from __future__ import absolute_import __all__ = ["Orbit"] import math import numpy as np from astropy import constants as const from astropy.time import Time import matplotlib.pyplot...
# D:\Users\Administrator\Anaconda3\python.exe # -*- coding: UTF-8 -*- # @Author : Steve # @File : 07_Queue.py # @Software: PyCharm # @Time : 2020-11-17 上午 11:32 class Queue(object): """队列""" def __init__(self): self.__list = [] def is_empty(self): """判断一个队列是否为空""" return se...
# D:\Users\Administrator\Anaconda3\python.exe # -*- coding: UTF-8 -*- # @Author : Steve # @File : 17_归并排序.py # @Software: PyCharm # @Time : 2020-11-17 下午 11:31 def merge_sort(alist): """归并排序""" if len(alist) <= 1: return alist # 递归拆分,拆分成单个元素时结束递归 mid = len(alist) // 2 left_li = merge...
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @param B : integer # @return a list of list of integers solutions = [] def pathSumUtil(s...
import numpy as np from layers import * from fast_layers import * from layer_utils import * from util import * class Transformer(object): ''' A multilayer perceptron whose purpose is to transform input images by applying a nonlinear transformation. We constrain the output by imposing a penalty for co...
from datetime import datetime class UserID (object): """ Constructor """ def __init__(self, name): """ Construct a new object. :param name: STRING, The user name. startDate: The date of the account was created. """ self.__username = name self.__startDat...
# generate a random derangement of a range # ref http://local.disia.unifi.it/merlini/papers/Derangements.pdf # http://stackoverflow.com/questions/25200220/generate-a-random-derangement-of-a-list import random def random_derangement(n): while True: v = range(n) for j in range(n - 1, -1, -1): ...
''' 利用parse模块模拟post请求 分析百度词典 分析步骤: 1. 打开F12 2. 尝试输入单词girl,发现每敲一个字母后都有请求 3. 请求地址是 http://fanyi.baidu.com/sug 4. 利用NetWork-All-Hearders,查看,发现FormData的值是 kw:girl 5. 检查返回内容格式,发现返回的是json格式内容==>需要用到json包 ''' from urllib import request, parse # 负责处理json格式的模块 import json import chardet ''' 大致流程是: 1. 利用data构造内容,然后urlopen打开 2....
#! /usr/bin/env python # To check presence of alphanumeric, alphabets, digits in a string. str1 = raw_input().strip() alnum = False alpha = False digit = False lower = False upper = False for ch in str1: if (ch >= 'a' and ch <= 'z'): alnum = True lower = True alpha = True if (ch >= '0' and ch <= '9'): alnum ...
#! /usr/bin/env python # capitalize each word in a sentence. str1 = raw_input().strip() str1 = str1 + " " for i in range(0,len(str1)): if str1[i-1] == ' ': str1 = str1[:i] + str1[i].upper() + str1[i+1:] print str1
n=int(input("Enter the number of terms : ")) result = list(map(lambda x: 2**x,range(n))) print("The total number of terms are : ",n) for i in range(n): print("2^",i,"=",result[i])
from tkinter import * root=Tk() #Window Appearancw root.title("House") c=Canvas(root,bg='white',height=700,width=1500) #----------------------------------House Front------------------------------------------------ c.create_polygon(600,250,700,150,800,250,800,400,600,400,width=2,fill="yellow",outline='black') c.creat...
#WAP to convert the number from decimal to binary using Reccursion def Convert(n): if n > 1: Convert(n//2) print(n%2,end = ' ') a=int(input("Enter the decimal number to conver into Binary : ")) Convert(a)
mylist=[] #emptylist mylist=[1,2,3,4] #list of integers print(mylist) mylist=[1,"Heello",3.6] print(mylist) mylist=[1,[1,8,9,8,[1.89,87,],(4,5,6)]] #nested list print(mylist) mylist=(1,2,5,[5,6],8) #list inside the tuple print(mylist) a=["mouse",['a']]; print(a); a=['maa','iiiiggggugg','l','a','n','h','a',['c','o']] pr...
#Converting given given temperature in Fahrenheit into degree Celsius. temperature_in_farhrenheit = float(input("Enter temperature in fahrenheit:")) celsius = (temperature_in_farhrenheit - 32) * 5 / 9 print("Temperature in celsius: " , celsius)
""" Write a Python function which accepts a string and returns a string made of the first 2 and the last 2 characters of the given string. If the string length is less than 2, return -1. Note: If the string length is equal to 2, consider the 2 characters to be the first as well as the last two characters. Sam...
list1=[5,4,15,3,1,0] print(list1) for i in range(len(list1)): min_val=min(list1) min_ind=list1.index(min_val) list1[i],list1[min_ind]=list1[min_ind],list1[i] print(list1)
class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree: def __init__(self, data=None): self.root = None if data: self.root = TreeNode(data) def insert(self, data): current = self.root # a ...
""" Example: Given an array of distinct integer values, count the number of pairs of integers that have given difference k. For example, given the array {1, 7, 5, 9, 2, 12, 3} and the difference k = 2, there are four pairs with difference 2: (1, 3), (3, 5), (5, 7), (7, 9). """ def diff_k(arr=[], k=2): ...
from CipherInterface import * import math # The enigma cipher in this implementation takes in a key that is 26x3 characters lone # this is then translated into 26 character keys for each rotor # each rotor key should only contain 1 of each character in the alphabet # the rotor will translate a single character across...
class Worker: def __init__(self, surname, experience, hourly_wag, hours_work): self.surname = surname self.experience = max(experience, 0) self.hourly_wage = max(hourly_wag, 0) self.hours_work = max(hours_work, 0) self.salary = self.calculate_salary(self.hours_work, self.hour...
def sumDigits(number) : sum = 0; while(number > 0) : sum += int(number%10) number = number /10 print(sum) if __name__ == "__main__": number = int(input("Enter a number")) sumDigits(number)
def Add(number1 , number2) : print("Addition is :: ",number1 + number2) def Sub(number1 , number2) : print("Substraction is :: ",number1 - number2) def Mult(number1 , number2) : print("Multiplication is :: ",number1 * number2) def Div(number1,number2) : print("Division is ::",number1/number2)
from __future__ import print_function import math z = 0 a = [] def series(i): x = z x = 0 for n in range(i+1): x += 10 * (((math.cos((1 + 2.3 * n) / 3)) * 3) + 6) # x += 0 + (10 * n) # x += 250 - (4.5 * n) print(x) def sequence(i): b = a b = [] for n in range(i+1...
z = 0 a = [] def series(i): x = z x = 0 for n in range(i): x += enter_formula() print("\n", x) def sequence(i): b = a b = [] for n in range(i): c = enter_formula() b.append(c) print("\n", b) # choose sequence or serie # diplay choices def display_choices():...
#Program: reader.py #Authors: Calvin Brown, Chad Gilmer #Description: Reades a file in and does things on it like ls, stat, and info of the file import sys import os import struct from Utilities import * from lsInfo import * from statInfo import * from info import * from read import * from changeDirectory import * fil...
""" Part 4 - Class Report: Generate Products and report on them """ import random from acme import Product # Variable Definitions for use throughout code ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(number...
#import requests from goose import Goose import urllib from bs4 import BeautifulSoup """ this function visits the link to the article and extracts the article text For more on requests: http://docs.python-requests.org/en/master/user/quickstart/ http://web.stanford.edu/~zlotnick/TextAsData/Web_Scraping_wit...
print('enter any number ') number = int(input()) n = 1 while True : print(number,'*',n,'=',number*n) n = n + 1 if n >= 11: break print('end')
maths = int(input('enter the markas of maths: ')) phy = int(input('enter the markas of physics: ')) chem = int(input('enter the markas of chemistry: ')) bio = int(input('enter the markas of bio: ')) m = int(input('enter the markas of computer: ')) per = (maths+phy+chem+bio+m)/5 print('percentage: ',per) if per...
#def factorial(x): # if x==1: # return 1 # return x * factorial(x-1) #result = factorial(3) #print(result) def factorial(x): if x==1: return 1 result = factorial(x-1) return x * result result =factorial(3) print(result)
# class method and static method class Person: def __init__(self,name,age): self.name = name self.age = age def get_name(self): return self.name def get_age(self): return self.age @classmethod def object_by_year(cls,name,year): return cls...
#!/usr/bin/python """ main routine of the intro cutter. 1 - extract a wav file with the intro from the given video, position and duration must be known and set in conf.py 2 - make a fingerprint from the extracted wav file 3 - iterate all video files in the given directory 3a - extract first half of the audio t...
def get_hills(n,arr): hill = 0 for i in range(1,n-1): if arr[i]>arr[i+1] and arr[i]>arr[i-1]: hill+=1 return hill def get_valleys(n,arr): valley=0 for i in range(1,n-1): if arr[i]<arr[i+1] and arr[i]<arr[i-1]: valley+=1 return valley def solution(n,arr): ans = get_hills(n,arr)+get_valleys(n,arr) f...
import base64 import numpy as np import random import rsa import math #TODO create function that allows user to enter a message, also allows the user to enter two separate "e" values # and then will use the rsa public key generation function to generate a modulus N. Calculates the ciphertexts. def userInput(): e1...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import json import pdb import os one_word_conjunction = ['y', 'a', 'e', 'o', 'u'] char_end_allowed = ['a', 'e', 'o', 'u', 'n', 'r', 's', 'l'] def pegar_tripletas(w1, w2, w3): separados = w1 + " " + w2 + " " + w3 if len(w1) > 1: if len(w2) > 1: return separ...
# Takes in a FEN-string and returns a boardMatrix on the following format: # (yes this convertion looses some information about the game that is not relevant for drawing the board) # [['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], # ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], # [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], # [...
from Board import * from tkinter import * myBoard = Board() myBoard.createBoard("easy.txt") #myBoard.printBoard() myEntries = [] root = Tk() #create entries and assign them a stringVar for row in range(9): myEntries.append([]) for col in range(9): entry = Entry(root, width = 2, justify = "center", fo...
import tensorflow as tf #importing tensor flow librarry hello = tf.constant('hello,Muneeba') # storing a strong as constant sess = tf.Session() # creating a tensorflow session print(sess.run(hello)) # sess.run is responsible for running the session #PLACEHOLDERS #Placeholders are the terminals/data point throug...
from random import shuffle from card import Card from player import Player def generate_deck(): """Generate a deck of cards. Returns: a new deck containing 52 cards """ deck = [] order = list(range(1,53)) shuffle(order) #shuffles the order randomly for i in order:#puts card in the de...
# First of all I need to create a class that will initialize also a dictionay # created using classe and PPO class Budg_calculator : def __init__ (self, amount): self.available = amount # this is the initial amount self.budgets = {} self.expenditure = {} self.first_budget = amou...
class Pegawai: kenaikanGaji = 1.05 def __init__(self, nama, email, gaji): self.namaPegawai = nama self.emailPegawai = email + 'gmail.com' self.gajiPegawai = gaji def gajiCalculateMontly(self): self.gajiPegawai = self.gajiPegawai * 30 return self.gajiPegawai ...
# Text 1 # Time period: 200 BC import random country_list = ['K*zakh-stan', 'K@z@kh-land', 'Qaz*qStepp*'] country_description = ['big', 'empty', 'large', 'enourmous', 'abanoded'] human_adjective = ['bold', 'crazy', 'creative', 'primitive'] country_name = random.choice(country_list) group_name = ['Saka', 'Skythian', '...
# EJ (Mercy) Emelike # May 26, 2016 # Homework 2 #LISTS # 0) make list numbers = [22, 90, 0, -10, 3, 22, 48] # 1) print list print(numbers) # 2) print 4th element of list print(numbers[3]) # 3) print sum of 2nd and 4th element print(numbers[1] + numbers[3]) # 4) print 2nd largest value numbers_sorted = sorted(numb...