text
stringlengths
37
1.41M
# Accepting input from the screen my_name = 'Aparna' your_name = input('Enter your name: ') print(f'Hello, {your_name}') num1 = input('Enter first number: ') num2 = input('Enter second number: ') print('Numbers entered are: ', num1,num2) print(eval(num1) +eval( num2)) # your_age = input('Please enter your age: '...
# Python Object Oriented Programming # A Class will have attributes and methods # A class is defines so that the data and it's associated actions(functions) can be combined into a single entity # This cannot be done in a dictionary class Employee: def __init__(self, first, last, pay): # Here self is the instanc...
# Regular methods automatically takes the instance as the 1st parameter # Class methods takes the class as the 1st parameter class Employee: num_of_emp = 0 # This class variable is to maintain the total employee count raise_amount = 1.04 # Class Variable def __init__(self, first, last, pay): # Here s...
# def hello_func(greeting, name='Abhi'): # # pass # to tell that we dont want to do anything in the function # # return '{}, {} Function!'.format(greeting, name) # # **** OR ****** # return f'{greeting}, {name} Function!' # # for x in range(2): # # print (hello_func().upper()) # # # print (hell...
# List slicing is mainly used to slice off from a list or create a new list friends = ['Ann', 'Jasu', 'Abhi', 'Teena', 'Jacob'] # forward index # ['Ann', 'Jasu', 'Abhi', 'Teena', 'Jacob'] # 0 1 2 3 4 # Reverse index # ['Ann', 'Jasu', 'Abhi', 'Teena', 'Jacob'] # -5 -4 -3 ...
import sys # Convert integer into hex string format for output def dec_to_hex(x): string = "" hex_num = hex(int(x)) if hex_num[0] == "-": string += "-" string += hex_num.split('x')[-1] return string.upper() # Find the sum of the given array of lengths of binary numbers and return as int # ...
#!/usr/bin/env python3 """ Main python script for solving spring-mass systems. """ __author__ = "Alex Witt <awitt2399@utexas.edu>" import argparse import sys from typing import List import numpy as np _GRAVITY = 9.80665 # m / s^2 def print_system( num_springs: int, num_masses: int, fix_top: bool, fix_bottom...
import this def myFunction(): pass def stars(): d=0 for d in range (1,5): print ("*"*4) stars() """ def stars2(): to_print = 1 going_down = False for i in range (0,7): for j in range(0, to_print): print("*", end="") print("") if to_print ==4: going_down = True if going_down: to_print -...
story = "once upon a time there was a youtuber named Sarthak who uploaded python course with notes Sarthak" # String Functions print(len(story)) print(story.endswith("Sarthak")) print(story.count("a")) print(story.capitalize()) print(story.find("was")) print(story.replace("Sarthak", "Sarthak_Thukral"))
import math def solution(left, right): answer = 0 for i in range(left,right+1,1): if(math.sqrt(i) == int(math.sqrt(i))): answer -= i else: answer += i return answer
def solution(phone_number): answer = '' phone_number = list(phone_number) answer = phone_number a = len(phone_number) for i in range(0,a-4): answer[i] = '*' answer = ''.join(answer) return answer
cache={} def is_lychrel(n,iter=0): if n in cache: return cache[n] if n<10: cache[n]=False return False if iter>53: cache[n]=False return False bb="" for char in reversed(str(n)): bb+=char bb=int(bb) aa=n+bb if is_palindrome(aa): ...
primes=[2,3] def is_prime(k): for prime in primes: if k%prime==0: return False return True for x in xrange(5,100000000): if is_prime(x): primes.append(x) if len(primes)>10000: break print len(primes),primes[-1]
class Friends: M = [[1, 1, 0], [1, 1, 0], [0, 0, 1]] def findCircleNum( M): """ :type M: List[List[int]] :rtype: int """ parents = [-1] * len(M) for i in range(len(M)): for j in range(len(M)): if M[i][j] == 1 and i !=...
def mystery(x,y): if(x>y): x=x-y if(x<y): y=y-x return x, y if __name__ == '__main__': x = 2437 y = 875 while(x!=y): x, y = mystery(x, y) print(x,y)
class Node: def __init__(self,data): self.data=data self.next=None class circularLinkList: def __init__(self): self.head=None #function to insert a node def push(self,data): node1=Node(data) temp=self.head node1.next=self.head if self.head is not Non...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def maxDepth( root: TreeNode) -> int: if root is None: return 0 return max(maxDepth(root.left), maxDepth(root.right)) + 1 root=TreeNode(3) root.left=TreeNode(9) root.right=TreeNode(20) r...
def reverseString( s) -> None: """ Do not return anything, modify s in-place instead. """ for i in range(len(s)//2): s[i],s[len(s)-i-1]=s[len(s)-i-1],s[i] return s print(reverseString(["h","e","l","l","o"]))
# def PalindromePermutation(str1): # count=0 # str1 = str1.replace(' ', '').lower() # if len(str1)%2 ==0: # count=1 # return True from collections import Counter def PalindromePermutation(data: str) -> bool: """Given a string, check if it is a permutation of a palindrome.""" data = da...
""" Given a list of packages that need to be built and the dependencies for each package, determine a valid order in which to build the package. eg. 0: 1:0 2:0 3:1,2 4:3 o/p : 0,1,2,3,4 Ans: Topological Sort dfs(node): visited=set([]) for neigh in items.neigh: if not visited: dfs(neigh) ...
# class2.py #클래스를 정의 class Person: #클래스에 소속된 멤버변수(주로 데이터를 공유하는 것이 목적) num_person = 0 #초기화 메서드(인스턴스 멤버 변수 초기화 담당) def __init__(self): self.name = "Default name" Person.num_person += 1 #일반 인스턴스 메서드 def print(self): print("My name is {0}".format(self.name)) #인스턴스 생성 p1 =...
#! -*- coding:utf-8 -*- def get_sum(n): if n == 1: return n else: return get_sum(n-1) + n def get_duplicate_number(inlist): c_sum = sum(inlist) o_sum = get_sum(len(inlist) -1) return c_sum - o_sum if __name__ == "__main__": res = get_duplicate_number([1,2,3,4,5,6,2]) prin...
""" sample.py """ from random import randint #Test text text = 'one fish two fish red fish blure fish' #histogram word_counts = {'one':1, 'fish':4, 'two':1, 'red':1, 'blue':1} #function accepts a histogram as input. def sample_by_frequency(histogram): #setting random_index as random int from 0 to the sum of the o...
""" Caesar Cipher Encrypt & Decrypt Algorithm ABCDEFGHIJKLMNOPRSTUVWXYZ XYZABCDEFGHIJKLMNOPRSTUVW """ def ceaser_encrypt(text): upper_alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","R","S","T", "U","V","W","X","Y","Z"] text = text.upper() new=[] ...
import unittest from my_list import MyList class AddTest(unittest.TestCase): def setUp(self): self.x = MyList([1, 2, 3]) self.y = MyList([5, 6]) def test_basic(self): self.assertEqual( self.x + self.y, MyList([6, 8, 3]) ) def test_type(self): ...
import numpy as np import pylab as pl import LU_decomp as LU def linear_interp(x,y,test_x): """For given arrays of x and y values function will return the y value of a given x value that is in the range of x values""" if not (type(x) is np.ndarray or type(x) is np.array or type(x) is list): raise ...
# 10. Faça um programa que receba dois números inteiros e gere os números # inteiros que estão no intervalo compreendido por eles. num1 = int(input('Primeiro número: ')) num2 = int(input('Segundo número: ')) lista = [] for i in range(num1,num2+1): lista.append(i) print(lista)
#TODO Futur mirar de sincronitzar amb GoogleCalendar #TODO Millorar estil de programació: noms variables, format, mirar bones pràctiques. #https://docs.google.com/document/d/1PEkRTAWlR4NYJNKJvz9iw4R6m-wJpxDi7xv5tpLPP54/edit alumnes = {} alumne1 = [ [] , [] , [] , [] , [] ] dies = [ "dilluns" , " dimarts" , "dimecres...
#!/usr/bin/env python3 # Function to count the number of words before Sam appears def count_sam(l_str): count = 0 for word in l_str: if word.lower() != 'sam': count += 1 else: count += 1 break return count words = ['a', 'joy', 'joey', 'liquor', 'x', 'y...
#!/usr/bin/env python3 # Function to sum the squares of numbers in a list def sum_square(ls): sum = 0 for i in ls: sum += i*i return sum ls = [3, 5, 9] if __name__ == '__main__': print(sum_square(ls))
#!/usr/bin/env python3 # Print True if all the numbers in the list are odd def true_odd(ls): count = 0 for number in ls: count += number % 2 == 0 print(count == 0) ls = [3, 5, 17, 23, 57, 68] if __name__ == '__main__': true_odd(ls)
#!/usr/bin/env python # -*- coding: utf-8 -*- class Node: def __init__(self, state, parent=None, action=None, cost=0): self.state = state self.parent = parent self.action = action self.cost = cost def __str__(self): return "-- Node {0} --\n Parent: {1}\n Action: {2}\n Cost: {3}" \ .format(self.stat...
# return the numbers of ones in deep array "arr" def findones(arr): total = 0; for element in arr: if (type(element) is int): total += element; else: total += findones(element); return total; class Trie: def __init__(self): self.words = [0] * 27; ...
# Enter your code here. Read input from STDIN. Print output to STDOUT # working backward def maxS(N, B): class helperSolution: def __init__(self, maxSWithMax, maxLastDigit, maxSWithMin, minLastDigit): self.maxSWithMax = maxSWithMax self.maxLastDigit = maxLastDigit self....
def check(n, arr): inverse_array = [None] * n; arr_set = set(arr); if (len(arr) != len(arr_set)): print("NO"); return; for i in range(1, n + 1): inverse_array[i - 1] = arr.index(i) + 1 involution = True; for j in range(0, n): if (inverse_array[j] != arr[j]): ...
# 回顾 # Python # 变量 """ 1、普通赋值 name = 10 2、链式赋值 a=b=c=10 3、多元赋值 a,b=1,2 """ # a = 10 # b = 20 # c = a # a = b # b = c # a,b = b,a # # print(a,b) # 输入输出工具 # sex = input('请输入你的性别:') # print("asdf",2345,1+2,end="\n") # """""" '''''' # 数据类型 # 数字类型(int/float) # bool 布尔 True False # 字符型 # '' "" """""" '''''' # 字符编码: A...
# InsertionSort.py # Author # Version 0.1 # 5 dec 2017 # Python implementaion of insertion InsertionSort this_file = open('RandomNumbers.txt') list_to_sort = [] for line in this_file: list_to_sort.append(int(line)) this_file.close() print(list_to_sort) def insertion_sort(this_list): for key_pos in range(1...
#create a variable and store a value on it x=10 print(x) x=x//5 print(x) #operator spacing #have 1 space before and after operators y = 5 z = x + y print(z) #average wrong_average = 50 + 50 + 50 + 100 + 80 + 50 / 5 right_average = (50 + 50 + 50 + 100 + 80 + 50) / 5 print(wrong_average) print(right_average) #Math funct...
""" Pygame base template for opening a window Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Explanation video: http://youtu.be/vRB_983kUMc image via google images """ import pygame pygame.mixer.init(44100, -16, 2, 2048) # D...
def online_count(dict): return len([person for person in dict if dict[person] == "online"]) print(online_count({"Alice": "online", "Bob": "offline", "Eve": "online"}))
"""Object Oriented Programming (OOP).""" import cv2 as cv class Window: """Create a window with an image.""" def __init__(self, win, img): self.win = win self.img = img cv.imshow(win, img) class App: def __init__(self): img = cv.imread('messi.jpg') Window('image', i...
"""Draw a button to a window with a circle.""" from cvlib import * import math class Window: """Create a window with an image.""" def __init__(self, win, img): self.win = win self.img0 = img.copy() self.img = img self.d = 2 self.col = GREEN cv.imshow(win, img) ...
"""Flip an image horizontally and vertically using keys.""" import cv2 as cv img = cv.imread('fish.jpg') cv.imshow('window', img) while True: k = cv.waitKey(0) if k == ord('q'): break elif k == ord('v'): img = cv.flip(img, 0) elif k == ord('h'): img = cv.flip(img, 1) cv...
def format_latin_text(unformatted_latin_text): """ Accepts a string of Latin text and upper-cases all of its alphabetic characters, replacing all 'U' characters with 'V'. :param unformatted_latin_text: A string containing Latin text :return: A string containing properly formatted Latin """ n...
account1 = {'login': 'ivan','password': 'q1'} account2 = {'login': 'peter','password': 'q2'} account3 = {'login': 'olga','password': 'q3'} account4 = {'login': 'anna','password': 'q4'} user1 = {'name': 'Иван', 'age': 20, 'account': account1} user2 = {'name': 'Петр', 'age': 25, 'account': account2} user3 = {'name': 'Оль...
import os import shutil file_name = input('Enter you file name: ') f = open(file_name) file_lines = f.readlines() found = False search_string = input('Enter the word you want to search: ') for lines in file_lines: print(lines) words = lines.split() for word in words: if(word == sear...
miasto_a = input("Podaj Miasto A:") miasto_b = input("Podaj Miasto B:") #dystans = int(input("Podaj dysntans z miasta A do miasta B:")) dystans = float(input("Podaj dystans z miasta "+miasto_a+" do "+miasto_b+":")) cena_paliwa = float(input("Podaj cenę paliwa:")) spalanie = float(input("Podaj spalanie na 100 km:")) wyn...
import datetime y = datetime.datetime.now().year x = int(input("Podaj rok urodzenia:")) # if 2018 - x > 18: # print("Jesteś pełnoletni!") if y - x > 18: print("Jesteś pełnoletni!")
__author__ = 'luoyuedong' __date__ = '2018/4/19 11:20' def reOrderArray(array): res = [] for i in range(len(array)): if(array[i]%2==1): res.append(array[i]) for i in range(len(array)): if(array[i]%2==0): res.append(array[i]) return res def reOrder...
#insert the data into the table "classroom" which is present inside the "classroomDB.db" database. import sqlite3 classroom_data = [ (1,"Ronak","M",40,23,24), (2,"Rohini","F",54,34,29), (3,"Mohit","M",45,34,93), (4,"sun...
# 6.5 Write code using find() and string slicing (see section 6.10) # to extract the number at the end of the line below. # Convert the extracted value to a floating point number and print it out. # 0.8475 text = "X-DSPAM-Confidence: 0.8475"; space = text.find(" ") raw_num = text[space:] num = raw_num.strip() num ...
# Extracting Data from JSON # In this assignment you will write a Python program somewhat similar to # http://www.pythonlearn.com/code/json2.py. # The program will prompt for a URL, read the JSON data from that URL using urllib and # then parse and extract the comment counts from the JSON data, compute the sum of the...
# 8.4 Open the file romeo.txt and read it line by line. # For each line, split the line into a list of words using # the split() method. The program should build a list of words. # For each word on each line check to see if the word is # already in the list and if not append it to the list. # When the program complet...
""" Elad Eliav Inc. """ START_RANGE = 1 INCREMENTER = 1 END_RANGE = 41 def my_print(): """prints number from 1 to 40 using a while loop""" x = START_RANGE while x < END_RANGE: print(x) x += INCREMENTER def main(): """ calls my_print() """ my_print() if __name__ == '__m...
import socket from constants import * connected = False # connected flag # list of commands COMMANDS = {'NAME', 'TIME', 'EXIT', 'RAND', 'HELP', 'SERVER_SHUTDOWN' } def init_client_socket(ip, port): """ Inits client socket :param ip:...
from random import randint from shapes import * # Wrapper object that holds an array of Shapes class ShapeContainer(object): # const dics for colors, shape types, and num of params required for shapes COLORS = {0: "White", 1: "Red", 2: "Green", 3: "Blue", 4: "Yellow", 5: "Brown", 6: "LightBlue", ...
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that pers...
from tkinter import * import sqlite3 root = Tk() root.geometry("1500x1000") con=sqlite3.connect('medicine7.db') c=con.cursor() c.execute("create table medicine1(name text,available text)") c.execute("insert into medicine1 values('paracitamal','10')") c.execute("insert into medicine1 values('Lotrel','10')") cur...
from tkinter import * import sqlite3 con=sqlite3.connect('staff2.db') c=con.cursor() root=Tk() root.geometry("1500x1000") i=0 #cur=c.execute("create table staff1(id INTEGER,name text,Department text,DOB text,Gender text,phone INTEGER,salary INTEGER,address text)") cur=c.execute("insert into staff1 values(1,'dee...
import random def key(): alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = {} for letters in alphabet: generator = random.choice(alphabet) key[letters] = generator alphabet = alphabet.replace(generator,"") return key def encrypt(key,message): message = message.upper() ciphert...
def _for_loops(): my_list = ['apple', 2, 'cat', 4, 'elephant'] for x in my_list: print(x) if x is 2: break def _example(): word = 'mac-book-pro' for letter in enumerate(word): print(letter) # for loop along with string literal def _for_loop_string_literal(): m...
# before reading files, let us look at prompt for user input from builtins import ValueError def _prompt_user_for_input(): print('Welcome to age prediction!') x = 1 while x > 0: age = input("please enter your age: ") try: age = int(age) if type(age) is not int: ...
import timeit def sum1(n): ''' Take an input of n and return the sum of the numbers from 0 to n ''' final_sum = 0 for x in range(n+1): final_sum += x return final_sum def sum2(n): """ Take an input of n and return the sum of the numbers from 0 to n """ return (n*(...
# Special (Magic/Dunder) methods # Operator overloading class Employee: employee_count = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first_name = first self.last_name = last self.email_address = self.first_name + '.' + self.last_name + '@company.com' ...
name=raw_input("give me ur name:") print("your name is "+name) age=int(input("Give me ur age:")) print("your age is "+ str(age)) out=str((100-int(age))+2017) print(name+" will be 100 years old in "+str(out))
class myStack: def __init__(self): self.stack = [] self.size = 0 # can use len() function but I wanted to do it this way using another variable. def isEmpty(self): return (self.size == 0) def push(self, item): self.stack.append(item) self.s...
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. # ----------------------------------------------------------- # Answer: 906609 palindromic_list = [] fo...
my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 # lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' # 此节练习用 %s、%d、%r 等格式化字符,将变量嵌入字符中间 # 要注意行末引用变量的数量要与前面嵌入的 格式化字符 的数量相对应 print "Let's talk about %s." % my_name print "He's %d inches tall." % my_height print "He's %d pounds ...
# -*- coding: utf-8 -*- import simple_draw as sd # Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py # (код функций скопировать сюда и изменить) # Запросить у пользователя цвет фигуры посредством выбора из существующих: # вывести список всех цветов с номерами и ждать ввода номера желаемог...
# d = {} # d = dict() # d = {"a": 1, "b": 2} # d["c"] = 3 # print(d) # # for a in d: # print(a, d[a]) # # print(d.values()) # print(d.keys()) # print(d.items()) # # dk = list(d.keys()) # dv = list(d.values()) # print(dk, dv) # # d1 = {} # for i in range(len(dk)): # d1[dk[i]] = dv[i] # # print(d1) # # d2 = d.cop...
def binary_search(user_list, searched_element, start, end): if start > end: return -1 mid = (start + end) // 2 if searched_element == user_list[mid]: return mid if searched_element < user_list[mid]: return binary_search(user_list, searched_element, start, mid-1) else: ...
# class Human: # name = "no_named" # date_of_birth = "date" # tel = "phone_number" # city = "city_name" # country = "country_name" # address = "address" # job = "no_job" # objects_count = 0 # # def __init__(self, name, phone): # self.name = name # self.phone = phone #...
user_name = str(input("Enter your name: ")) user_height = float(input("Enter your height in centimetres: ")) user_weight = float(input("Enter your weight in kilograms: ")) perfect_weight = (user_height - 100) * 1.15 weight_difference = user_weight - perfect_weight print(f"{user_name}, your perfect weight is: {round...
# numbers = [] # num = "" # while True: # num = input("Enter number or [e] to exit: ") # if num == "e": # break # if not num.isdigit(): # continue # # numbers.append(int(num)) # find = int(input("Enter number to find:")) # count = 0 # for number in numbers: # if number == find: # ...
# '''Есть три кортежа целых чисел необходимо найти элементы, которые уникальны для каждого списка.''' # a = (1, 2, 4) # b = (1, 3, 5) # c = (1, 2, 6) # # 4, 3, 5, 6 # # l = [1, 1, 2, 3, 5, 8] # print(l[l[4]]) # # def user_login(name=input("Enter your name: ")): # if name == "Yaroslav": # print("Hello") # F...
# import random # player_choice = '' # bot_choice = '' # player_score = 0 # bot_score = 0 # # bot_score, player_score = 0,0 # # for i in range(3): # #Choose # player_choice = str(input("Enter [r], [p], [s]")) # bot_choice = random.choice('rps') # #Check # if player_choice == bot_choice: # pr...
# print(f"5 > 2 {5 > 2}") # print(f"5 < 2 {5 < 2}") # print(f"5 >= 5 {5 >= 5}") # print(f"5 > 5 {5 > 5}") # print(f"5 <= 2 {5 <= 2}") # print(f"5 != 2 {5 != 2}") # print(f"5 == 2 {5 == 2}") # print(f"5 != 5 {5 != 5}") # print(f"5 == '5' {5 == '5'}") # a = 7 # b = 3 # print(f"{a} != {b} {a != b}") # # # if a > b: # # ...
english_ukr = {"book": "книга"} user_input = True while user_input: user_input = input("Enter a command:\n\t" "[add] - add words\n\t" "[del] - del words\n\t" "[find] - find word\n\t" "[edit] - edit words\n\t" ...
width_of_rectangle = int(input("Enter width of rectangle: ")) height_of_rectangle = int(input("Enter length of rectangle: ")) user_symbol = input("Enter a symbol: ") for j in range(height_of_rectangle): print() for i in range(width_of_rectangle): print(f" {user_symbol} ", end="")
user_number = int(input("Enter number: ")) if user_number > 0: print(f"Value of sign(x) = 1") elif user_number < 0: print(f"Value of sign(x) = -1") elif user_number == 0: print(f"Value of sign(x) = 0")
user_tuple_1 = (1, 2, 3, 5, 10, 11, 12) user_tuple_2 = (4, 2, 5, 7, 10, 11) user_tuple_3 = (3, 2, 7, 5, 11, 10, 13, 15) list_of_duplicates = [] final_list_of_duplicates = [] flag = True for nums in user_tuple_3: for num in user_tuple_2: if nums != num: print(nums) flag = True ...
# number1 = 2 # number2 = 4 # print(f"{number1} + {number2} = {number1 + number2}") # result = number1 + number2 # print(f"{number1} + {number2} = {result}") # # result = number1 * number2 # print(f"{number1} * {number2} = {result}") # # result = number1 / number2 # print(f"{number1} / {number2} = {result}") # # result...
user_notes = [['Andrey',2345],['Sten',433],['Ben',4567]] note_index = 0 while True: command = str(input("Enter command :\n [NEW] - create user\n" " [SELECT] - select user\n" " [create] - create note\n" " [read] - read notes\n" ...
fill_the_list = True my_list = [] while fill_the_list: entered_symbol = input("Enter a number to fill the list or press Enter to continue: ") if entered_symbol: my_list.append(int(entered_symbol)) else: fill_the_list = False print(my_list) num_to_delete = int(input("Enter a number to se...
""" The non-trivial part of the code is derived from: http://en.literateprograms.org/Huffman_coding_(Python) The link also contains a good description of the algorithm. """ # flake8: noqa import os, sys from collections import defaultdict from bitarray import bitarray from heapq import heappush, heappop def huffCode...
from tkinter import * from PIL import ImageTk, Image root = Tk() root.title("Learning to Code") root.iconbitmap('images/home.ico') myImage1 = ImageTk.PhotoImage(Image.open("images/house.jpg")) myImage2 = ImageTk.PhotoImage(Image.open("images/house2.jpg")) myImage3 = ImageTk.PhotoImage(Image.open("images/hous...
# caughtSpeeding.py # by _______ # Write function defintion: caughtSpeeding # Make sure it returns a value def caughtSpeeding(speed, speed_limit, isBirthday): print(speed,speed_limit,isBirthday) if isBirthday == True: speed = int(speed - 5) if speed <= 5 + int(speed_limit): print('You ge...
from scipy import array,sqrt,pi,arccos def gradXY(image): """ gradXY(image) -> (gradx,grady) Computes the gradient of an image along X and Y axis. argument : - image : the image as a numpy array returns: - tuple containing : - gradx : map of gradient along x axis - grady : map of gradie...
import pygame from pygame.locals import * import sys SCREEN_SIZE = (640, 480) if __name__ == '__main__': pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE) pygame.display.set_caption("Draw figures") while True: screen.fill((0, 0, 255)) # 矩形 rect(Surface, 色, Rect(左上の座標, 幅, 高さ)...
num_string = input('Input a number: ') num = int(num_string) length = int(len(num_string)) done = False num_binary_reverse = '' while done == False: current_digit = num % 2 num = int(num / 2) num_binary_reverse += str(current_digit) if num == 0: done = True num_binary = num_binary_reverse[::-...
# Library for colored text #from termcolor import colored, cprint # List of movies films = { "Sonic The Hedgehog": {'age': 13, 'seats': 100}, #1 "The Invisible Man": {'age': 18, 'seats': 50}, #2 "Onward": {'age': 13, 'seats': 95}, #3 "Harley Quinn: Birds of Prey": {'age': 15, 'seats': 80}, #4 "Blood...
from cogs.game.minigames.base_game.board import Board def alpha_beta(board, is_player_turn, depth = 0, alpha = Board.LOSS, beta = Board.WIN, max_depth = 4): """An alpha-beta pruning algorithm for an AI to decide which move is best for them :param board: A Board object to use to find the best move ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Met deze klasse bekijk ik het gebruik van inheritance op een geavanceerdere schaal Created on Fri Jan 29 09:40:41 2016 @author: giovanni """ create_script = ''' CREATE TABLE users(id INT(6) PRIMARY KEY, naam varchar(40),voornaam varchar(80) ) ''' import sqlite3 class ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 6 23:07:48 2016 @author: giovanni """ def showDict(*args): w = args[0] h = args[1] height =str(h) width =str(w) #printing .. print("Width : {}\nHeight : {}".format(width,height)) cords = dict({'width':23,'height':...
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This is a program to test file reading Created on Wed Jan 6 21:32:33 2016 @author: giovanni """ from __future__ import print_function f = open("MyText.txt",'r') #firstline = f.readline() #print(firstline) for line in f: print(line,end ='') f.close()
a = int(input()) c = int(input()) b = int(input()) d = int(input()) c1 = 0 c2 = 0 c3 = 0 c4 = 0 if a == 1: c1 = 461 elif a == 2: c1 = 431 elif a == 3: c1 = 420 else : c1 = 0 if b == 1: c2 = 130 elif b == 2: c2 = 160 elif b == 3: c2 = 118 else : c2 = 0 if c == 1: c3 = 100 elif c == 2: c3 = 57 el...
import pygame import random import button pygame.init() width = 800 height = 600 n = 300 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("sorting algorithms") myfont = pygame.font.SysFont('Comic Sans MS', 30) arr = [] buttons = [] buttons.append(button.Button(100, 10, ...
class Employee: def __init__(self,first,last): self.first=first self.last=last @property def email(self): return '{}{}@gmail.com'.format(self.first,self.last) @property def fullname(self): return '{} {}'.format(self.first,self.last) @fullname.sette...
#Target Practice #Nathan Wagstaff #1/31/2020 #The user will put in the coordinates to fire a point on the target. #user instructions and input print("Target Practice Fun!") xPos = input("Enter X coordinate: ") yPos = input("Enter Y coordinate: ") xPos = int(xPos) yPos = int(yPos) #general turtle setup import turtle...
# encoding:utf-8 ''' Solution for Travelling Salesman Problem using PSO (Particle Swarm Optimization) Discrete PSO for TSP References: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.258.7026&rep=rep1&type=pdf http://www.cs.mun.ca/~tinayu/Teaching_files/cs4752/Lecture19_new.pdf http://www.swarminte...