text
stringlengths
37
1.41M
import re txt = list("abcdefghijklmnopqrstuvwxyz") cip = list("zyxwvutsrqponmlkjihgfedcba") def encode(plain_text: str) -> str: output = "" for i in re.sub("[^0-9a-zA-Z]", "", plain_text.lower()): if i.isdigit(): output += i else: index = txt.index(i) outpu...
''' Spillet ble i første omgang laget for å kunne kjøre på et GUI. Det er derfor ikke implementert funksjoner som kan ta input fra brukeren for å kunne endre tilstanden i spillet. Det er kun opprettet et testklasse for å se at logikken i spillet fungerer som den skal. Her ville man bare ha laget funksj...
#!/usr/bin/python3 # encoding: utf-8 # @Time : 2020/2/21 11:28 # @author : zza # @Email : 740713651@qq.com # @File : 动态修改.py import types class A: def __init__(self): self.a = 1 def p(self, num): print("A", self.a) print("num", num) print("*" * 20) def p(num): ...
def gen_primes(a, b): """ Copied from stackoverflow Generate an infinite sequence of prime numbers. """ D = {} q = a result = [] while q <= b: if q not in D: result.append(q) D[q * q] = [q] else: for p in D[q]: D.setdef...
# petla while, for # lista = ["a", "b", "d", "e", "f", "g", "h", "i", "j"] # # for litera in lista: # print(litera) # if litera == "e": # print("to jest e!") # range genereuje liste na podstawie liczby podanej # for i in range(0, 51,2): # print(i) # _______________________________________________...
""""The variance allows us to see how widespread the grades were from the average. the grades varied against the average. This is called computing the variance. A very large variance means that the students' grades were all over the place, while a small variance (relatively close to the average) means that the majo...
BagOfHolding={'rope':1, 'tourch':6 , 'gold coin':42, 'dagger':1, 'arrow': 12} dragonLoot=['gold coin','gold coin', 'dagger', 'gold coin', 'ruby'] #addToInventory(inventory, additem) def displayInventory(BagOfHolding): print ('Your inventory includes the following:' ) item=0 for k, v in BagOfHolding.items()...
import random messages = ('It is certain', 'It is decidedly so', 'Yes definitely','Reply hazy try again', 'ask again later','Concentrate and ask again', 'NO!', 'Outlook is not so good', 'Very doubtful') print(messages[random.randint(0,len(messages)-1)]) #produces random number to use for index. The number will be dete...
print ("Pick a number:") spam=input() if spam == 0: print ("Howdey") if spam == 2: print("greetings") else: print("spam")
#! /usr/bin/python3 # # Strip superfluous commas and spaces from register file # Libreoffice adds lots of commas to pad out to the number of columns import sys inputfile = open(sys.argv[1], "r") while True: line = inputfile.readline() if not line: break output_line = line.rstrip().rstrip(',') p...
from enum import Enum class TokenType(Enum): # Arithmetic Operators PLUS = '+' MINUS = '-' MUL = '*' FLOAT_DIV = '/' POWER = '^' MODULO = '%' # Relational Operators GREATER_THAN = '>' LESS_THAN = '<' EQUALITY = '==' ...
import random # Get a noun. def get_nouns(num_nouns): nouns_list = [] for i in range(num_nouns): noun = input("Type a noun: ") nouns_list.append(noun) return nouns_list def get_verbs(num_verbs): verbs_list = [] for v in range(num_verbs): verb = input("give me a verb: ") ...
#!/usr/bin/env python3 # Created by Brian Musembi # Created on May 2021 # This program calculates the factorial of a user input def main(): # this function will calculate the factorial of a user input print("This program calculates the factorial of the given user input.") # loop counter variable lo...
# The file contains the edges of a directed graph. Vertices are labeled as positive integers from 1 to 875714. Every # row indicates an edge, the vertex label in first column is the tail and the vertex label in second column is the # head (recall the graph is directed, and the edges are directed from the first column v...
import numpy as np # Create vectors v1 = np.array([1,2]) v2 = np.array([0,5]) # Vector arithmetic v1 + v2 v1 * v2 # element-wise product np.dot(v1, v2) # dot product 2.0 * v1 print "v1 = " + repr(v1) print "v2 = " + repr(v2) print "v1 + v2 = " + repr(v1 + v2) print "v1 * v2 = " + repr(v1 * v2) # element-wise p...
"""Get the best option for buying all product in one place.""" # Python modules imports from operator import getitem # Comparator functions imports from .basics import get_location def get_products_length(df, market): """Get the number of products that a supermarket offers.""" length = 0 for i in rang...
# Program of simple calculaton; print("+ for addition") print("- for subtraction") print("* for multiplication") print("/ for division") choice = input("enter choice : ") num_1 = float(input("enter the num_1= ")) num_2 = float(input("enter the num_2= ")) if choice == "+": addition = num_1 + num...
''' Help Text: Before Running the script please read the help text below To run the script use the command: python move_and_hash.py --scramble Please make sure the directory structure is the same as it is. Do not change the directory structure or move files from one place to another. The Scripts starts below... ''' ...
#!/usr/bin/env python # coding: utf-8 from unittest import TestCase from eight_puzzle import Board, distance class TestBoard(TestCase): def test_extend(self): expected = [Board([1, 0, 2, 3, 4, 5, 6, 7, 8]), Board([3, 1, 2, 0, 4, 5, 6, 7, 8])] board = Board(range(9)) re...
# Author: Alan Tort # Date: 7/3/2021 # Description: Project 4b # A function named fib that takes a positive integer parameter and returns the number at that position of the # Fibonacci sequence def fib(positive_integer): """Fib takes a positive integer parameter and returns the number at the position of the...
listePieces = [ ]; # [ Valeur Piece , Quantité dans machine ] listePieces.append( [ 0.5, 6 ] ); listePieces.append( [ 0.05, 2 ] ); listePieces.append( [ 1.0, 1] ); listePieces.append( [ 0.01, 2 ] ); listePieces.append( [ 2.0, 3 ] ); listePieces.append( [ 0.1, 2 ] ); listePieces.append( [ 0.02, 0 ] ); listePieces...
""" File: bank.py This module defines the Bank class. """ import pickle import random from csc131.ch09.savings_account import SavingsAccount class Bank: """This class represents a bank as a collection of savnings accounts. An optional file name is also associated with the bank, to allow transfer of accoun...
def listSearch(L, x): """ Searches through a list L for the element x""" for item in L: if item == x: return True # We found it, so return True return False # Item not found
# ---------Bài 10: Viết hàm đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n cho trước. # Ví dụ: Hàm trả về 4 nếu n là 19922610 (do n có 4 số lẻ là 1, 9, 9, 1) # --------------------------------------------------------------- print("Đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n c...
import math n = int(input("Nhập bán kính : ")) def DienTichHinhTron(r): s=math.pi*r*r return s print(f"Dien tich hinh trong co ban kinh {n}: {DienTichHinhTron(n)}")
import sqlite3 import pandas as pd import datetime def fire_count(df, interest_date, day_range=7): """ Parameters: df: dataframe of interest. dataframe comes from geo table in fire.db and must already be parsed for the area of interest interest_date: date to look forward from ...
""" Course: CS 2302 [MW 1:30-2:50] Author: Kimberly Morales Assignment: Lab 8 Instructor: Olac Fuentes TA(s): Anindita Nath , Maliheh Zargaran Date: 5/9/2019 Date of last modification: 5/9/2019 Purpose of program: To implement interesting algorithms to solve problems that often require a more efficient a...
a = int(input("First Term: ")) b = int(input("Second Term: ")) c = int(input("Third Term: ")) for factors in range (1, a): factors = a % factor == 0 if factors == True: print factor else print print ('No integer factors')
import calendar from datetime import timedelta, date def gen_calendar(year, month): month_first = date(year, month, 1) calendar_first = month_first - timedelta(days=month_first.weekday()) calendar_dates = [] for i in range(6): week_dates = [] for j in range(7): week_date =...
from random import randint comparisons = 0 def quickSort(arr): quickSortHelper(arr, 0, len(arr) - 1) def quickSortHelper(arr, leftIndex, rightIndex): global comparisons if leftIndex < rightIndex: comparisons += rightIndex - leftIndex print(comparisons, rightIndex, leftIndex, arr) ...
TERMINAL = 'TERMINAL' FUNCTION = 'FUNCTION' class Node: def __init__(self, data, type: str): self.children = [Node] self.data = data self.type = type def PrintTree(self): print(self.data) for child in self.children: child.PrintTree() def insert(self, ...
positivos=0 cero=0 negativos=0 for x in range(0,10): x=int(input("ingrese un numero ")) if x==0: cero=cero + 1 else: if x>0: positivos= positivos + 1 else: negativos= negativos + 1 print("la cantidad de ceros es: " , ce...
## Exercise 3: # You are the parent of 3 teenage children, and you have no idea what they are saying in their texts. You decided to write a program to translate the abbreviations they use in their texts to plain english. You will write a program that prompts the user to enter a text message, translate the text message...
#Note:state is always a 2d list #this method find all unassigned cells in the initial state and return a list containing coordinates(e.g (3,4)) def getUnassigned(state): result=[] for i in range(len(state)): for j in range(len(state[0])): if not isinstance(state[i][j],int): ...
# Write a function is_even that will return true if the passed-in number is even. # YOUR CODE HERE def is_even(x): return True if x%2 == 0 else False while True: # Read a number from the keyboard num = input("Enter a number: ") num = int(num) # Print out "Even!" if the number is even. Otherwise print "Od...
#_*_ coding:utf-8 _*_ """ 线性回归算法: 寻找一条直线, 最大程度的 "拟合" 样本特征和样本输出标记之间的关系 分类问题的横纵坐标都是样本特征, 而回归问题横轴是样本特征, 纵轴是样本的 label(比如房屋的面积和价格). 线性回归算法的评测: 如果使用均方误差 MSE 的话, 量纲上可能会有问题, 所以, 一般使用 1. 根均方误差: RMSE (Root Mean Squared Error) sqrt(MSE) 2. 平均绝对误差: MAE(Mean Absolute Error) 1/m sum_{1}^{m} |yi - y...
''' Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (HH:MM:SS) HH = hours, padded to 2 digits, range: 00 - 99 MM = minutes, padded to 2 digits, range: 00 - 59 SS = seconds, padded to 2 digits, range: 00 - 59 ''' def make_readable(seconds): SS ...
import json from collections import defaultdict import config import requests import pandas as pd from pandas import DataFrame # Storing the API Keys API_KEY = config.api_key class NYTimes: """ This program uses the NY Times API to check relevant articles that for a specifc time period on a specific top...
# Crear un codigo que calcule las soluciones de la ecuacion cuadratica. # ax2+bx+c # x2+b+1 #x1= -b + b2-4.a.c / 2a #primero el descriminante #x2= -b-b2 -4.a.c/2a #importar paquete math import math a = float(input('favor ingresar a')) b = float(input('favor ingresar b')) c = float(input('favor ing...
""" After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you. The tropical island has its own currency and is entirely cash-only. The gold coins used there have a little picture of a starfish; the locals just call th...
class Stack: def __init__(self): self.container = [] def push(self, data): self.container.append(data) def pop(self): return self.container.pop() def stackSize(self): return len(self.container) def isEmpty(self): return self.container == [] def peek(s...
class Class03: """A Sample Calss01""" def __init__(self): print("Created object for Class03...!!!") class Class04: """A Sample Calss02""" def __init__(self): print("Created object for Class04...!!!") def main(): """ To give access to this code from outside of this module""" Cl...
def dateTwoDaysLater(month, day, year): M1 = {4, 6, 9, 11} M2 = {1, 3, 5, 7, 8, 10} M3 = {12} M4 = {2} D1 = set(list(range(1, 27))) D2 = {27} D3 = {28} D4 = {29} D5 = {30} D6 = {31} state = 0 #state表示是否是闰年,0表示不是,1表示是闰年 if (year % 4 == 0 and year % 100 != 0) or year % 4...
# 1- (started, end, step calculate) # 2- we can do for inside for # 3- we can do if inside for for x in range(1, 10, 2): print(x) class open_doors(): def __init__(self, status, open, closed): self.open_doors = open_doors self.status = status self.open = open ...
# Binary Search def binary_search(data, elem): low = 0 high = len(data) - 1 while low <= high: middle = (low + high) // 2 if data[middle] == elem: print("Your desired element ", elem, "is at position ", middle) return middle elif data[middle] > elem: ...
#New Adventure style game. #Trapped at the zoo '''Player gets trapped at zoo after dark. Various scenes follow where player: travels to different areas, enters different enclosures, and meets new animal friends. Animals can: talk to player, help player, or harm player. There will be challenges...
#Class-based programming quiz. Importing quiz functions import random import ex27v2 oop_phrases = { #word_drills = { 'class': 'Tell Python to make a new type of thing.', 'object': 'Two meanings: the most basic type of thing, and any instance of some thing.', 'instance': 'What you get when you tell Python to create a...
# dictionary of recognized words # words are matched with their type and sent to parser.py # where they become sentences that the app can understand def scan(userinput): # create list or dictionary of parts of speech, maybe expected # words for input vocab = {'north': 'direction', 'south': 'direction', 'ea...
import os import datetime import PIL.Image ASCII_chars = ['@', '#', 'S', '%', '*', '+', ';', ':', ',', '.', '`'] def resize_image(image, new_height=90): width, height = image.size ratio = width / height * 1.5 new_width = int(new_height * ratio) resized_image = image.resize((new_width, new_height)) ...
from decimal import Decimal a = 4.2 b = 2.1 print(a + b) print((a+b) == 6.3) a = Decimal('4.2') b = Decimal('2.1') print(a + b)
import numpy as np x = [1, 2, 3, 4] y = [5, 6, 7, 8] print(x * 2) ax = np.array([1, 2, 3, 4]) ay = np.array([5, 6, 7, 8]) print(ax * 2)
x = 1234.5678 print(format(x, '0.2f')) print(format(x, '>10.1f')) print(format(x, ',')) """ % operation is less powerful than modern format() """
list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9, 10] data = zip(list1, list2) print(data) data = sorted(data) print(data) #parallel sorting list list1, list2 = map(lambda t: list(t), zip(*data)) print(list1) print(list2)
# List basic empty = [] empty = list() sodas = ["Coke", "Pepsi", "Dr. Pepper"] print(len(sodas)) print("fast" in "breakfast") meals = ["breakfast", "lunch", "dinner"] print("lunch" in meals) print("lunch" not in meals) test_scores = [99.0, 35.0, 23.5] print(99.0 in test_scores) print("organic"[5]) w...
rmb_str_valur = input('请输入人民币金额:') print('您输入的金额为:', rmb_str_valur) rmb_value = eval(rmb_str_valur) usd_vs_rmb = 6.77 usd_value=rmb_value / usd_vs_rmb print('美元金额为:', usd_value) a1 = 34 a2=str(34) print(a1+eval(a2))
USD_VS_RMB = 6.77 mmb_str_valur = input('请输入带符号的金额:') print('您输入的金额为:', mmb_str_valur) unit = mmb_str_valur[-3:] input_value = mmb_str_valur[0:-3] input_value = eval(input_value) print(unit) print(input_value) if unit == 'RMB': usd_value = input_value / USD_VS_RMB print("美元金额为 : ",usd_value) elif unit == 'USD':...
# Reinforcement Learning Watch this video: <iframe width="560" height="315" src="https://www.youtube.com/embed/kopoLzvh5jY" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <hr> :::{admonition} Assignments: :class: hint 1. *In...
from simplecrypt import encrypt, decrypt import base64 import random from Account import * import sys def welcome(): print("Welcome to Cardiff ATM!") print("1. Login into your account") print("2. Create new account ") print("3. Exit") answer = input("- ") print() try: if int(answer) == 1: loginAccount() ...
name = "marton zeisler" print("Welcome " + name.title()) print(name.upper()) lang = " python " print(lang.lstrip() + "!") print(lang.strip() + "!") # comment print(str(3**2)+".")
def formatYou(first, last): return (first + " " + last).title() print(formatYou("marton", "zeisler")) def squareList(list): del list[0] list = [each**2 for each in list] return list myList = [1,2,3,4,5] myList = squareList(myList[:]) # passing list by print(myList)
# user input and while loop age = int(input("Enter your name: ")) if age >= 18: print("You can drink") else: print("You cannot drink") while True: age += 1 print("You're " + str(age)) if age < 18: print("You still can't drink buddy") else: print("yay go get drunk quick") break
#nonlocal,global关键字 def outer(): b=10 def inner(): nonlocal b #申明外部函数的局部变量 print("inner b:",b) b=20 global a #申明全局变量 a=1000 inner() print("outer b:",b) outer() print("outer b:",a)
#测试选择结构的嵌套 score = int(input("请输入一个在0-100之间的数字:")) grade = "" if score>100 or score<0: score = int(input("输入有误!请重新输入一个在0-100之间的数字")) else: if score >= 90: grade = "A" elif score >=80: grade ="B" elif score>=70: grade ="C" elif score >=60: grade = "D" else: ...
r1={"name":"高一","age":"18","salary":"3000","city":"北京"} r2={"name":"高二","age":"19","salary":"4000","city":"上海"} r3={"name":"高三","age":"20","salary":"5000","city":"广州"} tb=[r1,r2,r3] #获高小二的薪资 print(tb[1].get("salary")) #获取表中所有人的薪资 for i in range(len(tb)):#i--->0 1 2 print(tb[i].get("salary")) #打印所有的数据 for i in range...
#测试for循环 for x in (20,30,40): print (x*3) for y in "abcdef": print(y) #遍历字典 d={"name":"SKY","age":"18","address":"陕西西安"} for x in d: print (x) for x in d.keys(): print(x) for x in d.values(): print(x) for x in d.items(): print(x) #range对象 for i in range(10): print (i) for j in range(3,...
class ShortException(Exception): def __init__(self, word, length): Exception.__init__(self) self.word = word self.length = length try: text = input('Введите что нибудь:') if len(text) < 3: raise ShortException(len(text), 3) except EOFError: print('EOF') except ShortException as ex: print('ShortException: ...
zoo = ('питон', 'слон', 'пингвин') print('Количество животных в зоопарке:', len(zoo)) new_zoo = ('обезьяна', 'крокодил', zoo) print('количество клеток в зоопаре:', len(new_zoo)) print('все животные в новом зоопарке:', new_zoo) print('животные привезенные из старого зоопарка:', new_zoo[2]) print('последнее животное прив...
#this program says hello and asks for my name and age and my age in 5 years time #intro print('Hello Dude!') #asks my name print('What is your name?') myName = input() print('Nice to meet you, ' + myName) print('The length of your name is: ') print(len(myName)) #asks my age print('what is your age?') myAge = input()...
########## CALCULATOR ########### print("######CALCULATOR######") ##operators = ['+', '-', '/', '*', '**', '%'] # Create a list of functions you want to use for your calculator def add_(x,y): return(x+y) def sub_(x,y): return(x-y) def mult_(x,y): return(x*y) def div_(x,y): return(x/y) def pow_(x,y): ...
# Priority (Non-Pre-emptive) CPU SCheduling algorithm # for processes with same arrival time (Arrival Time = 0). def waitingTime(process, wt): n=len(process) wt[0]=0 for i in range(1, n): wt[i]=process[i-1][2]+wt[i-1] def turnAroundtime(process, wt, tat): for i in range(len(process)): tat[i]=process[i][2]+wt[...
""" Metacharacters are what make regular expressions more powerful than normal string methods. They allow you to create regular expressions to represent concepts like "one or more repetitions of a vowel". The existence of metacharacters poses a problem if you want to create a regular expression (or regex) that matche...
The module itertools is a standard library that contains several functions that are useful in functional programming. One type of function it produces is infinite iterators. The function count counts up infinitely from a value. The function cycle infinitely iterates through an iterable (for instance a list or string). ...
#1 To find the maximum or minimum of some numbers or a list, you can use max or min. print(min(0, -2, 3, 15,78)) # -2 print(max(0, -2, 3, 15,78)) # 78 #2 To find the distance of a number from zero (its absolute value), use abs. print(abs(0, -2, 3, 15,78)) # TypeError: abs() takes exactly one argument (5 given) ...
# 1 temperature = 21 if temperature > 21: print("It's a warm day") # False elif temperature < 21: print("It's a cold day") # False else: print("It's a lovely day") # Will print -> It's a lovely day #2 price = 1000000 salary = 120000 if price / salary > 8: print("We can give you credit in 10% per yea...
#1 append() numbers = [5, 2, 1, 7, 4] numbers.append(13) print(numbers) # [5, 2, 1, 7, 4, 13] #2 insert() numbers = [5, 2, 1, 7, 4] numbers.insert(2, 10) print(numbers) # [5, 2, 10, 1, 7, 4] # remove() numbers = [5, 2, 1, 7, 4] numbers.remove(5) print(numbers) # [2, 1, 7, 4] # clear() numbers = [5, 2, 1, 7...
#1 customer = { "name": "Hayk Ekizyan", "age": 30, "is_verified": True } print(customer["name"]) # Hayk Ekizyan print(customer.get("name")) # Hayk Ekizyan customer["birthdate"] = "Dec 7 1989" print(customer["birthdate"]) # Dec 7 1989 #2 When the key does n...
from random import sample def dfs_generator(self, v:int, visited:list, road_used:list, parent:int): ''' Recursive Randomized Depth First Search Algorithm with Backtracking Parameters: self (Maze): maze class v (int): current vertex visited (list): list of vis...
#!/usr/bin/env python3 import sys try: from math import gcd except Exception: from fractions import gcd YES = "Yes" # type: str NO = "No" # type: str def solve(N: int): return NO if bool(N % (sum([int(v) for v in str(N)]))) else YES def main(): def iterate_tokens(): for line in sys.stdin: ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import random def merge_sort( data ): l = len( data ) if l <= 1: return data left_data = merge_sort( data[:(l//2)] ) right_data = merge_sort( data[(l//2):] ) res = [] li = 0 ri = 0 while left_data[li:] and right_data[ri:]: ...
import os, sys, re, math class StreetParking: # int freeParks(String street) def freeParks(self, street): ok = 0 for i in range( len( street ) ): if 'B' in street[ i : min( i + 3, len( street ) ) ]: continue if 'D' == street[i]: continue if 'S' in street[ max( i - 1 , 0 ) : min( i + 2,...
#!/usr/bin/env python # -*- coding:utf-8 -*- import random import sys def heap_sort( data ): length = len( data ) heap = [] for d in data: heap.append( d ) l = len( heap ) - 1 while True: if l == 0: break parent = ( l - 1 ) // 2 ...
#!/usr/bin/env python3 import sys from math import * from itertools import * from collections import * from functools import * try: from math import gcd except Exception: from fractions import gcd def solve(x: "List[int]", y: "List[int]"): d = (x[1] - x[0], y[1] - y[0]) x2 = x[1] - d[1] y2 = y[1]...
#!/usr/bin/env python # -*- coding:utf-8 -*- import collections import heapq import sys def find_dijkstra( g, src ): min_cost = {} node_heap = [] heapq.heapify( node_heap ) heapq.heappush( node_heap, ( 0, src ) ) while node_heap: cost,node = heapq.heappop( node_heap ) if node in m...
#!/usr/bin/env python # -*- coding:utf-8 -*- import itertools def is_prime( vv ): i = 2; while i * i <= vv: if vv % i == 0: return False i += 1 return True def main(): max_prime = 0 for i in range( 9, 0, -1 ): for v in itertools.permutations( '123456789'[:i], ...
class Node: def __init__(self, value, next): self.value = value self.next = next class LinkedList: def __init__(self): self._head = None self.count = 0 def insert(self, value, index=None): if self._head is None: self._head = Node(value, None) el...
#!/usr/bin/env python # -*- coding:utf-8 -*- def binary_search( values, target ): left = 0 right = len( values ) while left < right: mid = ( left + right ) // 2 if target == values[ mid ]: return True elif values[ mid ] < target: left = mid + 1 else...
#!/usr/bin/env python import math import random def isPrime( q, k=50 ): q = abs( q ) if q == 2: return True if q < 2 or q & 1 == 0 : return False d = ( q - 1 ) >> 1 while d & 1 == 0: d >>= 1 ass = [ x for x in [ 2, 7, 61] if x < q ] for a in ass: #a = ran...
#!/usr/bin/env python # -*- cofing:utf-8 -*- import math def fibo( n ): golden_ratio = ( 1 + math.sqrt( 5 ) ) / 2 return int( math.floor( math.pow( golden_ratio , n ) / math.sqrt( 5 ) + 0.5 ) ) def digits( n ): return len( str( n ) ) def main(): val0 = fibo( 1100 ) val1 = fibo( 1101 ) index = 1101 while( digi...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from .money import Money class Bank: def __init__(self): self.rates = {} def reduce(self, source, to): return source.reduce(self, to) def addRate(self, original, to, rate): self.rates[(original, to)] = rate def rate(self, ori...
import timeit print('#'*67) print(""" Fibonacci programına hoşgeldiniz! | Aşağıda yapmak istediğiniz işlemin numarasını giriniz. | | Yazdığınız sayıya kadar olan fibonacci sonuçları = 1 | | Belirli bir adımdaki fibonacci sayısı = 2 | | Yazdığınız sayıya kadar...
while True: num = float(input("Enter a number: ")) if num.is_integer(): if num % 2 == 0: print("Even") else: print("Odd") for x in range(0,21,2): print(x+int(num),end=' ') break else: print("Number is not a whole number ")
import matplotlib.pyplot as plt def draw_graph(x, y): plt.plot(x, y, marker='x') plt.xlabel("Distance in metres") plt.ylabel("Force in Newton") plt.title("Plot of gravitational force against distance") plt.show() def gen_fr(m1 = 1000, m2 = 1000): r = list(range(100, 1001, 50)) F = [] ...
import sympy print("McLaurin expansion of sin(x)") x = sympy.Symbol('x') def series(x): val = int(input("Enter number of terms: ")) series = x for i in range(1, val + 1): if i % 2 == 1: series -= x ** (i*2 + 1)/ sympy.factorial(i*2 + 1) else: series += x ** (i * 2...
import argparse from cv2_tools.Management import ManagerCV2 from cv2_tools.Selection import SelectorCV2 import cv2 ''' Check first ManagerCV2 examples, here I assume that you know how it works. ''' vertex = [] def mouse_drawing(event, x, y, flags, params): global vertex if event == cv2.EVENT_LBUTTONDO...
# MIT License # Copyright (c) 2019 Fernando Perez import cv2 from cv2_tools.Utils import * class SelectorCV2(): """ SelectorCV2 helps to select information in frames. This is the original idea of the library, being capable to select multiple zones with enough intelligence to decide how to show as much i...
import os import csv # Import reference data file - assuming residing in same directory bank_csv = 'budget_data.csv' with open(bank_csv, 'r') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') # Initialize variables to proper type after reading as strings header = next(csvfile) firstStr = ne...
import numpy as np "################ Prime Stuff ######################" prime_list = [2, 3, 5] "list of primes" def prime_list_func(upper_limit): """ with sieve of atkin :param upper_limit: :return: """ start_limit = prime_list[-1] + 2 upper_limit = int(upper_limit) + 1 candidates =...
list1 = {1:[[1,2,3,4],[100,100,100],[200,200,200]]} # values = set(map(lambda x:x[1], list1)) newlist = [[y[1] for y in list1 if y[1]==x] for x in list1] print newlist
# -*- coding: utf-8 -*- """ Created on Mon Jul 20 23:02:51 2020 @author: Oussama """ #Question 7 #Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose valu...
""" See https://algorist.com/problems/Set_Packing.html The data are represented by a set of subsets S1,...,Sm of the universal set U={1,...,n}. The problem is to find the largest number of mutually disjoint subsets from S? Examples of Execution: python3 SetPacking.py -data=Subsets_example.json """ from pycsp3 impo...