text
stringlengths
37
1.41M
# Write a program that reads a number from the standard input, then draws a # pyramid like this: # # # * # *** # ***** # ******* # # The pyramid should have as many lines as the number was number = int(input('Give me a number please: ')) for e in range(number): if e > 0 and e %2 == 1: print((number...
# Things are a little bit messed up # Your job is to decode the notSoCrypticMessage by using the hashmap as a look up table # Assemble the fragments into the out variable out = "" notSoCrypticMessage = [1, 12, 1, 2, 11, 1, 7, 11, 1, 49, 1, 3, 11, 1, 50, 11] hashmap = [ {7: "run around and desert you"}, {50: ...
""" This program will open provided world map image Read latitude, longitude and population data from countries csv file provided in countries population folder Read total covid 19 infected cases from txt files in the countries covid directory Plot on the world map according to the data read from these ...
from linked_list import LinkedList from stack import Stack from queue import Queue from stock_account import * from companies import * import json if __name__ == "__main__": print("Commercial Data Processing") linked_list = LinkedList() while True: print("Enter 1 to create account\n2 to access acc...
s=set()#to create an empty set or else a not so empty example: s = {1,2} s.add('1') print(s) s.add('1') print(s) s.add(1) #{1,'1'} print(s) s2=('2') s3 = s.union(s2) print(s3) s4 = s.intersection(s2) print(s4)
# create an init function to set length and width # write code to get area() # func to get perimeter() ret peri of rect class rectangle: def __init__(self,length,width): self.length = length self.width = width def getarea(self): return self.length*self.width def getperimet...
try: x = float(input("enter a number")) x1 = float(input("enter a another number")) z = 10/0 print(x) print(y) except ValueError as e : #this comes first if you want to use 2 or more exeption print(e) except ZeroDivisionError as e: print("it is zero division error") except Exception as ...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt """ This is a test program, where a network of 2 hidden layers is used to fit the curve. Batch Normalization is implemented. Basic Tensorflow and Tensorboard APIs are used. """ def add_layer(inputs,in_training,in_size,out_size,activation_func...
# Write code to create a new string by concatenating the first 2 and the last 2 chars of the given string. If the length of the given string is less than 2, then return an empty string. def join(String): join_str="" length = len(String) if length<2: return join_str join_str=String[:2]+Stri...
# Write code to convert the given sentence to Sentence Case (Capitalize the first letter of each word) def capt_sen(String): capt_sentence = "" length = len(String) for a in range(0,length): if (a==0) or (ord(String[a-1])==32): if (ord(String[a])>96) and (ord(String[a])<123): ...
# Reverse the given string in python: def reverse(String): str = "" for a in String: str = a + str return str String = "Udhaikumar" print("The reversed string is: ",end=":") print(reverse(String))
# Write code to remove all the spaces and special symbols from a given string: def remove_syms(String): str="" for a in String: if ((ord(a)>64 and ord(a)<91) or (ord(a)>96 and ord(a)<123) or (ord(a)>47 and ord(a)<58)): str+=a return str String = """India scored 167 runs by the los...
#Faça um Programa que peça o raio de um círculo, #calcule e mostre sua área. rad = float (input('Informe o raio do círculo: ')) area = 3.14 * rad**2 print(f'A área do círculo é {area}m²')
import random def myrand(): mini = int(input("Enter Min Range")) maxi = int(input("Enter Max Range")) range = (maxi - mini + 1) ans = (random.random() * range + mini) print(int(ans)) print(ans)
ans = 0 def facto(x): if x == 0: return 1 return x * facto(x - 1) x=int(input("Enter The Number")) ans = facto(x) print(ans)
# Uses python3 import sys def fibonacci_partial_sum_naive(from_, to): if m == 0 and n == 1: return n elif m == 0 and n == 2: return n elif m == 1 and n == 2: return n elif m == 0 and n > 2: a, b = 0, 1 cum = 1 for x in range(1, n): a, b = b, (...
def check_board_value(row, column, sign, board, size, win_amount): res_row = res_column = res_diag1 = res_diag2 = False board_row_list = [] board_column_list = [] for i in range(size): board_row_list.append(board[row][i]) res_row = check_win_condition(board_row_list, sign, win_amount) ...
size=int(input("Введите размер массива: ")) array=[] for s in range(size): value=int(input("Введите значение массива:")) array.append(value) print("Массив имеет вид:",array) for i in range(size): if int(array[i])%3==0: print(array[i])
""" Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3...
""" The pond problem Calculate the sizes for all ponds on a plot of land Land is represented like this: 0 1 2 3 0 0 4 5 0 6 7 8 9 0 1 0 2 3 0 4 What is 0 (lowest point) and land is everything else A body of water can be connected by any adjacent cells (Think horizontal, diagonal, and vertical) """ import pprin...
def coin_sums(target): coins = [1, 2, 5, 10, 20, 50, 100, 200] ways = [1] + [0]*target for coin in coins: for i in xrange(coin, target+1): ways[i] += ways[i-coin] print ways return ways[target] def multiples(high): s = 0 stor = [] for i in xrange(1, high): if i % 3 == 0 or i % 5 == 0: s +...
class PriceCalculator(): '''Calculate ticket price based on user input''' def __init__(self, age): '''Initalize attributes''' self.age = age ticket = 0 ticket_list = [] def input(self, age): if age.isnumeric == True: def integer_input(self, age): ...
import json class MovieEncoder(json.JSONEncoder): def default(self, o): return o.__dict__ def from_json(json_movie): return Movie(json_movie['id'], json_movie['title'], json_movie['year'], json_movie['actors'], json_movie['director']) class Movie: def __init__(self, movie_id, ...
import time import RPi.GPIO as GPIO import argparse parser = argparse.ArgumentParser() parser.add_argument("-w", "--wait", type=float, default=0.001, help="Time to wait (in seconds) between steps. Default time is 0.001") parser.add_argument("-s", "--steps", type=int, default=500, help="Number of steps to take. Defaul...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 18 08:43:00 2020 @author: matty """ """ This script is used to calculate the correlation per season between model output and observations for a given region. The correlation is performed for each grid point per season. The seasons are defined as Sum...
""" Search for colour hex decimals by using color name """ CODE_TO_NAME = { "rosybrown": " #bc8f8f", "saddlebrown": "#8b4513", "sandybrown": "#f4a460", "slategray": "#708090", "yellowgreen": "#9acd32", "whitesmoke": "#f5f5f5", "violetred": "#d02090", "navyblue": "#000080", "plum": "...
""" CP1404/CP5632 - Practical Broken program to determine score status """ import random def main(): user_score = float(input("Enter score: ")) print(score_result(user_score), end="\n\n") print("Computer generated score from a range of -10 to 110") computer_score = random.randint(-10, 110) print(...
import pygame pygame.init() X=400 Y=300 pos_x=240 pos_y=300 velocidade = 10 velocidade_outros = 20 fundo = pygame.image.load('tela.jpg')#baixar PNG carro = pygame.image.load('carro.png') policia = pygame.image.load('policia.png') ambulancia = pygame.image.load('ambulancia.png') caminhonete = pygame.image.load('caminho...
from array import * print ('hola') a = array('d',[4,6,3,6,7,2,5]) b = [] #almacena corridas hacia arriba c =[] #almacena corridas hacia abajo corrida = 'corrida: ' numCorridas=0 rango = len(a) for i in range(rango-1): if (a[i+1]>=a[i]): print a[i+1] print ('es mayor que') print a[i] if i < rango: p...
from xml.dom import minidom import xml.etree.ElementTree as ET from listaCircular import ListaCircular from Matrices import Matriz from listaDato import ListaDato data = ListaCircular() nombre = "" def pedirOpcion (): correcto = False opcion = 0 while (not correcto): try: opcion = int(inp...
nombre = input("Bienvenido al programa, ingresá tu nombre...") print("Hola, ", nombre, ". Por favor, elegí una de las siguientes opciones...") print("1-Detectar mayor de 3 números\n2-Identificar un horario\n3-Decidir si suma de cifras deun número de 3 digitos es par o impar\n4-Descomponer un número de cinco dígitos y m...
import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split ###################### General functions ###################### def scale_general(df, scaler): ''' Scale a dataframe using a given scaler (fit ...
class Board(object): def __init__(self): self.positions = [None]*9 def draw(self): for i in range(0, 3): print "\t\t %s | %s | %s " % (self.pos(i*3), self.pos(i*3+1), self.pos(i*3+2)) if i < 2: print "\t\t-----------" def pos(self, pos): sym ...
# assing the number of cars to a variable cars = 100 # assing the space in a car to a variable space_in_a_car = 4 # assign the number of drivers to a variable drivers = 30 # assign the number of passengers to a variable passengers = 90 # assign the calculation for cars not driven to a variable cars_not_driven = car...
class ContaBancaria: numero = "00000-0" agencia = "0000-0" saldo = 0.0 codigo_tipo = "01" #01 = Conta Corrente, 02 = Poupança nome_tipo = "" def __init__(self, numero, agencia, saldo, codigo_tipo): if (self.validaTipo(codigo_tipo) == True): self.numero = numero s...
class Fatura: def __init__(self, num_item, descricao, quantidade=0, preco_unitario=0): self.__num_item = num_item self.__descricao = descricao if (quantidade < 0): quantidade = 0 self.__quantidade = quantidade if (preco_unitario < 0): preco_unitario =...
#Python3 import socket import sys import subprocess import time import os def main(): print(' ', '#'*40, '\n\n programs:\n client\n server\n QUIT\n\n', '#'*40) available_programs = ['client', 'server', 'QUIT'] while True: selection = input('>>>') if selection in available_programs: ...
#Performs a standard recursive binary search for a target value def BinarySearch(list, target, start, end): if start >= end: return "No." else: mid = (start+end)/2 if list[mid] == target: return "Yes." elif list[mid] > target: return BinarySearch(list,target,start,mid-1) else: return BinarySearc...
a=10 b=20 if a==10: print("Hello world") else: print(b)
#!/usr/bin/env python # coding: utf-8 # In[1]: print("Hello world!") # In[3]: #인공지능과 기계학습 과제 - 3주차 num1=int(input("첫번째 정수 : ")) num2=int(input("두번째 정수 : ")) operator=input("연산자 : ") if(operator=="+"): print(num1,operator,num2,"=",num1+num2) elif(operator=="-"): print(num1,operator,num2,"=",num1-num2) el...
import csv data = [] with open(r"D:\PythonProjects\C129\venv\data2.csv","r") as f: csvreader = csv.reader(f) for row in csvreader: data.append(row) headers = data[0] planet_data = data[1:] # CONVERTING ALL PLANET NAMES TO LOWER CASE for data_point in planet_data: data_point[2] ...
import unittest from src.greedy_examples import * class TestExamples(unittest.TestCase): def test1_children_groups(self): ages = [5, 5.5, 7, 7, 3, 3.3, 4] n_groups = children_groups(ages) self.assertEqual(n_groups, 3, "children_groups: wrong result") def test2_car_stops(self): ...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Hongrui' import threading import time #定义每个线程要执行的操作 def run(n): print "task:",n time.sleep(2) print "task done",n start_time = time.time() thread_list = [] if __name__ =="__main__": for i in range(30): t1 = threadi...
# !/usr/bin/env python # _*_ coding:utf-8 _*_ __author__ = 'Hongrui' import collections def find_J(J,S): sum = 0 J_dict = collections.Counter(J) S_dict = collections.Counter(S) for k,v in J_dict.items(): if S_dict.has_key(k): sum+=S_dict[k] print sum # tmp ={} # for i in...
## CRIAÇÃO DO CÓDIGO # a. Crie as variáveis necessárias para que o programa funcione corretamente. '''não compreendi a diferença entre essa letra A e as letras B e D. Tirar dúvida com André e executar este comando''' # b. Inicialize as variáveis com valores padrão adequados. '''não compreendi a diferença entre essa...
# Simple Password Generator # import random # initialize variables complex_a = ["simple" , "a-z"] # ASCII Dec: 97 - 122 complex_b = ["better" , "a-z,A-Z"] # ASCII Dec: 65 - 90 complex_c = ["strong" , "a-z,A-Z,0-9"] # ASCII Dec: 48 - 57 complex_d = ["complex" , "a-z,A-Z,0-9,sym"] # ASCII Dec: 33 - 47, 58 - 6...
#!/usr/bin/python3 ''' Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320 ''' f=1 x=int(input("Enter Number:")) if(x<0): print(...
""" O(n^2) but shift operation uses ~1/3 less processing work as an exchange. So it will perform better than bubble and selection sorts. """ #### first implementation # def insertionSort(alist): # # [17, 2, 3] # for index in range(1,len(alist)): # insertion sort starts with the first item as an already sorted l...
import re, os, collections # declaring functions def verification_of_data(): print('Сonfirm that you entered the correct answers (у/n): ') answer = input() if re.match('[yY]', answer): print('Positive answer: {}'.format(answer)) print('Writing to a file') wri...
# Программа берет данные пользователя и сохраняет их # Приветствие print("Привет, ответь на несколько вопросов.") # Переменные и ввод данных n={} n['name'] = input("Как тебя зовут?:") n['surname'] = input("Напиши свою фамилию:") n['age'] = int(input("В каком году ты родился? Например '1999':")) n['hobby'] = input(...
name = input("Введите свое имя?") age = int(input("Сколько вам лет?")) city = input("Где вы живете?") print("Ага, значит вас зовут %s, вам %i лет," "и вы живете в %s. Ого!" % (name,age,city)) outputfile ="Data.txt" datafile = open(outputfile, mode='w') datafile.write("data:"+ " " + name + " " + str(age) + " "...
print ('--- === Dictionaries === --- ') name = input('Enter your name:') last_name = input ("Enter your last name:") age = input ('Enter your age:') city = input ('Where do you live?') dict_inform = { 'name': name, 'last_name': last_name, 'age': age, 'city' : city } print (dict_inform) results ...
print ("Hello! by filling out a simple form to continue using the site.") anketa = open("anketa.txt", "w") name = input ("What is your name?") surname = input ("What is your surname?") age = int(input ("How old are you?")) town = input ("Where do you live?") name_surname = name + ' ' + surname letter = "Thank you %s...
n = input('Enter your name:') s = input('Enter your surname:') a = int(input('Enter your age:')) e = input('Enter your e-mail:') l = input('Enter your login:') content = open('data.txt', 'w') list = 'Your data:\nname %s;\nsurname %s;\nage %s;\ne-mail %s;\nlogin %s.' %(n, s, a, e, l) content.write(list) content.close(...
import csv with open('lunch.csv', 'r',encoding='utf8') as f: # lines = f.readlines() csv_reader=csv.reader(f) for i in csv_reader: print(i) print(type(csv_reader)) # for line in lines: # print(line.strip().split(','))
# 3. 도시별 최근 3일의 온도입니다. city = { '서울': [-6, -10, 5], '대전': [-3, -5, 2], '광주': [0, -2, 10], '부산': [2, -2, 9], } # 3-1. 도시별 최근 3일의 온도 평균은? # 아래에 코드를 작성해 주세요. for cit in city.keys() : sum=0 for tem in city[cit]: sum += tem print('{0} : {1}'.format(cit,round(sum/len(city[cit]),2)))
""" My version of the game of life """ import random import itertools import uuid import math import pygame DISPLAY = (800, 600) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) class Blob(): """ Unit in the Game of Life """ def __init__(self, position=(0, 0), velocit...
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ Tic Tac Toe OO game """ import logging import random #from board import Board LOGGER = logging.getLogger() LOGGER.setLevel(logging.DEBUG) class Player(): """ represents a random player a player shouldn't have a marker? or should they made this a s...
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ Board object for Connect Four Created 10/6/18 """ import logging import copy import itertools LOGGER = logging.getLogger() LOGGER.setLevel(logging.DEBUG) class Board: """ object represents the board with X, O markers """ EMPTY = ' ' """ c...
def get_total_plan(steps, h): # steps Array that used to store the step length # n the total number of stairs f = [0] * (h + 1) f[0] = 1 for i in range(1, h + 1): for x in steps: if i >= x: f[i] += f[i - x] return f[h] print(get_total_plan([34, 4...
class Polynomial: def __init__(self, *coefficients): """ input: coefficients are in the form a_n, ...a_1, a_0 """ self.coefficients = list(coefficients) # tuple is turned into a list def __repr__(self): """ method to return the canonical string representation ...
class Node: # Node Section def __init__(self,value): self.prev=None self.next=None self.value=value class Double_link_list: def __init__(self): self.head=None self.tail=None self.size=0 def add_value(self,value): # new Value Add node=No...
# Algorithm: # 1 move goat # 2 move wolf or move cabbage # 3 move goat back # 4 move wolf or move cabbage # 5 move goat def main(): print('\n--------------------- Wolf - Goat - Cabbage Problem ------------------------------------\n') play = 'y' while play == 'y' or play == 'Y': move1 =...
class Song(): def __init__(self, name, artist, length): self.name = name self.artist = artist self.length = length self.song_list = [] def add_new_song(self, name, artist, length): new_song = {"song_title": name, "artist": artist, "song_length": length} self.song...
#!/usr/bin/env python3 print("Входные данные ") x = int(input()) print("Выходные данные") print((x // 60) %24 ) print(x % 60)
#!/usr/bin/env python3 # Tuples: an immutable data structure # Lists are mutable and Tuples are immutable # Creating an Empty Tuple # empty_tuple = () # empty_tuple = tuple() # Mutable list_1 = ['History', 'Math', 'Physics', 'CompSci'] list_2 = list_1 print(list_1) print(list_2) list_1[0] = 'Art' print(list_1) pr...
#!/usr/bin/env python3 """ p. 96 ~ """ from matplotlib.pyplot import * import numpy as np # Basic Usage plot([1, 2, 3, 9]) xlabel("x- axis") ylabel("y- axis") title("My Figure") show() # Cosign, Sign x = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(x), np.sin(x) plot(x, C) plot(x, S) show()
#!/usr/bin/env python3 import datetime class Employee: # Class Variable num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): # Instance Variables (Attributes) self.first = first self.last = last self.email = first + '.' + last + '@email.com' ...
#!/usr/bin/env python3 """ Random Module - Generate pseudo-random numbers - Use Secrets module for security purposes or cryptography """ import random # Random method: Return a random value(0 <= r < 1) value = random.random() print(value) # Randint method: Return a random integer(a <= r <= b) va...
#!/usr/bin/env python3 # Python Tutorials # str() vs repr() # The goal of __str__ is to be readable # The goal of __repr__ is to be unambiguous a = [1, 2, 3, 4] b = 'sample string' print(str(a)) print(repr(a)) print(str(b)) print(repr(b))
from copy import deepcopy import functions as ft from itertools import permutations def posicao(arr, value): for i in range(len(arr)): if(arr[i]==value): return i return -1 def insert(m , key1, key2, value1, value2, inicial=0): listx = [] cont1 = inicial while(cont...
a = 12 b = 12 print(a + b) print(a - b) print(a / b) print(a // b) print(a % b) print(a**b)
from collections import deque if __name__ == '__main__': de = deque([1, 2, 3]) print('The deque:', end=' ') print(*de) de.append(4) print('The deque after appending to the right:', *de) de.appendleft(6) print('The deque after appending to the left:', *de) de.append(3) print('The ...
from doubly_linked_list import Node, DoublyLinkedList if __name__ == '__main__': llist = DoublyLinkedList() llist.head = Node(1) second = Node(2) third = Node(4) llist.head.next = second second.next = third llist.print_list() llist.insert_after(2, 3) print('\nInserting 3 after 2...
from Graph import Graph def create_graph(): graph = Graph(8, True) graph.add_weighted_edge('A', 'B', 3) graph.add_weighted_edge('A', 'C', 6) graph.add_weighted_edge('B', 'C', 4) graph.add_weighted_edge('B', 'D', 4) graph.add_weighted_edge('B', 'E', 11) graph.add_weighted_edge('C', 'D', 8) ...
from heapq import heappush, heappop, heapify class MinHeap: def __init__(self): self.heap = [] def parent(self, i): return (i - 1) // 2 def insert_key(self, key): heappush(self.heap, key) def decrease_key(self, i, new_val): """ Decrease value of key at index 'i' to n...
from Graph import Graph from heapq import heappush, heappop def create_graph(): graph = Graph(8, False) graph.add_weighted_edge(0, 1, 10) graph.add_weighted_edge(0, 2, 1) graph.add_weighted_edge(0, 3, 4) graph.add_weighted_edge(1, 2, 3) graph.add_weighted_edge(1, 4, 0) graph.add_weighted_e...
import os from pandas import DataFrame from randomcsv.Column import Column from randomcsv.FileUtils import write class CsvGenerator: """ Main Class, used to generate CSV files and pandas.DataFrame Methods ------- add_column: Configure Columns by adding Column Objects. calculate_column: Add f...
from numpy.random import RandomState from randomcsv.Column import Column class CategoryColumn(Column): """ A Column with categorical data. Example ------ >>> column = CategoryColumn('MyCategory', ['A', 'B', 'C']) >>> column.generate_entries(3) 0 A 1 A 2 C dtype: categor...
import pandas as pd import numpy as np # math reference: https://towardsdatascience.com/logistic-regression-detailed-overview-46c4da4303bc class LogisticRegressionClassifier: def __init__(self): pass def sigmoid(self, X, beta): ''' X is a matrix of shape (n, p) be...
# Listas vogais = ['a', 'e', 'i', 'o', 'u'] for vogal in vogais: print(f'Posição = {vogais.index(vogal)}, valor = {vogal}') # Mesmo resultado vogais = [] print(f"\nTipo de objetos vogais = {type(vogais)}\n") vogais.append('a') vogais.append('e') vogais.append('i') vogais.append('o') vogais.append('u') for p,...
# -*- coding: utf-8 -*- version = 3.8 print(version) #%% version > 3 version <= 3 #%% number = 1200 number > 1000 number == 1200 number == 1000 number != 1200 number != 1199 #%% 4 spacje wciecia przed instrukcja # if [warunek]: # [instrukcje] #%% if 8 > 10: prin...
""" This module lets you practice the ACCUMULATOR pattern in its simplest classic forms: SUMMING: total = total + number Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Aaron Wilkin, their colleagues, and Ben Hawkins. """ # Done: 1. PUT YOUR NAME IN THE ABOVE LINE. imp...
import os def rename_files(): file_list = os.listdir('/Users/cidmedeiros1/Pictures/Piri_Trip') print(file_list) saved_path = os.getcwd() print("Working dir is " + saved_path) os.chdir('/Users/cidmedeiros1/Pictures/Piri_Trip') var0 = '.JPG' var1 = 1 var2 = 'Piri_Trip' for file_name in...
#!/usr/bin/env python3 import json import argparse import os import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_val_from_json(filename, field): if not os.path.exists(filename): eprint(f'ERROR: {filename} not found!') sys.exit(1) with open(filename) as ...
from Localizer import OneDimensionalLocalizer from SimpleMaze import random_maze, render_graph from typing import List, Dict def dijkstra(maze: List[List[int]], start: int, end: int) -> Dict[int, int]: """ Given a maze, and the start and end nodes, return a dictionary of the distances from the start...
#!/usr/bin/env python # encoding: utf-8 class Handler: def __init__(self): self.successor = None def set_successor(self, successor): self.successor = successor def handle_request(self, request): pass class ConcreteHandlerA(Handler): def handle_request(self, request): ...
import turtle as tl class Window: def __init__(self, width=800, height=600): self.WIDTH = width self.HEIGHT = height self.tl = tl self.tl.hideturtle() self.tl.title("GAME OF THE GAME OF THE GAME") self.tl.screensize(self.WIDTH, self.HEIGHT) tl.title("GAME ...
# 判断是否是 2 的幂次方 # 法一:& 运算 n&(-n) = 0 class Solution: def isPowerOfTwo(self, n: int) -> bool: return (n > 0) && (n & -n) == n class Solution: def isPowerOfTwo(self, n: int) -> bool: return n>0 and not (n&n-1) # 法二:移位,左移一位,=*2; 右移1位,缩小2倍 class Solution: def isPowerOfTwo(self, n: int) ...
import tkinter class TestAvg: def __init__(self): self.main_window = tkinter.Tk() self.main_window.title("Calculate average") self.top1_frame = tkinter.Frame(self.main_window) self.top2_frame = tkinter.Frame(self.main_window) self.top3_frame = tkinter.Frame(self.main_windo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """《算法导论》 174页 红黑树 重点是在插入或删除元素后,通过左旋、右旋和改变颜色恢复红黑树的性质""" from a_sequence_generator import generate_sequence Red = True Black = False class Tree_node: def __init__(self, data): self.data = data self.color = Black self.p = None ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """《算法导论》 070页 随机排列数组""" import numpy as np from a_swap import * def permute_by_sorting(lst): length = len(lst) p = np.random.random(length) # p = lst.copy() # sort lst using p as key for i in range(0, length): for j in range(1, length-i...
def fast_expoentiation(a,b): res=1 while(b!=0): bit = b & 1 if bit==1: res=res*a a*=a b=b>>1 return res print(fast_expoentiation(3,5))
def GCD(a,b): return a if b==0 else GCD(b,a%b) a,b = [int(i) for i in input().split()] print(GCD(a,b))
def get_ith_Bit(N,i): if N & (1<<i) != 0: return 1 else: return 0 def clear_ith_bit(N,i): mask = ~(1<<i) return N & mask def update_ith_bit(N,i,v): mask = ~(1<<i) N = N & mask return N | (v<<i) def set_ith_bit(N,i): return N | (1<<i) def is_odd_even(N): return N &...
keypad = ["","","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"] def generate_names(arr,out,i): if i==len(arr) or len(out)==len(arr): print(out) return num = arr[i] if num == 0 or num==1: # For cases having "" string in keypad generate_names(arr,out,i+1) else : ...
def multiply(A,B): res = [[0]*(k+1) for i in range(k+1)] for i in range(k+1): for j in range(k+1): temp = 0 for x in range(k+1): temp = (temp + (A[i][x]*B[x][j])) res[i][j] = temp return res def power(T,n): if n==1: return...
# Accepted on SPOJ def canPlaceCow(arr,n,c,min_sep): cnt = 1 # Placed cow in first stall lastCowBarn = arr[0] for i in range(1,n): if arr[i] - lastCowBarn >= min_sep: # Cow can be placed at this stall cnt+=1 lastCowBarn = arr[i] # updating last barn pos if ...
def bin_to_dec(bin): bin = str(bin) mul = 1 res=0 for i in range(len(bin)-1,-1,-1): if bin[i]=='1': res+=mul mul=mul*2 return res print(bin_to_dec("1101100")) #89 #108
ansset = set() def print_unique_permutation(inp,i,n): global ansset if i == n: res = "" for j in inp: res=res + j+" " ansset.add(res) return for j in range(i,n): if i==j or inp[i] != inp[j]: inp[i],inp[j] = inp[j],inp[i] ...