text
stringlengths
37
1.41M
import turtle def circle(t): t.circle(100) t.forward(10) def main(): t = turtle.Pen() for i in range(int(input())): circle(t) if __name__ == "__main__": main()
# author :: HimelSaha text = input("Text: ") # input text from user letterCount = 0 spaceCount = 0 sentenceCount = 0 for i in range(0, len(text)): if (text[i] == '.' or text[i] == '!' or text[i] == '?'): # if iteration encounters these characters, increase sentence c...
import argparse import re from math import sqrt, floor indexes = ["", "6", "7", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18","22", "25"] vowels = ['a', 'e', 'i', 'o', 'u', 'y'] def syllable_count(word): word = word.strip(",.!?;:").lower() n_syllables = 0 if word[-1] == "e": ...
import sqlite3 # SQLite DB 연결 conn = sqlite3.connect("test.db") # Connection 으로부터 Cursor 생성 cur = conn.cursor() # SQL 쿼리 실행 cur.execute("select * from magnet_list order by id") # 데이타 Fetch rows = cur.fetchall() for row in rows: print(row) # Connection 닫기 conn.close()
#!/usr/bin/python #working with methods/functions in python relating to method Str()... #string-str-function.py """ the str() function converts the non-string values into string values str(2) will resture "2" """ """Declare and assign your variable on line 4, then call your method on line 5!""" pi = 3.14 pi_str = st...
#!/usr/bin/python #Using the String Formating2 in python language... # NOT using the default concatenating... use % to replace the strings and concat 'em string_1 = "ABCDEF" string_2 = "XYZ" print "Greetings %s, %s is a Farzi company" % ( string_1, string_2 )
import os import sys import re #This script must be run as root! It validate the MAC address format def check_privilege(): if os.geteuid()!= 0: sys.exit('This script must be run as root!') else: print("You have root privileges. You can run the script! ") Search_mac = [] def validate_mac(mac): try: va...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) del new_class[5] print(new_class) # Code ends he...
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 09:08:35 2020 @author: LG """ import sqlite3 dbpath = 'chinook.db' #연결 conn = sqlite3.connect(dbpath) #커서 cur = conn.cursor() # SQL 문 strSQL = 'SELECT * FROM employees' #실행 cur.execute(strSQL) item_list = cur.fetchall() # fetch 가져오다 for it in item_list: print(it) ...
# -*- coding: utf-8 -*- """ Created on Wed Feb 12 13:24:00 2020 @author: LG """ # by reference def my_function(input_arg): print('Value received: ', input_arg, 'id: ', id(input_arg)) input_arg *= 10 print('Value multipied: ', input_arg, 'id: ', id(input_arg)) x = 10 print('Value before being passed: ', x,...
# [실습 7] 주가 조회하기 - Timer from threading import Timer from time import sleep import bs4 from urllib.request import urlopen import datetime as dt # Timer 출처 # https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwar...
# if 구문 price = int(input("Enter Price: ")) qty = int(input("Enter Quantity: ")) amt = price * qty if amt > 1000: print('10% discount is applicable') discount = amt * 10 / 100 amt = amt - discount print("Amount payable: ", amt)
# Dictionary vs. Set # Dictionary capitals = {"USA":"Washington", "France":"Paris", "India":"New Delhi"} print(capitals.get('France')) print(capitals.get('Paris')) capitals['USA'] = 'Washington, D.C.' print(capitals.get('USA')) del capitals['India'] for key in capitals: print("Key = " + key + ", Value = " +...
# Time Complexity : O(logn) # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : Yes, was trying to do using recursion. But couldn't device a perfect base case # Your code here along with comments explaining your approach class Solution: def searc...
# -*- coding: utf-8 -*- ''' Created on 2016年4月26日 @author: todoit ''' #BubbleSort #冒泡排序,生成器方法 def bubbleSort(data): size = len(data) for i in range(size): for j in range(1,size-i): if data[j-1] > data[j]: data[j-1],data[j]=data[j],data[j-1] #print(data) ...
# -*- coding: utf-8 -*- ''' Created on 2016年4月22日 @author: todoit ''' ''' 思路: 两个共用一条边的正三角形都围绕其中一个三角形的中心旋转 ''' import matplotlib.pyplot as plt import numpy as np #对一个点进行旋转 #输入参数,a是转换前的点的坐标,p是围绕旋转的点,angle是旋转的度数 def rotatePoint(a, p, angle): #计算出该点到某一点的距离,即半径 print("旋转前的点: ",a) #旋转后点的坐标 b0 = p[0]...
# Python script to convert images to Pencil like Sketches import cv2 def sketchit(path): image=cv2.imread(path) grey_img=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) invert=cv2.bitwise_not(grey_img) blur=cv2.GaussianBlur(invert,(21,21),0) invertedblur=cv2.bitwise_not(blur) sketch=cv2.divide(grey_img ...
class Solution: def rotate(self, matrix: List[List[int]]) -> None: n=len(matrix) for i in range(n): for j in range(0,i): matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j] for ele in matrix: ele.reverse()
class Solution: def calculate(self, s: str) -> int: if not s: return 0 stack, curr_num, operator = [], 0, "+" all_operators = {"+", "-", "*", "/"} nums = set(str(x) for x in range(10)) for indx in range(len(s)): char = s[indx] ...
#!/usr/bin/env python # coding: utf-8 # In[1]: #2.>leap year y=eval(input('enter the year')) if(y%100==0): if(y%400==0): print('It is a leap year') else: print('it is not a leap year') else: if(y%4==0): print('It is a leap year') else: print('it is not a leap year') ...
import numpy as np #Recursive Finder Class class RecursiveFinder: def find(self, arr, key, low, high): if low > high: return False else: mid = (low + high) // 2 if key == arr[mid]: return True elif key < arr[mid]: retu...
from classes.passenger_vehicle_class import PassengerVehicle class Bicycle(PassengerVehicle): vehicle_type = 'bicycle' def __init__(self, id, hire_date, return_date, max_num_of_passengers, classification): super().__init__(id, hire_date, return_date, max_num_of_passengers) self.cl...
import pdb def sort_list(mylist): #this function actally change the mylist to mysortedlist, the original mylist doesn't eist anymore mysortedlist = [] for i in range (0, len(mylist)): for j in range (1+i, len(mylist)): max = mylist[i] if mylist[j] > max: max = mylist[j] mylist[j] = mylist[i] m...
# def uniq(alist): # unique_list = [] # dup_list =[] # for x in alist: # if x not in unique_list: # unique_list.append(x) # else: # dup_list.append(x) # print unique_list # print dup_list # return def uniq_2(alist): a=set(alist) aa=str(a) aaa=aa.replace ('set([','') aaaa=aaa.replace(...
def split_sentence(sentence): alist=[] asentence='' bsentence='' alist=sentence.split() asentence=''.join(alist) bsentence=''.join(sentence).split() #alist=sentence.split('',1) return alist, asentence, bsentence my_sentence='Boston is a nice city' print split_sentence(my_sentence)
def sort(mylist): less = [] equal = [] greater = [] if len(mylist) > 1: pivot = mylist[0] for x in mylist: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: greater.append(x) ...
""" In this exercise, you'll be playing around with the sys module, which allows you to access many system specific variables and methods, and the os module, which gives you access to lower- level operating system functionality. """ import sys # See docs for the sys module: https://docs.python.org/3.7/library/sys.html...
# generate the monthly oustanding mortgage # input: annual interest rate, a floating-point percentage rate = 0.05 # input: monthly payment, a positive integer in a currency payment = 200 # input/output: morgage, positive number, same currency mortgage = 1000 print('Outstanding mortgage:', mortgage) while mortgage > 0: ...
from food import Pizza, Gaseosa, Agua, Plato from abc import ABC, abstractmethod import random # Completar las clases donde corresponda # class Personalidad(ABC): def reaccionar(self, plato): # Rellenar aquí pizza=plato.pizza bebestible=plato.bebestible if (pizza.calidad + bebest...
# Write a list or lists. # iterate through the list using for loop. taco_toppings = ['meat', 'cheese', 'lettuce', 'salsa'] for topping in taco_toppings: print 'I am hungry and {} sounds good on my taco'.format(taco_toppings[0])
pi = 3.14 print type(pi) print str(pi) text = 'The value of pi is %d' % pi print text text = 'The value of pi is %r' % pi print text #below comment will fail text = 'The value of pi is ' + pi text = 'The value of pi is ' + str(pi) print text input_value = raw-input("Enter a radius: ") radius = float(input_value) area ...
#Branch 1 removing my_ from variable names. name = 'Amigo' age = 30 height = 170 #Cm height_in_inches = height*0.393701 weight = 88 #KGs weight_in_pounds = weight*2.20462 eyes = 'Brown' teeth = 'White' hair = 'Black' print ("Let's talk about %s." % name) print ("He's %r centimeters tall which is %f inches"...
import hashlib type_of_hash = str(input('MD5 or SHA1, what would you like to hash?: ')) password_list_path = str(input('Enter the path to your password list: ')) hash_to_decrypt = str(input('Enter the hash value: ')) with open(password_list_path, 'r') as file: for line in file.readlines(): if type_of_hash...
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> # int datatype >>> num = 5 >>> type(num) <class 'int'> >>> #float datatype >>> num = 6.5 >>> type(num) <class 'float'> >>> #string datatyp...
# a = [1, 2, 3, 4] # for x in a: # if x == 2: # # 强行终止循环 # # break # # 跳过此循环 # continue # print(x) # print("=========") # # range(0,10,2):表示从0开始到10结束,中间间隔为2递增数列 # # range(10,0,-2):表示从10开始到0结尾的数列中,中间间隔为2的等差数列 # for x in range(0, 10, 2): # print(x, end='|') # for y in range...
# ------- coding:utf-8 -------- ''' 题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点 ''' class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head_node): prev_node = None current_node = head_node next_node = None reverse_head_node = None while current_node...
# ------ coding:utf-8 ---------- ''' 题目:输入两颗二叉树A和B,判断B是不是A的子结构 ''' class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: ''' 书上的思路:遍历father,如果father的根结点和child的根结点一样的话,就调用doesTree1haveTree2判断接下来的结构是否一样 如果father的根结点不与child的根结点一样的时候,就遍历father ''' def hasSubTr...
# --------- coding:utf-8 --------- ''' 题目:实现函数power(base, exponent),求bese的exponent次方 不得使用库函数,不需要考虑大数问题 ''' class Solution: ''' 注意: 区分base是否为1 区分exponent的正负情况 ''' def power(self, base, exponent): if base == 0: return 0 else: if exponent == 0: return 1 elif exponent > 0: for i in range(exponen...
# -*- coding: utf-8 -*- """ Created on Sat Sep 9 16:58:04 2017 @author: Administrator """ import random def buildLargeMenu(numItems, maxVal, maxCost): items = [] for i in range(numItems): items.append(Food(str(i), random.randint(1, maxVal), random....
from time import sleep import RPi.GPIO as GPIO from gpiozero import Motor,RGBLED, Button, LED def on(): global sensorOn global sensorOff global state global speed while True: sensorOn = GPIO.input(sensorPinon) sensorOff = GPIO.input(sensorPinoff) if sensorOn == GPI...
scores={} points={0:0,1:15,2:30,3:40,4:"40+1",5:"40+1+1"} setWinner=[] setScore={"set1":[],"set2":[],"set3":[]} gameWinner=[] #Function to find the winner of the match. def calculate_matchwinner(player1,player2): if setWinner.count(player1) > setWinner.count(player2): return player1 elif se...
def parenbuilder(num_pairs): if num_pairs > 0: result = [] pairs_doubled = num_pairs * 2 _parenbuilder(pairs_doubled-1, 1, 0, num_pairs, '(', result) return result def _parenbuilder(num_pairs, num_open, num_closed, pairs_in, cur_res, result): #try to open paren if num_open >...
import itertools def floor_puzzle(): floors = bottom, _, _, _, top = [1,2,3,4,5] orderings = list(itertools.permutations(floors)) result = next((Hopper, Kay, Liskov, Perlis, Ritchie) for (Hopper, Kay, Liskov, Perlis, Ritchie) in orderings if Hopper is not top and Kay is ...
import time def mergeSort(arr,low,high): if low < high: mid = (low + (high-1))//2 mergeSort(arr, low, mid) mergeSort(arr, mid + 1, high) merge(arr, low, mid, high) def merge(arr, l, m, h): b = [0] * len(arr) low = l med = m count = l - 1 while low <= m and med+1 <= h: if arr[low] < arr[med+1]: cou...
def Solution(A): if A is None or len(A) == 0: return first_row = False first_col = False if A[0][0] == 0: first_row = True first_col = True else: # for i in range(1,len(A[0])): # if A[0][i] == 0: if 0 in A[0]: first_row = True # break for i in range(1,len(A)): ...
def solution(A): slow = A[0]; fast = A[A[0]]; while (slow != fast): slow = A[slow]; fast = A[A[fast]]; # print("S",slow) # print("F",fast) # print(slow,fast) fast = 0; while (slow != fast): slow = A[slow]; fast = A[fast]; # print("S",slow) # print("F",fast) return slow; A =...
import init_music def initialise(sentence): sentence = sentence.lower() song_dict = init_music.init_music() #print (song_dict) check_song_name(sentence, song_dict) def check_song_name(sentence, song_dict): sentence = sentence.split() name = sentence[1:] n = len(name) flag =...
soma = 0 total = 0 while total < 2: notas = float(input()) if notas >= 0 and notas <= 10: soma += notas total += 1 else: print("nota invalida") print("media = {:.2f}".format(soma/2))
from math import sqrt, pow test = True while test: try: values = [int(num) for num in input().split()] x = values[0] y = values[1] a = values[2] b = values[3] v = values[4] r1 = values[5] r2 = values[6] space = v * 1.5 n = sqrt(pow((x ...
def limitador(caractere): total = '' total += str(caractere) k = len(total) if k > 80: return print("NO") else: return print("YES") n = input() limitador(n)
n = int(input()) while n > 0: termos = int(input()) if termos % 2 == 0: soma = n * (1 - 1) print(soma) else: soma = n * (1 - 1) + 1 print(soma) n -= 1
def year_bissexto(year): if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: print("This is leap year.") huluculu(year) buluculu(year) elif year % 15 == 0: huluculu(year) else: print("This is an ordinary year.") def huluculu(year): if year % 15 == 0: ...
distance = int(input()) cont = distance * 2 print("{} minutos".format(cont))
from math import pow test = True try: while test: volume = float(input()) d = float(input()) pi = 3.14 r = d / 2 area = pi * pow(r, 2) h = volume / area print("ALTURA = {:.2f}".format(h)) print("AREA = {:.2f}".format(area)) except EOFError: te...
N = int(input()) if N >= 3600: hora = N // 3600 mim = (N % 3600) // 60 seg = (N % 3600) % 60 else: if N < 3600: hora = 0 mim = N // 60 seg = N % 60 print("{}:{}:{}".format(hora, mim, seg))
n = float(input()) if n > 0: print('+%.4E' % n) elif n < 0: print('%.4E' % n) elif n == 0 and str(n)[0] != '-': print('+%.4E' % n) elif n == 0 and str(n)[0] == '-': print('%.4E' % n)
number = float(input()) if number < 0 or number > 100: print("Fora de intervalo") else: if 0 <= number <= 25: print("Intervalo [0,25]") elif 25 < number <= 50: print("Intervalo (25,50]") elif 50 < number <= 75: print("Intervalo (50,75]") elif 75 < number <= 100: print...
cont = 0 def food(meal): global cont if meal == 1: return cont if meal < 1: return cont else: meal /= 2 cont += 1 return food(meal) n = int(input()) while n > 0: meal = float(input()) print("{} dias".format(food(meal))) cont = 0 n -= 1
# class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e # class Solution: def merge(self, intervals): intervals = [[x.start, x.end] for x in intervals] intervals.sort(key=lambda x: (x[0], x[1])) #print(intervals) i = 1 #Len = len(...
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ # 寻找环的第一个节点的方法是: # 首先假定链表起点到入环的第一个节点A的长度为a【未知】 # 到快慢指针相遇的节点B的长度...
from math import sqrt class Solution: def climbStairs(self, n: int) -> int: if n <= 2: return n else: temp = 1 i = 2 ans = 2 while i < n: temp, ans = ans, temp + ans i += 1 return ans # fibs ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def tree2str(self, t: TreeNode) -> str: self.ans = [] self.preOrder(t) return ''.join(self.ans) def preOrder(self, root...
class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.Min = [] def push(self, x: int) -> None: self.stack.append(x) if not self.Min or x <= self.Min[-1]: self.Min.append(x) def pop(self) ->...
class Solution: def sortColors(self, nums) -> None: """ Do not return anything, modify nums in-place instead. """ # dic = {} # dic['0'] = nums.count(0) # dic['1'] = nums.count(1) # dic['2'] = nums.count(2) # nums = [] # for num in ['0', '1', '2...
class Solution: def containsDuplicate(self, nums) -> bool: nums.sort() temp = nums[0] type = 1 for num in nums: if temp != num: type += 1 temp = num return type != len(nums)
''' class Solution: def longestCommonPrefix(self, strs): List = list(strs) minLen = 10000 str = '' for i in range(len(List)): if len(List[i]) < minLen: minLen = len(List[i]) for i in range(minLen): for j in range(0, len(List) - 1): ...
#!/usr/bin/env python3 # an example Python program # by Erin Coffey # 10 January 2018 import sys MODULES_DIR = "/Users/erin/Documents/Development/Python/modules/" sys.path.append(MODULES_DIR) # import local module for welcome message import stringer # import module for tracking lost time import timer ...
#!/usr/bin/env python3 # an example Python program # by Erin Coffey # 10 January 2018 import sys MODULES_DIR = "/Users/erin/Documents/Development/Python/modules/" sys.path.append(MODULES_DIR) # import local module for welcome message import stringer # import module for tracking lost time import timer ...
#!/usr/bin/env python3 # an example Python program working with dictionaries # by Erin Coffey # 29 January 2018 import sys MODULES_DIR = "/Users/erin/Documents/Development/Python/modules/" sys.path.append(MODULES_DIR) # import local module for welcome message import stringer # import module for tracking lost time im...
#!/usr/bin/python3 #@pfiff, christina class Person: def __init__(self,name,age=20,size=10): self.name=name[0].upper() + name[1:] self._age=age self.__size=size def __str__(self): return "ich heiße: {}".format(self.name) pass class Student(Person): pass class GuiElement: def __init__(self, x = 0, score =...
#!/usr/bin/python3 #author leitner mitterer class Paper(): def __init__(self,text): self.text=text class Timer(): def __init__(self, time): self.time=time class Securepaper(Paper, Timer): def __init__(self, encryptiontype, text, time): Paper.__init__(self,text) Timer.__init__(self,time) self.encr...
#! /usr/bin/python3 # @author Christina, Viktoria def add(a,b): return a+b print(add(1,3)) def add(a,b=1): return a+b print(add(2)) print("Done")
#!/usr/bin/python3 #@sakaijun, taucherp #print("Hallo") def generator(s): slist=s.split() for el in slist: yield(el) #yield(slist) g=generator("Heute ist das Wetter nicht schoen") for a in g: print(a)
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') from sklearn.cluster import MeanShift from sklearn import preprocessing df = pd.read_excel('titanic.xls') original_df = pd.DataFrame.copy(df) # print(df.head()) df.drop(['name', 'body'], 1, inplace=...
def is_leap(year): #all statements evalueate to booleans, therefore function returns a boolean return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0) def print_ints(n): nums = "" for i in range(1, n+1): nums += str(i) return nums print(is_leap(2100)) print(print_ints(5))
#LIFO - Last in first out. E.G. A stack of books. A new book will be added to the top of the stack. #Removing a book will remove the book at the top of the stack. class Stack: def __init__(self): self.items = [] def push(self, item): """Accepts an item as a parameter and appends it to the end ...
from Deque import Deque def main(data): deque = Deque() for character in data: deque.add_rear(character) while deque.size() >= 2: front_item = deque.peek_front() rear_item = deque.peek_rear() deque.remove_front() deque.remove_rear() if rear_item != fron...
def first_three_multiples(num): print(num * 1) print(num * 2) print(num * 3) return num *3 def tip(total, percentage): result = total * (percentage / 100) return result def introduction(first_name, last_name): return last_name+ ", " + first_name + " " + last_name def dog_years(name, age):...
def in_range(num, lower, upper): if num >= lower and num <= upper: return True else: return False def same_name(your_name, my_name): if your_name == my_name: return True else: return False def always_false(num): if num > num or num < num: return True ...
#Method Overiding. 자식 클래스 메소드를 쓰고플 때 새로 메소드를 정의하여 사용 class unit: def __init__(self, name, hp, velocity): self.name = name self.hp = hp self.velocity = velocity def move(self, location): print("Unit move") print("{0} : {1} location. velocity {2}"\ .form...
hours = float(input("Enter Hours:")) #45 rate = float(input("Enter Rate:")) #10.50 def computepay(h,r): if h >40: return (h-40)*r*1.5 + 40*r else : return h*r p = computepay(hours, rate) print("Pay",p)
class Unit: def __init__(self): print("Unit 생성자") class Flyable: def __init__(self): print("Flyable 생성자") class Flyable_Unit(Unit,Flyable): def __init__(self): # super().__init__() #다중 상속 시 마지막 부모 클래스만.. 그래서 unit.__init__(self) 로 초기화해야함 Unit.__init__(self) Flyable...
from tkinter import * from tkinter.scrolledtext import ScrolledText from book import Database database = Database() class Window(object): def __init__(self,window): self.window = window self.window.wm_title("Book Reminder") l1 = Label(window,text="Title") l1.grid(row=0,column=0) ...
#This is a simple import random guess_made=0 name=raw_input('hello,what is your name?\n') number=random.randint(1,20) print 'well {0},i am thinking a number between 1 and 20.'.format(name) while guess_made <6: guess=int(raw_input('Take a guess:')) guess_made +=1 if guess <number: print 'your gues...
''' Game of Life: Rules: 1.Any live cell with fewer than two live neighbors dies, as if caused by under-population. 2.Any live cell with two or three live neighbors lives on to the next generation. 3.Any live cell with more than three live neighbors dies, as if by over-population.. 4.Any dead cell with exactly three li...
def findMinStep(board , hand) : def status(board , idx , ball) : board = board[:idx]+ ball + board[idx:] i = 0 while i <len(board)-2 : if board[i] == board[i+1] and board[i+2] == board[i+1] : j = i + 2 while j<len(board) and board[j]==board[i] : ...
#import module from tkinter for UI from tkinter import Tk, Label, Button from _tkinter import * import os #creating instance of TK root=Tk() root.configure(background="#80D8FF") #root.geometry("600x600") def function1(): os.system("python training.py") def function2(): o...
import time import RPi.GPIO as GPIO from time import sleep mtc1 = 7 mtc2 = 32 enar = 29 in1r = 31 in2r = 33 enal = 11 in1l = 12 in2l = 13 temp1=1 GPIO.setmode(GPIO.BOARD) GPIO.setup(mtc1, GPIO.IN) GPIO.setup(mtc2, GPIO.IN) GPIO.setup(in1r,GPIO.OUT) GPIO.setup(in2r,GPIO.OUT) GPIO.setup(enar,GPIO.OUT) GPIO.setu...
# ВНИМАНИЕ! Извините было мало времени, не успел в методах обработать ошибки по вводу цифр, символов и букв # чтобы пользователь не сломал программу. class TV_controller: def __init__(self, model, channels): self.model = model self.channels = channels self.selected_channel = 0 def firs...
class Product(object): def __init__(self,price,item_name,weight,brand,cost,status="For Sale"): self.price = price self.item_name = item_name self.weight = weight self.brand = brand self.cost = cost self.status = status self.tax = 0.06 # Sell: changes stat...
# Print num 1-255 def print1to255(): for some_number in range(0, 256): # for looping in range 0 -256 print some_number # print1to255() # Print array with odds arr =[1,2,3,4,5,6,7,8,9] def withOdds(arr): for some_element in range(0, len(arr)): if arr[some_element] % 2 != 0: arr[som...
print ("Hell World") x = "Hello Python" print x y = 42 print y #String name = "Zen" print "My name is", name name = "Zen" print "My name is" + name # String Interpolation using {} first_name = "Zen" last_name = "Coder" print "My name is {} {}".format(first_name, last_name) ''' The following is a list of commonly u...
class InventoryItem(object): def __init__(self, description, cost, quanity): self.description = description self.cost = cost self.quantity = quanity inventoryList = [ InventoryItem('Monitor', 149.99, 5), InventoryItem('Keyboard', 29.99, 12), InventoryItem('Mouse', 24.99, 13), ...
# Get our numbers from the command line import sys numbers= sys.argv[1].split(',') numbers= [int(i) for i in numbers] # Your code goes here index = int() highest_number = int() integer = int() result = int() highest_number = numbers[0] index = 0 for index in range(0, len(numbers)): integer = numbers[index] if int...
num_days = int() num_weeks = int() snow_fall = float() daily_total = float() weekly_total = float() for num_weeks in range(1,3): for num_days in range(1,4): snow_fall = float(input("Enter how much snow has fallen: ")) daily_total = daily_total + snow_fall print("Total Daily Snowfall: ", daily_t...
#Variables daily_cans = int() weekly_cans = int() total_cans = int() #outer loop keeping track of number of weeks for weeks in range(1,3): #inner loop keeps track of days for days in range (1,4): daily_cans = int(input("Enter total cans collected today: ")) weekly_cans = weekly_cans + daily_can...
from collections import defaultdict import random from flow_utilities import generate_flow_network, delete_node_from_network,modify_link_from_network,generate_flow_randomly import time from flow_visualize import generate_graph, generate_flow_distribution class Graph: """This class uses a 2D array in python to repr...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import hashlib __all__ = ['hasher'] def hasher(string, size=8): """Simple function to generate a SHA1 hash of a string. Parameters: - string : string or bytes The string to be hashed. - size : int Size ...
start = 99 while start: print("{} bottles of beer on the wall".format(start)) print("{} bottles of beer.".format(start)) print("Take one down, pass it around") start -= 1 print("{} bottles of beer on the wall.".format(start)) if start == 0: print('All outta beer')
list = [] def show_help(): print('What do you want to add to your list?') print(''' type "SHOW" to show current list type "HELP" to show a list of app commands type "DONE" to stop adding items ''') def show_list(): print('Here is your list:') for item in list: print(item) def add_items(new_item): ...