text
stringlengths
37
1.41M
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree: def __init__(self, root): self.root = Node(root) def print_tree(self, traversal_type): if traversal_type == 'preorder': return self.pre_or...
class Graph: def __init__(self): self.connections = {} def create_edges_from_vertexes(self, first_vertex_id, second_vertex_id, weight): if weight < 0: raise ValueError('Weights must be > 0') if (type(first_vertex_id) is not int) | (type(second_vertex_id) is not int) | (typ...
import csv import pandas as pd import numpy as np ''' Eventually, can clean up data and use OOP with Data as a Class ''' #Parse csv file containing pollutant parameters data and convert it into a Pandas DataFrame All_data = pd.read_csv("E:/Work Study AIr Pollution Research/254 Wellington/254 wellington st n ...
#Gets input from user for variables Num=int(input("Enter the number you would like to check:")) print("The factors of",Num,"are:") #checks for factors and outputs them for x in range(1,Num + 1): if(Num % x == 0): print(x)
from math import exp # exp(x) gives e^x def grouper(seq, n): '''Extract all n-grams from a sequence An n-gram is a contiguous sub-sequence within `seq` of length `n`. This function extracts them (in order) from `seq`. Parameters ---------- seq : sequence A sequence of words or token ...
class Solution: def addBinary(self, a: str, b: str) -> str: result = "" # 补全少的一方,以免循环结束后继续判断 if len(a) > len(b): b = "0" * (len(a) - len(b)) + b elif len(a) < len(b): a = "0" * (len(b) - len(a)) + a i, j = len(a) - 1, len(b) - 1 flag = False ...
''' --- Day 8: Space Image Format --- The Elves' spirits are lifted when they realize you have an opportunity to reboot one of their Mars rovers, and so they are curious if you would spend a brief sojourn on Mars. You land your ship near the rover. When you reach the rover, you discover that it's already in the proces...
''' --- Day 1: The Tyranny of the Rocket Equation --- Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements fr...
import argparse from src.functions import * def main(): """Main module checks the arguments passed by the user and adds as an exclusion rule the simultaneous use of encoding and decoding arguments """ parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() g...
#this function implements extracting values from BST in the given range def bstInRange(root,k1,k2): if root is None or root.data<k1 or root.data >k2: return bstInRange(root.left,k1,k2) print str(root.data)+" ", bstInRange(root.right,k1,k2)
import sqlite3 def create_store_schema(): """this function is used to create the initial schema, 3 different tables""" sqlite_file = 'inventory_schema' con = sqlite3.connect(sqlite_file) c = con.cursor() columns_creation = 'ProductName TEXT default NAMEPH NOT NULL,\ ManufacturerName TEXT default M...
""" https://www.codewars.com/kata/54e6533c92449cc251001667 Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: unique_in_order('AAAABBBCCDAABBB') ==...
import time from .logging import Logging class Timer: def __init__(self): self.current_time = time.time() def reset(self): self.current_time = time.time() def get_duration(self): current_time = self.current_time self.reset() return self.current_time - current_ti...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import linregress def draw_plot(): # Read data from file df = pd.read_csv('epa-sea-level.csv', usecols=[0,1]) x = df['Year'] y = df['CSIRO Adjusted Sea Level'] # Create scatter plot plt.scatter(x, y) # ...
# Generate a histogram of state distribution of users. # Some regex is used here to parse the addresses we collected from the CSV file # and retrieve the State Abbreviation. Thanks @John Ring. adrs = [] REGEX = re.compile(',\s([A-Z]{2})\s(\d{5})') for adr in addresses: adr = re.search(REGEX,adr) if adr != None:...
import os def rename_files(): #1 get file names from a folder file_list = os.listdir("/home/wang/Desktop/udacity/prank") current_path = os.getcwd() os.chdir("/home/wang/Desktop/udacity/prank") print ('Current working directory : ' + current_path) for file_name in file_list: print('Old ...
# 位置参数 def power(x): return x*x # 当我们调用power函数时,必须传入有且仅有的一个参数x print(power(5)) print(power(15)) # 计算xn def power(x,n): s=1 while n>0: n=n-1 s=s*x return s power(5,2) power(5,3) # 默认参数 def power(x,n): s=1 while n>0: s=s*x return s def power (x, n:int=2): s=1 ...
# 字符串是一种Sequence类型(元素、字符) a=[] a=[12,'add','inner','list'] a[:3] a[2:] a[1:4] print() print(a[1:4]) # 列表 是一种Sequence类型(每个元素是任意类型)不支持赋值 a=[ 'adda' 'dsdaf' 'adada' 'adada' ] a=['sdad','add',['adad','adadf']] a[2][1] print(a[2][1]) # indentation缩进 # 元组的定义和创建 切片可行但赋值不行a[0]=2 a=(11,1331,'asa','asdf')...
i=1 # while condition while i <=10: # 先判断条件 print(i) # 后遍历并循环 i += 1 # i=i+1 print("Done with loop")
# for (i=0; i<list.length;i++){ # n=list[i]; # } d={'a':1,'b':2,'c':3} for key in d: print(key) # 默认情况下,dict迭代的是key # for value in d.values() # 同时迭代key和value # for k, v in d.items() for ch in 'ABC': print(ch) # 一类是集合数据类型,如list、tuple、dict、set、str等 # 一类是generator,包括生成器和带yield的generator function # 这些可以直接作用...
# 数据类型 整数 浮点数 字符串 # 转义字符 \ 换行 \n 制表符 \t 字符\用\\表示 print('I\'m ok') print('I\'m learning\npython') print('\\\n\\') print('\\\t\\') # r''默认字符不转义 print(r'\\\t\\') # '''...'''表示多行内容,多行输入提示符>>>变为... 注意...是提示符,不是代码的一部分 print('''linel ...line2 ...line3 ''') # 输入'''和括号)后,执行该语句并打印结果 print('''linel line2 line3 ''') print...
# 逻辑运算符号 ''' def reverseWords(input): inputWords = input.split(" ") inputWords = inputWords[-1::-1] output = ' '.join(inputWords) return output if __name__ == "__main__": input = 'You like me ni mei shi ba' rw = reverseWords(input) print(rw) ''' ''' student = ['Tom', 'Jim', 'Mary', 'Tom', '...
# Merge two sorted list using recursion # Recursive def merge_list(lst1, lst2): if not lst1: return lst2 if not lst2: return lst1 if lst1[0] < lst2[0]: return [lst1[0]] + merge(lst1[1:], lst2) return [lst2[0]] + merge(lst1, lst2[1:]) # iterative def merge_list(lst1, lst2): ...
# Implement integer exponentiation power(base, exp). Do it with recursion def power(base, exp): # Negative exponent if exp < 0: return power(1 / base, -1 * exp) # Base case if exp == 0: return 1 return base * power(base, exp - 1)
import random from collections import namedtuple Experience = namedtuple("Experience", ['obs', 'action', 'reward', 'next_obs', 'done']) class ExperienceMemory(object): def __init__(self, capacity=int(1e6)): self.capacity = capacity self.mem_idx = 0 self.memory = [] def s...
import RPi.GPIO as GPIO import time from picamera import PiCamera #library for raspberry pi camera from datetime import datetime GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN) #PIR motion sensor input pin GPIO.setup(3, GPIO.OUT) #LED output pin camera = PiCamera() #Camera output pin while Tru...
import threading import time def task(): print('Inicio tarea.- {}'.format(threading.current_thread().name)) time.sleep(3) print('fin tarea.- {}'.format(threading.current_thread().name)) if __name__ == "__main__": num_hilos = 20 hilos = list() for i in range(num_hilos): hilo = thre...
def create_dict(file_name: str) -> dict: recipes_dict = dict() with open(file_name, 'r', encoding='utf-8') as file: for line in file: dish_name = line.strip() number_of_ingredients = int(file.readline()) list_of_ingredients = [] for ingredient in ra...
# Richella O'Driscoll 2018-02-27 # Guessing Game from random import randint target = randint(1, 100) guess = 101 print("Guess a number between 1 and 100:") while guess != target: guess = int(input("Please enter your guess:")) if guess == target: print("Well Done! You guessed correctly!"...
class Fraction: def __init__(self, x = '', y = 0): if type(x) == Fraction: self.a = x.a self.b = x.b elif x == '' and y == 0: self.a = 0 self.b = 1 elif y == 0: if '/' in str(x): self.a, self.b = list(map(int, x.spli...
class Point: def __init__(self, x, y = ''): if type(x) == str: self.x, self.y = list(map(int, x.split())) else: self.x = x self.y = y def __sub__(self, other): A = Point(self.x - other.x, self.y - other.y) return A def ...
def bin_gcd(a, b): if a == 0: return b if b == 0: return a if a == b: return a if a == 1 and b == 1: return 1 if not a & 1 and not b & 1: return 2 * bin_gcd(a // 2, b // 2) if not a & 1 and b & 1: return bin_gcd(a // 2, b) if a & 1 and not b & ...
input = open('input.txt', 'r') output = open('output.txt', 'w') a = input.readline(1) letters = 0 words = 0 lines = 0 previous = '' while a != '': if 'a' <= a <= 'z' or 'A' <= a <= 'Z': letters += 1 elif ('a' <= previous <= 'z' or 'A' <= previous <= 'Z') and (a < 'A' or 'Z' < a < 'a' or ...
def fastPow(a, n): res = 1 while n: if n & 1: res *= a n = n >> 1 if n == 0: break a *= a return res class Fraction: def __init__(self, x = '', y = 0, IS = True): if type(x) == Fraction: self.a = x.a self.b = x.b ...
def validate_input(prompt, validf, message=''): # prompt: how to ask for the the input # validf may either be an iterable or function # message: what to return if validation fails. if empty and list, return valid string list. if callable(validf): validtype = 1 elif hasattr(validf, '__iter__'...
#!/usr/bin/env python3 # Created by DJ Watson # Created on October 2019 # this program checks if an inputted year is a leap year def main(): # input numinput = input("Enter year: ") # process and output try: intcheck = int(numinput) if int(numinput) >= 0: if (int(numinpu...
from math import pi radius =float (input("the radius of the circle:")) print("the area of the circle with radius "+str(pi*radius**2))
import matplotlib.pyplot as plt import numpy as np from scipy import integrate import math as m #Error Function def exp1(t): a=-1*(t**2) b=np.exp(a) return b def errf(x): a=integrate.quad(exp1,0,x)[0] return (2*a)/((np.pi)**0.5) def taylor(n,x): a=np.arange(0,n+1,1) f=0 for i in a...
class BinaryTreeNode: def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # supplementary code not from book def insert(self, data): # compare new value with the parent node if self.data: if data < s...
class ListNode: def __init__(self, data=None, next_node=None): self.data = data self.next = next_node # search for a key def search_list(linkedlist, key): while linkedlist and linkedlist.data != key: linkedlist = linkedlist.next # if key was not present in the list, L will have be...
# Uses python3 # My custom getMax routine (mutates, but hey I'm a noob at this python stuffs) def getMax(arr): maxN = 0 popIndex = -1 for i in range(0, len(arr)): if (arr[i] > maxN): maxN = arr[i] popIndex = i if (popIndex > -1): arr.pop(popIndex) return maxN n = int(input()) a = [int(x)...
def menu(): print('Diccionario') print('.......................') print('1. AGREGAR') print('2. IMPRIMIR') print('3. ELIMINAR') print('4. CONSULTAR O BUSCAR') print('5. SALIR') opcion=input('Eliga una de las opciones: ') return opcion def main(): while True: ...
#인덱스 생략 letters = ['A','B','C','D','E','F'] print(letters[:3]) print(letters[3:]) print(letters[:]) #이건 리스트 복사할 때 사용함. 걍 전체 복사
ame_no = int(input("아메리카노는 몇잔? ")) caf_no = int(input("카페라테는 몇잔? ")) cap_no = int(input("카푸치노는 몇잔? ")) money = int(input("얼마 있으십니까? ")) charge = 0 charge += ame_no * 2500 charge += caf_no * 3000 charge += cap_no * 3000 print("총 금액은",charge,"입니다.") if (money>=charge): print("거스름돈은",money-charge,"원 ...
class BankAccount: def __init__(self): self.__balance = 0 def withdraw(self, amount): self.__balance -= amount print("통장에 ", amount,"가 출금되었음") return self.__balance def deposit(self, amount): self.__balance += amount print("통장에 ", amount,"가 입금되었음"...
num=int(input()) if (num%2)==0: print("{0} even".format(num)) else: print("{0} odd".format(num))
import os #统计给定文件的行数 def countfile(test): f=open(test) num=0 for x in f:num=num+1 return num #用来判断给定输入是目录还是文件,如果是文件,返回输入行数,如果是目录,迭代主程序 def count(test): if(os.path.isfile(test)): return countfile(test) return total(test) #主程序,接收输入,返回总共的行数 def total(test): l=os.listdir(test) ...
import urllib def getURL(url): socket = urllib.urlopen(url) readSocket = socket.read() socket.close() return readSocket def printInfo(listInfo): print "Stock Symbol: " , listInfo[0] print "Last Trade Price: " , listInfo[1] print "Last Trade Date: " , listInfo[2] print "Last Trade Time: " , listInfo[3] print...
# -*- coding: utf-8 -*- #替换字符串开头的空格 i=0 while s[i].isspace(): i=i+1 else: ss=s[0:i].replace(' ','*') s=ss+s[i:] print s #www.iplaypy.com #替换字符串结尾的空格 i=-1 while s[i].isspace(): i=i-1 else: ss=s[i+1:].replace(' ','*')#list 用负数进行索引时,[a:-1],-1仍然是取不到的 s=s[:i+1]+ss print s
关于python时间模块问题 #:当前时间时间戳 1312181113.31 print(time.time()) #将字符串转成时间戳 ts = '2011-08-01 14:15:40' b = time.mktime(time.strptime(ts,'%Y-%m-%d %H:%M:%S')) print(b) #返回指定时间的时间戳使用mktime d = datetime.datetime(1997,12,29,15,59,59) t = d.timetuple()#再转为元组 print(time.mktime(t)) #使用time的mktime方法返回时间戳 #将时间戳转成时间使用strftime() u = t...
import random import time import logging def isSorted(ml): for i in range(len(ml) - 1): if ml[i] > ml[i + 1]: return False return True def swap(ml, m, n): t = ml[m] ml[m] = ml[n] ml[n] = t def bubbleSort(ml): for m in range(len(ml) - 1): for n in range(len...
#coding=utf-8 import datetime # input datetime1, and an month offset # return the result datetime def datetime_offset_by_month(datetime1, n = 1): # create a shortcut object for one day one_day = datetime.timedelta(days = 1) # first use div and mod to determine year cycle q,r = divmod(datetime1.mon...
import sys import random def strategy(boxes, p): ''''' return True if strategy success ''' return False def simulate(n, strategy, times): ''''' n: number of boxes or prisoners strategy: strategy used times: random simulation times return numbers of succeeded prisoner...
people={ 'Alice':{ 'phone':'2341', 'addr':'Foo drive' }, 'Beth':{ 'phone':'9102', 'addr':'bar street 42' }, 'Cecil':{ 'phone':'3158', 'addr':'Baz avenue 90' } } labels={ 'phone':'phone number', 'addr':'addre...
""" HEADS UP this is the version for trying to see the pokemon cards on a web page NOT the version submitted for the project PokeCardDex template. This is a template file that is used to define the classes and functions to work with Pokemon cards and lists of Pokemon cards called PokeCardDex """ import json i...
#https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/529/week-2/3299/ class Solution: def stringShift(self, s: str, shift: List[List[int]]) -> str: #calculate the net shift net_shift = 0 for entry in shift: net_shift += ((-1 if entry[0] == 0 else 1) * entry[1...
#https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/530/week-3/3304/ #BY_HEART the bloody program -- too many opportunities to inject bugs class Solution: def search(self, nums: List[int], target: int) -> int: #find the pivot ( min ele) if not nums or not len(nums): ...
# Maximum Subarray # https://leetcode.com/explore/other/card/30-day-leetcoding-challenge/528/week-1/3285/ class Solution: def maxSubArray(self, nums: List[int]) -> int: #store_max_sum_till_now #Keep adding elements to current sum as long as it is +v. # Update the max_sum if required at eve...
D = { 'girl' : 'dziewczyna', 'boy' : 'chłopiec', 'house' : 'dom', 'car' : 'samochód' } print ('Angielskie girl to', D['girl']) D['table'] = 'stół' D['ass'] = "dupa" print (D) """ for k in D: print ('Klucz', k, D[k]) #szybkie print (list(D), len(D)) for k,v in D.items(): print (k,v) print (D....
import math def zdubluj(x): return 2*x #zdubluj("trzy") #wynik:'trzytrzy' # można dublować listy, liczby, napisy #gdy zdubluj('trzy')[4] wynik: 't' dubluje 5ty element licząc od zera >> "abrakadabra"[1:6] 'braka' >>> "abrakadabra" [1:100:2] 'baaar' 'arbadakarb' >>> "abrakadabra"[::1] 'abrakadabra' >>> #odwracam l...
#analiza Collatza program, który oblicza energię liczby def F(n): if n % 2 == 0: return n / 2 else: return 3 * n + 1 def zamien(a,b): if a>b: print("Zły format przedziału, naprawię go.") c=b w=a b=w a=c else: print("Dobry przedz...
# LeetCode 74. Search a 2D Matrix from typing import List matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]] def printMatrix(matrix: List[List[int]]) -> None: for row in matrix: print(row) printMatrix(matrix) class Search2dMatrix: def searchTarget(self, matrix: List[List[int]]...
import func numOfTeams = int(input("Number Of Teams: ")) teams = [] for i in range(numOfTeams): teams.append(input(f"{i+1}. Team Name: ")) if numOfTeams%2!=0: teams.append("BAY") print("\n") for i in range(len(teams)-1): print("------ week {} ------".format(i+1)) teams = func.tea...
wieght = int(input("Please enter weight: ")) grams_mod_100 = int(wieght%100) grams_div_100 = int(wieght/100) grams_mod_50 = int(grams_mod_100%100) grams_div_50 = int(grams_mod_100/100) grams_mod_10 = int(grams_mod_50%10) grams_div_10 = int(grams_mod_50/10) grams_mod_5 = int(grams_mod_10%5) grams_div_5 =...
import time start_time = time.time() #open the file and parse it into a list of strings on newlines text_file = open("input.txt", "r") lines = text_file.read().split('\n') #every input text file has an empty newline at the end, delete it lines.pop(-1) #convert every string in the list to an int for i in range(0, len(...
import time start_time = time.time() #open the file and parse it into a list of strings on newlines text_file = open("input.txt", "r") lines = text_file.read().split('\n') #every input text file has an empty newline at the end, delete it lines.pop(-1) #define the checkslope function that i will be using to check each...
import time start_time = time.time() #open the file and parse it into a list of strings on newlines text_file = open("input.txt", "r") lines = text_file.read().split('\n') #every input text file has an empty newline at the end, delete it lines.pop(-1) #convert every string in the list to an int for i in range(0, len(...
import tkinter as tk from cell import Cell from grid import Grid # Create the window with the Tk class root = tk.Tk() # Create the canvas and make it visible with pack() canvas = tk.Canvas(root, width=800, height=800) canvas.pack() # this makes it visible # Loads and create image (put the image in the folder) de...
class Solution: def twoSum(self, nums, target): hash_map = dict() for i, x in enumerate(nums): if target - x in hash_map: return [i, hash_map[target - x]] hash_map[x] = i if __name__ == '__main__': l = [2, 7, 9, 15] l.append(2) print(l) s = S...
import random from collections import deque initial_state = { 'a': 7, 'b': 2, 'c': 4, 'd': 5, 'e': None, 'f': 6, 'g': 8, 'h': 3, 'i': 1 } target_state = { 'a': 7, 'b': 2, 'c': 4, 'd': 5, 'e': 6, 'f': None, 'g': 8, 'h': 3, 'i': 1 } # Number of incorrect positions def h1(current, target): s...
import time seconds = int(input("How many seconds?")) for i in range(seconds): print(str(seconds - i) + " seconds remain") time.sleep(1) print("Times UP!")
class prefix: l = 0 w = 0 h = 0 def __init__(self,l,w,h): self.l = l self.w = w self.h = h def calcvolume(self): l = self.l w = self.w h = self.h print("The volume equals:", str(w*l*h)) def calcsurface(self): l = self.l ...
class Solution: def isValid(self, s: str) -> bool: dict1={"{":"}","[":"]","(":")"} #Create a dict stack=[] # Create a empty a stack for i in range(len(s)): if s[i] in dict1.keys(): stack.append(s[i...
#creating of empty dictionary d={} print("Type of d : ",type(d)) l=dict() print("Type of l : ",type(l)) #retrieving dictionary values using keys d={1:'python',2:'java',3:'c',4:'c++'} print("retrieving value of key 2 d[2] : ",d[2]) # len() function print("length of d : ",len(d)) #dictionary manipulation #adding entr...
import shutil import cmath class Rectangle: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height # Use the terminal size as the number of "pixels" on the screen viewport = shutil.get_terminal_size() # https://www.bo...
message = 'GUVF VF ZL FRPERG ZRFFNTR.' LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # loop through every possible key for key in range(len(LETTERS)): translated = '' # loop through the message character by character for char in message: if char in LETTERS: num = LETTERS.find(char) # get the number of the character ...
def print_vars(arg1, *args, **kwargs): print('arg1:', arg1) print(type(args)) for arg in args: print(arg) print(type(kwargs)) for key, arg in kwargs.items(): print(key, arg) print_vars('one', 'two', 'whar', name='neo', phone='iphone') def multiplication(*args): if len(args...
import itertools class Tree(object): def __init__(self, data, left, right): self.left = left self.right = right self.data = data # String -> (Int, String) def splitSumTree(xs): head, *tail = xs if head.isdigit(): return head + splitSumTree(tail) else: retur...
class Song: def __init__(self, name): self.name = name self.next = None def next_song(self, song): self.next = song def is_repeating_playlist(self): songs = set() next_song = self while next_song: if next_song.name in songs: ...
class Node: def __init__(self,val): self.left = None self.right = None self.val = None def insert(self,root,val): node = Node(val) curr = root while curr: if val > curr.val: if tmp.right: tmp = tmp.right ...
##Node Class class Node: def __init__(self,data=None,nextNode=None): self.data = data self.nextNode = nextNode #self.min = None def get_Val(self): return self.data def get_Next(self): return self.nextNode def set_Next(self,Node): self.nextNode...
#starts and ends with {} # used to store value in key-pair format dictionary = {"key":"value"} print(dictionary["key"]) #dictionary with multiple key-value pair person = { 'name': ('Collins','Jumah'), 'age': 100, 1:100 } print('name' in person) print(person['name']) person['city'] ="Nairobi" print(perso...
#collection of different data type which is ordered and unchangeable(Immutable) # written in round brackets () # Once created its value cannot be changed, # We cannot use add, insert, remove methods coz its not modified # Methods related to tuple are: # tuple() > to create an empty tuple #count() > to count the number...
price = 50451.28 print("Euro to Bitcoin converter") while True: val_eur = float(input("Euro: ").replace(",", ".")) val_bit = val_eur / price print("{0} Euro = {1} Bitcoin".format(val_eur, val_bit)) cont = input("Continue? (Y/N)") if cont.upper() == "N": break
"""Alex's super great Battleship game. Now with 100% more unit testing!""" import string SHIP_TYPES = { 'Patrol boat': 2, 'Submarine': 3, 'Destroyer': 3, 'Battleship': 4, 'Carrier': 5 } ROW_LABELS = string.ascii_uppercase COL_LABELS = [str(col + 1) for col in range(26)] DEBUG = True class Coord...
class Reverse: def __init__(self, input_value): self.stack = [] self.reverse_word = None self.input_value = input_value def reverse_me(self): if isinstance(self.input_value, str): self.reverse_word = "" for letter in self.input_value: sel...
class Node: def __init__(self, data): self.data = data self.right = None self.left = None class BST: def __init__(self): self.root = None def add(self, data): if self.root is None: self.root = Node(data) return else: self...
from com.abc.lib.student import Student print(Student.count) s1 = Student('mehul chopra', 10, 'm', 45) # RAM (7009) -> Student object print(s1.name) print(s1.roll) ''' Internally 1. In the RAM at some random memory address (7009) it is going to reserve some space for this Student object 2. Student.__init__(7009) ''' ...
def area_rectangle(length, breadth): return length * breadth def perimeter_rectangle(length, breadth): return 2 * (length + breadth) # l1, b1 = 6, 4 # single line multi variable declaration l1 = float(input('Enter length: ')) # l1 -> '5' -> 5.0 b1 = float(input('Enter breadth: ')) # b1 -> '3' ''' print(type(l...
n = int(input('enter n: ')) # branching statements # if-else statement ''' if <<some relational or logical expression that evaluates to a True>>: I1 I2 I3 I4 else: I5 I6 I7 ''' ''' if n % 2 == 0: print('It is even number') else: print('It is odd number') ''' ''' if n % 2: prin...
from enum import Enum import sys class TokenType(Enum): INTEGER_TYPE = 0 SYMBOL_TYPE = 1 UNARY_TYPE = 2 OP_TYPE = 3 PLUS_TYPE = '+' MINUS_TYPE = '-' MUL_TYPE = '*' DIV_TYPE = '/' class Token: def __init__(self, token, line, col, tokentyp...
import tkinter as tk import os import json fpath = "player-info.json" # GUI window is a subclass of the basic tkinter Frame object class MainFrame(tk.Frame): def __init__(self, master): # Call superclass constructor tk.Frame.__init__(self, master) # Place frame into main window sel...
# dictionary: melons # key: melon name # value: list containing melon-price, and is-seedless melons = { 'Honeydew':[0.99, True], 'Crenshaw':[2.99, False], 'Crane':[2.50, False], 'Casaba':[2.50, False], 'Cantaloupe':[0.99, False] } def update_melons(dictionary_new_data): """takes a dictionary ...
list1=[] size=int(input('enter the size of the list\n')) print('enter the elements of first list\n') for i in range(size): i=int(input('enter the element')) list1.append(i) print('first list is-',list1) clonelist=list(list1) print('copied list is',clonelist)
def count(str1): count1=0 for x in str1: count1=count1+1 print('length of the string is',count1) print('enter the string whose words has to count') str1=input('enter the string') count(str1)
# Write a program where you can do the following to pre-set tuples: # 1. Sort by name # 2. Sort by age # 3. Sort by score # Name, Age, Score tom = ('Tom', 19, 80) john = ('John', 20, 90) jony1 = ('Jony', 17, 93) jony2 = ('Jony', 17, 91) json = ('Json', 21, 85) tuple_list = [tom, john, jony1, jony2, json] print(...
count = 0 limit = 4 user_input = [] for x in range(limit): user_input.append(int(input("Enter a grade value (0-100): "))) grade_list = [] for x in range(len(user_input)): grade = user_input[x] if(grade <= 100 and grade >= 90): grade_letter = "A" elif(grade <= 89 and grade >= ...
# string = "AbcDefgHijkL" # uppercase = 0 # lowercase = string - uppercase # # # for x in string: # if string[x].isupper(): # uppercase += 1 # else: # continue # ====================================== # numbers = [1,2,3,4] # double = [] # blah = [(n*2) for n in numbers if n%2 ==...
while True: i = 10 while i: t = i-5 if t: i -= 2 else: i -= 1 print("done")
i = 10 while i: i -= 1 a = 1 if a: print("hello") print("done")