text
stringlengths
37
1.41M
d = {'k1': 1, 'k2': 2} dict1 = {x: x ** 2 for x in range(10)} print(dict1)
import math import numpy as np def load_matrices(filename): ''' Returns two matrices if the correct filename is given. ''' files = np.load(filename) return files['arr_0'], files['arr_1'] def method1(A,B): ''' Multiply two matrices together using nested for loops ''' product_matrix = np.zeros((A.shape[0], B...
# testDriver.py """Test Driver for Getting Started Lab""" # Test script def test(student_module, late=False): """Test script. You must import the students file as a module. X points for problem 1 X points for problem 2 X points for problem 3 X points for problem 4 ... Parameters: ...
# solutions.py """Volume I: Monte Carlo Integration Solutions file. Written by Tanner Christensen """ import numpy as np import scipy.stats as stats def mc_int(f, mins, maxs, numPoints=500, numIters=100): """Use Monte-Carlo integration to approximate the integral of f on the box defined by mins and maxs. ...
# name this file 'solutions.py' """ Volume II Lab 3: Public Key Encryption (RSA) Tanner Christensen <Date> <Class> """ from rsa_tools import * from Crypto.PublicKey import RSA from ExEucAlg import EucAlg import random # Problem 1: Implement the following RSA system. class myRSA(object): """RSA String ...
# WordList.py """Volume II Lab 5: Data Structures II (Trees). Auxiliary file Use this function to complete problem 4. Do not modify. """ import numpy as np # Use this function in problem 4. def create_word_list(n, filename='English.txt'): """Read in a list of words from the specified file. Randomize the order...
def find_max(l, index): if len(l) == 1: # maximum found return l[0] elif l[index-1] - l[index] < 0: # if increasing return find_max(l[index:], len(l[index:])//2) elif l[index-1] - l[index] > 0: # if decreasing return find_max(l[:index], len(l[:index])//2) ...
from __future__ import division import numpy as np from scipy import linalg as la def unit_sphere(): """I wasn't getting good estimates with 10000, so I bumped it up.""" #numPoints = 10000 numPoints = 1000000 points = np.random.rand(3,numPoints) points = points*2-1 """ This part h...
#!/usr/bin/env python2 """You're going to write a binary search function. You should use an iterative approach - meaning using loops. Your function should take two inputs: a Python list to search through, and the value you're searching for. Assume the list only has distinct elements, meaning there are no repeated valu...
import random from isSimple import is_simple from Point import Point def generate_random_point(min, max): return Point(random.randint(min, max), random.randint(min, max)) def generate_simple_polygon(min, max, n=6): p = [] simple = False while not simple: p = [generate_random_point(min, max) ...
#Programa que cria um vetor utilizando o metodo .split() #E faz o usuario tentar adivinhar um nome da lista import random nomes = ''' Ana Maria Júlia Beatriz Sabrina Mirela Hedmilla Marcela Carla essica Luiza Ingrid Karol Jamille Fernanda'''.split() nomes.sort() print (' '.join(nomes)) sorteado = random.choice(nomes...
#É preciso criar uma nova string para alterar uma string #Pois em python, apesar da string ser muito rapida, ela #ela é imutavel s = 'Cassio' s = 'X' + s[1:]
def pdb2selection(pdbfile): ''' A little utility function to convert 'mask' pdb files into MDAnalysis-style selection strings. Basically it reads the second column (atom number) and uses it to construct 'bynum' selections. Runs of consecutive numbers are expressed in start:stop form. ''' se...
# http://www.codeskulptor.org/#user41_A9yVpwrc7NGxFDu.py """ Monte Carlo Tic-Tac-Toe Player """ import random import poc_ttt_gui import poc_ttt_provided as provided # Constants for Monte Carlo simulator # You may change the values of these constants as desired, but # do not change their names. NTRIALS = 50 ...
""" Planner for Yahtzee Simplifications: only allow discard and roll, only score against upper level """ # http://www.codeskulptor.org/#user41_83LnQWWKg06l4fJ.py # game link: https://cardgames.io/yahtzee/ # Used to increase the timeout, if necessary import codeskulptor codeskulptor.set_timeout(20) def gen_all_seque...
#!/usr/bin/env python2.7 -B -tt """ Coding problems involving prime numbers. """ def prime_generator(x): """ Generate all primes less than or equal to x. """ prime = 2 while prime <= x: test = True for mod in xrange(2, prime/2 + 1): if prime % mod == 0: t...
## 进程间通讯 # 进程之间数据是互相隔离的,要先实现进程间的通信(IPC机制), # 需要借助技术实现,比如multiprocessing模块中的 # 队列和管道,这两种方法都可以实现进程间数据传输的,由于队列是管道+锁的方式实现的 # 我们着重研究队列 # 队列: 创建共享的进程队列,Queue是多进程安全的队列,可以使用Queue实现多进程之间的数据传递。 # 队列支持多个人从队列的一端放入数据,同样支持多个人从队列的另一端取数据 ## 基本用法 ## Queue([maxsize]) #创建共享的进程队列,队列底层使用管道和锁定实现。 # 参数: maxsize是队列中允许的最大项数。如果省略此参数,则无...
## 09-02 封装 ## 面向对象的三大特性:封装、继承、多态。 ## 封装就是把数据和功能都整合在一起。还可以严格控制对他们的访问,分两步实现:隐藏于开发接口 ## 隐藏属性 ## python的Class机制采用双下划线开头的方式,将属性隐藏起来(设置成私有的), ## 单这其实仅仅只是一种变形操作,类汇总所有双下划线开头的属性都会在类定义阶段、 ## 检测语法时自动变成"_类名称__属性名"的形式: ## sample 01 class Foo: __N = 0 def __init__(self): self.__x = 10 def __f1(self): ...
## 09-01 面向对象编程 from Student import Student #print(Student.__dict__) stu1 = Student('bobo','男',30) stu2 = Student('jojo','女',28) #stu3 = Student() print(Student) print(stu1.__dict__) print(stu2.__dict__) stu1.choose() print("School name is :",stu1.school) stu1.school = 'aaa' print("School name is :",stu1.school)...
##用python 匿名函数做一个功能 将list内容换行打印出来 ##lambda k:print(k,end=''),(listA) ##print(lambda k:listA[k](listA),end='') ##for l1 in listA: ## print(l1,end='\n') def showlinefeed(obj): print("开始打印....") for o in obj: print(o,end='\n') def unittest(): if __name__ == 'main': listA = list(['a', 'b...
##07-05 学习笔记 ##装饰器 ##—————————————————————————————————— ## 2.1 无参数装饰器的实现 ##如果想为下述函数添加统计其执行时间的功能 import time def index(): time.sleep(3) print('1.Welcome to the index page') return 200 index() #函数原本的执行方式 ##遵循不修改被装饰器对象源代码的原则,我们想到的解决方案可能是这样↓ start_time = time.time() index() stop_time = time.time() print('1...
''' Write a Python program that will prompt for input and then display a pig "saying" whatever text was provided by the user. Place the input you receive from the user inside a speech bubble. Exapand or contract the speech bubble in order to make it fit around the input provided. ''' #Prompt the user for what they wo...
#回溯法 #八皇后问题 def main(n): res=[] queen=[None]*n linep=[None]*n linem=[None]*n def add(num): print(queen) if num==n: queenre=queen res.append(queenre) else: for x in range(0,n): if (x not in queen) and (x+num not in line...
def operaciones_basicas(x, y): suma = x + y resta = x - y producto = x * y return suma, resta, producto num1 = int(input('Digite primer número: ')) num2 = int(input('Digite segundo número: ')) s, r, p = operaciones_basicas(num1, num2) print('La suma de ', num1, ' + ', num2, 'es: ', s) print('La rest...
lista1 = [[1, 'ANA', 3], [1, 56, -12]] lista2 = [[1, 'ANA', 3], [1, 56, -12]] lista3 = [['Carlos', 'Mario', 'Andres', 'Maria', 'Luisa'], [3.2, 2.1, 4.5, 2.2, 4.0]] i = 1 for elem in lista1: print(str(i) + ':\t' + str(elem)) i += 1 largo = len(lista2) for i in range(largo): print(str(i + 1) + ':\...
''' Programa lee secuencia de números, cuantos son pares y cuantos son impares. Se termina cuando ingrese Cero (0) ''' numero = int(input('Ingrese un número y cero (0) para terminar: ')) pares = 0 impares = 0 while numero != 0: if numero % 2 == 0: pares = pares + 1 else: impares = impares + 1...
# import the turtle module so we can use all the neat code it contains import turtle from helper_code import Box, printwin from counters import Score from time import clock # Record start time in seconds t0 = clock() done = False score = Score(0) # Create variables to contain our Box objects a = Box(100,100) b = Box...
# import the turtle module so we can use all the neat code it contains import turtle # Create a variable `tina` that is a Turtle() object. Set shape to 'turtle' tina = turtle.Turtle() tina.shape('turtle') # Create a variable `screen`, a Screen() object, that will handle keyss screen = turtle.Screen() # Define a func...
"""3. Написать программу, которая генерирует в указанных пользователем границах: a. случайное целое число, b. случайное вещественное число, c. случайный символ.""" import random print('Введите границы числового и буквенного диапазона:') low = int(input('Нижняя граница числового диапазона: ')) high = int(input('Верхня...
"""4. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.""" first = input('Введите первую букву: ') second = input('Введите вторую букву: ') print(f'Буква "{first}" в алфавите {ord(first) - 96}-я.\n' f'Буква "{second}" в алфавите {ord(second) - 96...
"""Найти максимальный элемент среди минимальных элементов столбцов квадратной матрицы. Короткое решение со встроенными функциями zip(), max() и min(). Однозначно это решение наиболее эффективное: максимально лаконичное и быстрое в исполнении.""" from random import randint import cProfile def def_matrix(n): matr...
from tkinter import Tk, simpledialog, messagebox if __name__ == '__main__': window = Tk() window.withdraw() # TODO: Look at the AreYouHappy.png image # Use pop-ups to recreate the chart using if and elif statements happy = simpledialog.askstring(title="", prompt="Are you happy?") if hap...
#!/usr/bin/python3 '''Write a function that checks for lowercase character''' def islower(c): '''check to see if letter is lowecase or not''' c = ord(c) if c >= 97 and c <= 122: return(True) return(False)
#!/usr/bin/python3 add = __import__("add_4").add '''program imports function from file''' def addThem(): ''' uses imported fuction to add variables''' a = 1 b = 2 print('{} + {} = {}'.format(a, b, add(a, b))) if __name__ == '__main__': addThem()
#multipliaca os 9 primeiros digitos pelos numeros de 10 a 2 #soma o resultado, multiplicapor 10 e divide por 11 #verifica o resto da divisão - deve ser igual ao primeiro digito verificador #multipliaca os 9 primeiros digitos e o primeiro digito verificado pelos numeros de 11 a 2 #soma o resultado, multiplicapor 10 e d...
__author__ = 'MohanVelaga' import os import sqlite3 from Employee import Employee class DataBase: DBName = "Employee.sqlite" @staticmethod def createTable(): conn = sqlite3.connect(DataBase.DBName) cursor = conn.cursor() cursor.execute("create table Employee (id INTEGER PRIMARY KEY...
#!/usr/local/bin/python2.7 def heapsort(inputs): print "Input Array" print inputs print l = [] for start in range((len(inputs)-2)/2,-1,-1): heapify(inputs, start) print "After Heapifying " print inputs for end in range((len(inputs)-1),0,-1): inputs[end],inputs[0] = inputs[0],inp...
# coding: utf-8 # # Use 'employee_compensation' data set. # # Find out the highest paid departments in each organization group by calculating mean of total compensation for every department. # In[ ]: import pandas as pd import os # In[2]: current_path=os.getcwd() #gives current directory # In[6]: employe...
#Task #You are given a string . #Your task is to find the first occurrence of an alphanumeric character in (read from left to right) that has consecutive repetitions. #Input Format: #A single line of input containing the string . #Output Format: #Print the first occurrence of the repeating character. If there are n...
#Task #You are given a space separated list of numbers. Your task is to print a reversed NumPy array with the element type float. #Input Format #A single line of input containing space separated numbers. #Output Format #Print the reverse NumPy array with type float. #-----------------------------------------------SO...
#You are given an HTML code snippet of n lines. Your task is to detect and print all the HTML tags, attributes and attribute values. #Print the detected items in the following format: #Tag1 #Tag2 #-> Attribute2[0] > Attribute_value2[0] #-> Attribute2[1] > Attribute_value2[1] #-> Attribute2[2] > Attribute_value2[2] #Ta...
#There is an array of integers. There are also disjoint sets, A and B , each containing integers. #You like all the integers in set A and dislike all the integers in set B . Your initial happiness is 0. #For each integer in the array, if i is in A, you add 1 to your happiness. If i is in B, you add -1 to your ha...
#Task #Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers. #You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and ...
from langdetect import detect text = input("Enter any text in any language: ") print("language of this text is : ", detect(text)) # by kshitiz
n = int(input()) map = {} count = 0 for i in range(n): word = input() if word not in map: map[word] = 1 count += 1 else: map[word] += 1 print(count) for key, value in map.items(): print(value, end = " ") #by kshitiz
print("Welcome To This Auto Card Generator :)") import random cards = ["Diamonds", "Spades", "Hearts", "Clubs"] ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"] def pick_a_card(): card = random.choices(cards) rank = random.choices(ranks) return(f"The {rank} of {card}") print(...
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 21:30:24 2019 @author: Anonymousgod """ import turtle turtle.color("red", "blue") turtle.begin_fill() for i in range(9): turtle.forward(250) turtle.left(160) turtle.end_fill() turtle.done
"""Задание: принимаем alert В этой задаче вам нужно написать программу, которая будет выполнять следующий сценарий: Открыть страницу http://suninjuly.github.io/alert_accept.html Нажать на кнопку Принять confirm На новой странице решить капчу для роботов, чтобы получить число с ответом """ import math from selenium imp...
##Written by Steven Faber ##8/29/2018 ##This code will informt the user how to best utilize both car and public transport to arrrive at a destination in the least amount of time for the least amount of money import webbrowser import urllib import time import requests api_key = 'AIzaSyDKG09pG4lwdh5H1zlgCUDTHOUX...
import requests def my_public_ip(): """ Get the public address details. """ map_values = { 'YourFuckingCountryCode': 'Countrycode', 'YourFuckingHostname': 'hostname', 'YourFuckingIPAddress': 'ip address', 'YourFuckingISP': 'isp', 'YourFuckingLocation': 'location'} url = "https://wtfismyip.com/json" r...
numb_user = int(input("Введите номер месяца: ")) seasons_list = ["winter", "spring", "summer", "autumn"] seasons_dir = {1 : "winter", 2 : "spring", 3 : "summer", 4 : "autumn"} if numb_user == 12 or numb_user == 1 or numb_user == 2: print(seasons_dir.get(1)) print(seasons_list[0]) elif 3 <= numb_user <= 5: p...
# Required hash table class # Implemented with nested lists class HashTable: # Initialize the hash table with empty buckets # Use 10 buckets as default def __init__(self, capacity=10): self.root = [] for i in range(capacity): self.root.append([]) # Very basic hash function, ...
import random import time picks = ["Stein", "Schere","Papier"] player_entry = ["Stein", "Schere","Papier"] def computer_pick_print(computer_picks): print("Der Computer wählt "+ (computer_picks)); time.sleep(0.5) def player_loses(): time.sleep(0.2) print("Du verlierst! :(") def player_wins(): time...
fahrenheit = float(input("Enter your temperature in Fahrenheit: ")) celsius = ((5/9) * (fahrenheit - 32)) print("Your temperature in Celcius is", "{0:.2f}".format(celsius))
def Imtdef(): #предупрждение print('вводите целые числа! ') #данные try: w = float(int(input('ваш вес: '))) except ValueError: print('вы ввели не число') try: h = float(int(input('ваш рост (в сантиметрах): '))) except ValueError: print('вы ввели не число') ...
N = int(input()) name_set = set() for i in range(N): s = input() if s not in name_set: name_set.add(s) print(i+1)
def quick_sort(lst): _quick_sort(lst, 0, len(lst) - 1) def _quick_sort(lst, left, right): if left < right: pivot = _partition(lst, left, right) _quick_sort(lst, left, pivot - 1) _quick_sort(lst, pivot + 1, right) def _partition(lst, left, right): if right == -1: right = l...
fruits=['apple','banana','orange'] for fruit in fruits: print(fruit)
import cv2 #opencv for image processing #creating a videocapture object cap = cv2.VideoCapture(0) # 0 indicates primary webcam we can use 1,2,3 depending on number of webcam conencted to our pc #getting the background image while cap.isOpened(): ret, background = cap.read() #simply reading from the web...
import csv import sys from pprint import pprint def main(): ##-- Code below extracts data from csv called puzzle ##-- Brings in data first as a string ##-- Filters unwanted characters out of string inputpuzz = "" with open('puzzle.csv') as f: reader = csv.reader(f) for row in reader: inputpuzz += str(row...
from app import db class Address(db.Model): """ A class to represent an address .... Attributes ---------- addressLine: string house/block of address city: string city name zipCode: string zip-code of address M...
#!/usr/bin/env python # 分片 # 分片包含左值不包含右值 a=[1,2,3,4,5,6,7,8,9] b=(1,2,3,4,5,6,7,8,9) # 迭代 # dict的迭代 d={'a':1, 'b':2, 'c':3} for key in d: print(key) for value in d.values(): print(value) for k,v in d.items(): print(k,":",v) from collections import Iterable from collections import Iterator # isinst...
def solution(A,B): answer = 0 a = sorted(A) b = sorted(B, reverse=True) while a and b: answer += (a.pop() * b.pop()) return answer # 짧고 좋다! def solution(A,B): a = sorted(A) b = sorted(B, reverse=True) return sum(i*j for i, j in zip(a, b))
#The number of lights should be configurable on the command line with a default value of 20. #The set of lights will be made up of a repeating set of colours in a fixed order (e.g red, green, white) #When you run the program, it should turn each light in the set on for 1 second and then turn it off. #The output of the ...
# This file will contain the login function to check if the user has inputted correct email/pw or register them # if they have inputted new identification. # Returns whether or not it was a successful login. (User w/ correct pw or new user registering in) def login(c, conn, email, password): # if the email is in ...
from typing import Dict from itertools import product def sweep_cartesian_product(sweep_params: Dict[str, tuple]) -> Dict[str, tuple]: """ Makes a cartesian product from dictionary values. This is useful for plugging inside the sys_params dict, like: ```python sweep_params = {'a': [0.1, 0.2], 'b':...
import json def file_reader(path): with open(path, "r", encoding="utf-8") as file: json_object = json.load(file) return json_object def json_navigation(json_data): dict_print = "This is dictionary, choose a key: " lst_print = " This is list, choose a index: " while isinstance(json_data,...
rows = range(1,4) cols = range(1,3) # list comprehension (함축, 내포)를 통한 cells list 정의 # [ 표현식 for 항목 in iterable ] cells = [(row, col) for row in rows for col in cols] print(cells) # 언패킹으로 출력 for row, col in cells: print(row, col) # dictionary comprehension 을 활용한 문자열의 알파벳별 개수 세기 # { 키 표현식 : 값 표현식 for 표현식 in iterab...
list1 = [1,2,3] tuple1 = ('a','b','c','d') # zip 함수로 iterable 객체들을 묶어 병렬로 순회할 수 있음. # 이 때 더 짧은쪽에 맞춰짐 for data1, data2 in zip(list1, tuple1): print(data1, data2) # 그 외에도 zip으로 n개의 iterable 타입들을 묶어 list, dict 등으로 만들 수 있음 print(list(zip(list1, tuple1))) print(dict(zip(list1, tuple1))) # zip의 결과는 zip class인데 iterabl...
''' while ~ else 구문 break로 탈출하지 않은 경우 else구문이 실행됨. ''' numbers = [1, 3, 5] while numbers: number = numbers.pop() if number % 2 == 0: print('found even!') break else: print('cannot find even...')
import numpy as np from MLlib.activations import Sigmoid class MeanSquaredError(): """ Calculate Mean Squared Error. """ @staticmethod def loss(X, Y, W): """ Calculate loss by mean square method. PARAMETERS ========== X:ndarray(dtype=float,ndim=1) ...
import pytest from pytest_bdd import given, when, then @pytest.mark.input @given("A user inputs a string from the terminal") def test_get_input(): t_input = input("Please enter the string to be reversed: ") # t_input = "This is a simple test of reversing a string" assert len(t_input) > 0, "get_input funct...
# it's day one i am learning about tkinter to make some GUI application # to start we have to import tkinter its built in python # so you really dont need to install it # lets import it we are goin to import every thing from tkinter from tkinter import * # now we have to create main window object to render # our win...
""" Given an array of n integers(duplicates allowed). Print “Yes” if it is a set of contiguous integers else print “No”. """ def is_contiguous(a): b = [] for elem in a: if not b.__contains__(elem): b.append(elem) a_sum = 0 for j in range(min(a), max(a)+1): a_sum += j b_...
board=['_']*9 won=False turn=0 # To know whose turn it is #Function to Print the Board def print_board(): print(board[0]+'|'+board[1]+'|'+board[2]) print(board[3]+'|'+board[4]+'|'+board[5]) print(board[6]+'|'+board[7]+'|'+board[8]) #Function to Continously check for the Winner def check_w...
"""def refib(n): if n==0 or n==1: return n else: return refib(n-1)+refib(n-2)""" d={} d[0]=0 d[1]=1 def btfib(n): """ *Dictionaries are used for fast access *bottom up approach for dynamic programming *dependencies must be priorly known""" for i in range(2,n...
lines = int(input("Enter lines for pyramid: ")) space = " " star = "* " for i in range(0,lines+1): print((lines+1)*space, end = '') print(i*star) lines = lines - 1
n = int(input("Enter a value for n,Range until the prime numbers are needed: ")) def print_primes(n): prime_nums = [] for num in range(n): if num > 1: for i in range(2, num//2): if (num % i) == 0: break else: prime_nums.append...
def nguyento(n): if n <= 3: return n > 1 elif n % 2 == 0 or n % 3 == 0: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True n = int(input()) print("{}".format("YES" if nguyento(n) else "NO"))
a,b = map(int, input().split()) res = [i for i in range(a + 1, b) if i % 3 == 0] if len(res) == 0: print("NOT FOUND") else: for i in res[::-1]: print(i, end = " ")
def check(a, b): if(len(a) != len(b)): return False elif(sorted(list(a)) == sorted(list(b))): return True else: return False def main(): list1 = ['a', 'b', 'c', 'd'] list2 = ['d', 'b', 'a', 'c'] str1 = 'abcd' str2 = 'cdba' print(check(str1, str2)) result = c...
# Program to reverse a string # String input by User # Python 3 def revString(myString): # Method1 - Slicing. # With indexing we manipulate or return a single item but with Slicin we can manipulate multiple items. # To access parts of sequences like strings, tuples, and lists is known as slicing in Python. ...
def countEleLessThanOrEqual(arr1, n1, arr2, n2): # sorting both the arrays in increasing order sorted_arr2 = sorted(arr2) # sorted_arr1 = sorted(arr1) result = [] # traversing the first array for elem in arr1: l = 0 h = n2 - 1 while(l <= h): mid = int((l + h)...
class Student: def __init__(self, age): self.__age = age @property def age(self): return self.__age @age.setter def age(self, age): self.__age = age s = Student(20) s.age = 10 print(s.age) # 单例模式 class Singleton: __instance = None def __new__(cls, *args, **kwar...
import tkinter from tkinter import messagebox top = tkinter.Tk() def helloCallBack(): messagebox.showinfo("Hello Python", "Hello World") B = tkinter.Button(top, text="Hello", command=helloCallBack) B.pack() top.mainloop()
# -*- coding: utf-8 -*- """ Introduction to Web Science Assignment 3 Question 2 Team : golf Script description : This script declares a 'Sender' class which will be used as a client """ # modules import socket """ the Sender class will play the role of a client object """ class Sender(): # nothing special t...
# -*- coding: utf-8 -*- """ Introduction to Web Science Assignment 2 Question 4 Team : golf Script description : This script creates a simple TCP server listening to a client """ # modules import socket #we create a connection-oriented sockets (stream socket) that uses TCP tcp_server_socket = socket.socket(socket...
""" Introduction to Web Science Assignment 8 Team : golf """ import pandas as pd import re #used for some text cleaning from collections import Counter import math import time # might need to replace by timeit store = pd.HDFStore('store2.h5') df1=store['df1'] df2=store['df2'] # number of documents or articles nbr_docs...
import unittest from game import * class TestGame(unittest.TestCase): def test_start(self): game = Game('oleg') self.assertEqual(game.state, Game.NOTREADY) game.join('max') self.assertEqual(game.state, Game.READY) self.assertIn('oleg', game.players) self.assertIn(...
from tkinter import * def btn(numbers): global operator operator = operator + str(numbers) txt_input.set(operator) def Clear(): global operator operator='' txt_input.set('') Display.insert(0,'Start Calculating...') #def Equal(): # global operator # sumu = float(eval(o...
import turtle as tu COLOR_PICK = ['red','green','yellow','blue','orange','violet','gray', 'purple','pink', 'darkblue','darkgreen','darkorange','darkred','darkgray'] def move(obj, pos_x=0, pos_y=0): obj.penup() obj.setx(pos_x) obj.sety(pos_y) obj.pendown() def go(obj, go, angle=0): """ go=f...
#! python import os import sys import datetime """ file-docs : OPEN A RESTAURANT : Making Order System (1) to Show MENU_PAN = MENU_PAN (changeable) (2) to Input order = by Item index & quantity (3) to Calculate the Bills = Including (Tax= 6.5%, Tip= 10%) * Release Note : correct sorting version - Dict can n...
""" # Youtube : https://www.youtube.com/watch?v=htXz33hXHek # # py3.6 turtle documentation # : https://docs.python.org/3.6/library/tu.html#module-turtle """ import time import math import random as rnd import turtle as tu tu.speed(0) tu.colormode(255) tu.width(3) def set_random_pencolor(obj): """ change pencolo...
import random def get_secret_num_digit(num_digits=10): """ Return certain digits of number_str, num_digits = less than 10 digits Returns a string that is numDigits long, made up of unique random digits. """ numbers = list(range(10)) # print('neated numbers=',numbers) random.shuffle(numbers) ...
import Adafruit_PCA9685 import smbus import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) # to use Raspberry Pi board pin numbers GPIO.setup(11,GPIO.OUT) # to set board pin 11 as output GPIO.setup(13,GPIO.OUT) # to set board pin 13 as output GPIO.setwarnings(False) pwm = Adafruit_PCA9685.PCA9685() pwm.set_...
''' This file contains the Character class only. ''' class Character: ''' This class is used to initialize the player's position at the beginning of the game. It also checks if the player can move or not regarding his position in the labyrinth. ''' def __init__(self, level_structure):...
from sklearn.decomposition import PCA import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import normalize from sklearn.preprocessing import StandardScaler """ The function gets a data set The function returns the data after PCA in 2 dimensions """ ...
print('Hello, I\'m Ahammed') print("Hello, I'm Ahammed Al Mostofa") print("This is \\ backslash") print("This is double backslash \\\\") print('This is line A\nThis is line B') print('This is space\t...') # # This is commemt print('output : Line A \\n Line B') print('output: \\" \\\'I') # Exercise or practise # *******...
print("") print("This program compares 2 numbers and gives comparison equation") print("") num1 = int(input("Enter the first number you want to compare: ")) num2 = int(input("Enter the second number you want to compare: ")) print("Choose One of the Comparison Operators: > , < , =, !=") oper = input("Enter the com...
print("This program is calculates the area of a triangle using base and height.") base = float(input("What is the base of your triangle? Please enter here and no letters: ")) height = float(input("What is the height of your triangle. Please enter here and no letters: ")) unit = input("What unit do you want to use fo...