text stringlengths 37 1.41M |
|---|
# https://leetcode.com/problems/second-largest-digit-in-a-string/
"""
Problem Description
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
"""
# Time Compl... |
# https://leetcode.com/problems/third-maximum-number/submissions/
"""
Problem Description
Given integer array nums, return the third maximum number in this array. If the third maximum does not exist, return the maximum number.
"""
# Time Complexity Space Complexity
# O(N) O(1)
import sys
class Solut... |
# https://leetcode.com/problems/sign-of-the-product-of-an-array/
"""
Problem Description
There is a function signFunc(x) that returns:
1 if x is positive.
-1 if x is negative.
0 if x is equal to 0.
You are given an integer array nums. Let product be the product of all values in the array nums.
"""
# Time Compl... |
################################################################################
################################################################################
################################################################################
# CLASS Vector: Represents vectors. Provides corresponding vector operations
... |
import sqlite3
# Database Declaration
db = sqlite3.connect('C:/Users/ethan/Desktop/Databases/assessment.db')
cursor = db.cursor()
# Database Declaration
# Functions
## Initial Input Of Shopper ID To Get Corresponding DB Data
def get_shopper_id(shopper_id):
# Initiate Loop
shopper_id_found = True
while s... |
class Capper(object):
"""
A capper is responsible for capping and uncapping containers, subject
to certain restrictions:
1. A capper can only contain one container at a time.
2. A capper can only cap/decap containers of a certain type.
3. A capper can only recap the same container that it unc... |
def exam_grade(score):
if score > 95:
grade = "Top Score"
elif score >= 60:
grade = "Pass"
else:
grade = "Fail"
return grade
print(exam_grade(65)) # Should be Pass
print(exam_grade(55)) # Should be Fail
print(exam_grade(60)) # Should be Pass
print(exam_grade(95)) # Should be Pass
print(exam_grad... |
import random
class Card:
def __init__(self,suit,rank):
self.rank=rank
self.suit=suit
def get_rank(self):
return self.rank
def get_suit(self):
return self.suit
class Deck:
def __init__(self):
self.cards=[]
def generate_deck(self,suits,numbe... |
#!/usr/bin/python3
import sys, pygame
from pygame.locals import *
black = (0, 0, 0)
white = (255,255,255)
red = (255,0,0)
green = (0, 255, 0)
blue = (0, 0, 255)
pygame.init()
pygame.display.set_caption("drawing") # set the title of the window
surface = pygame.display.set_mode((400, 300)) # return pygame.Surface
su... |
#!/usr/bin/python3
"""
# 通过一个对象a访问一个类变量x时: python 先在对象自身的__dict__中查找是
# 否有x,如果有则返回,否则进入对象a所属于类中的__dict__中进行查找
# 对象a试图修改一个属于类的immutable的变量,则python会在内存中为对象a
# 新建一个变量,此时a就具有了属于自己的实例变量
"""
class Student:
StudentNums = 0 # <=== 类变量,同一个类的所有对象(实例)共有,只有一份
test = 99
def __init__(self, name="", stuID=0):
... |
#!/usr/bin/python3
"""
继承(Inherit)
父类(基类,超类)
子类(派生类)
"""
class People:
def __init__(self, name="unkown", gender="x"):
self.name = name
self.gender = gender
def info(self):
print("name=%s, gender=%s" %(self.name, self.gender))
class Student(People):
def __init__(self, name="unkn... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
list0 = [1,2]
list1 = [3, 4, 5,6 ]
list2 = [4]
print("list0 is: ", end="")
print(list0)
print("list1 is: ", end="")
print(list1)
print("list2 is: ", end="")
print(list2)
print("list0 + list1 is: ", end="")
print(list0 + list1)
# error, don't define "-" operation. ask ch... |
#!/usr/bin/python3
import sys
import pygame
from pygame.locals import *
BLACK=(0,0,0)
BLUE = (0, 0, 255)
pygame.init()
surface = pygame.display.set_mode((400, 300)) # return pygame.Surface
pygame.display.set_caption("Hello") # set the title of the window
font = pygame.font.Font(None, 32)
# pygame.key.set_repeat(... |
import os
import csv
csvpath = os.path.join('budget_data.csv')
csvoutput = 'Pybank_output.txt'
total_months = []
pL = []
pL_change = []
# Skip the header labels to iterate with the values
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile)
csv_header = next(csvreader)
#print(... |
#4、判断输入字符串是否是合法的IP地址
#ipv4
def isValidIP(list):
if not list:
return False
if len(list) < 7 or len(list) > 15:
return False
i = 0
j = 0
pointNum = 0
while j < len(list):
if (ord(list[j]) >= ord('0') and ord(list[j]) <= ord('9')) \
or ord(list[j]) == ord('.'):
... |
# // 面试题6:从尾到头打印链表
# // 题目:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
class Node(object):
def __init__(self,val):
self.val = val
self.next = None
def createList(list = []):
if not list or not len(list):
return
head = Node(list[0])
cur = head
for i in range(1,len(list)):
... |
#3、数组两个数的最大差
def miunsOfMax(list):
if not list or len(list) < 2:
return None
min = list[0]
max = list[0]
for i in list:
if i < min:
min = i
if i > max:
max = i
return max - min
print(miunsOfMax([1,2,3,4,5]))
print(miunsOfMax([2,4,3,1,5]))
|
class Node(object):
def __init__(self,val):
self.val = val
self.next = None
class MyLinkQueue(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def enqueue(self,val):
if val == None:
return
node = Node(val)... |
# #// 面试题31:栈的压入、弹出序列
# #// 题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是
# #// 否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1、2、3、4、
# #// 5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列对应的一个弹出序列,但
# #// 4、3、5、1、2就不可能是该压栈序列的弹出序列。
def IsPopOrder(pPush, pPop):
if pPush == None or pPop == None:
return False
if len(pPush) != len(pPop) or (len(pPush)... |
# #// 面试题36:二叉搜索树与双向链表
# #// 题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求
# #// 不能创建任何新的结点,只能调整树中结点指针的指向。
def ConvertNode(root,last:list):
if not root:
return
ConvertNode(root.left,last)
lastNode = last[0]
root.left = lastNode
if lastNode:
lastNode.right = root
last[0] = root
Co... |
# #// 面试题8:二叉树的下一个结点
# #// 题目:给定一棵二叉树和其中的一个结点,如何找出中序遍历顺序的下一个结点?
# #// 树中的结点除了有两个分别指向左右子结点的指针以外,还有一个指向父结点的指针。
def GetNext(node):
if not node:
return
if node.right:
cur = node.right
while cur.left:
cur = cur.left
return cur
else:
if node.pa... |
# #// 面试题23:链表中环的入口结点
# #// 题目:一个链表中包含环,如何找出环的入口结点?例如,在图3.8的链表中,
# #// 环的入口结点是结点3。
def EntryNodeOfLoop(pHead):
if not pHead:
return
slow = pHead
fast = pHead.m_pNext
while slow != fast and fast != None and fast.m_pNext != None:
slow = slow.m_pNext
fast = fast.m_pNext.m_pNext
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def inorderTraversal(self, root: 'TreeNode') -> 'List[int]':
if not root:
return
cur = root
stack = [root]
l = []
... |
# 1、找树的最长路径的两个节点
#根据前序和中序,生成一颗二叉树,数组中不能有重复数字
class TreeNode(object):
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def buildTree(preOrder,interOrder,start,end,index=[0]):
if start > end:
return None
idx = index[0]
val = preOrder[idx]
... |
#Python Program to Check if a Number is Positive, Negative or Zero
class Number:
run= True
while run:
print('\n\t\t@@@Welcome In Number World@@@')
try:
num = int(input('Enter the number to check it is positive or negative:= '))
if num!=0 and num>0:
print('... |
import math
def read_grades(grade_path):
"""(file open for reading) -> NoneType
Returns a data structure containing the function's data.
"""
grade_data = []
student = []
with open(grade_path, 'r') as gradebook:
for line in gradebook:
line = line.strip()
line =... |
import cmd
from room import load_db
import textwrap
import shutil
import tempfile
print()
print('\n-_-_-WELCOME TO THE ADELPHIC HALL TEXT BASED ADVENTURE GAME!-_-_-\n')
for line in textwrap.wrap('INSTRUCTIONS: Here are the commands implimented in the ADELPHIC HALL ADVENTURE GAME that you can utilize at your discretion... |
# Dillon J. Cooper
# CS 240 Lab 05
# Exercise 1: Complete exercise 5 from chapter 13. Include part a in the
# docstring of your function. Include part d as the doctests. Turn in only the
# documented function bubble_sort.
def bubble_sort(l):
"""(list) -> NoneType
Compares every unsorted pair of elements in t... |
#!/usr/bin/python
#Sunny Shah CS260 HW7 prob2.py
import sys
graph = {1: [3, 2, 7],2: [1],3: [1, 5, 6, 8],4: [5, 7],5: [3, 4, 6],6: [3, 5, 7],7: [1, 4, 6], 8: [3]}
def BFS(graph, start):
queue = []
order = []
queue.append(start)
while(queue):
node = queue.pop(0)
if node not in order:
order.append(node)
f... |
#!/usr/bin/python
# Sunny Shah
# Problem1- Write a function called list_concat( A, B )
# that takes two Cell lists and returns a list that is the concatenation of both of them
import sys
from cell import Cell
def list_concat( A, B ) :
temp = A
while temp.next is not None:
temp = temp.next
temp.next = B
ret... |
import numpy as np
import pandas as pd
import sympy
from collections import deque
def main():
"""This program prints the number of circular primes below one million
and the list of these primes."""
primes = []
for i in range(2,1000000):
if sympy.isprime(i) and IsCircular(i):
prim... |
#coding:utf-8
from numpy import *
import time
import matplotlib.pyplot as plt
# Calculate the European distance
def euclDistance(vector1, vector2):
return sqrt(sum(power(vector2 - vector1, 2)))
# 0ρ = sqrt( (x1-x2)^2+(y1-y2)^2 ) |x| = √( x2 + y2 )
# power Calculate the second order of the list
# Initiali... |
a = int(input("Enter the first number:"))
b = int(input("Enter the second number:"))
c = int(input("Enter the third number:"))
d = int(input("Enter the fourht number:"))
e = int(input("Enter the fifth number:"))
if a > b and a > c and a > d and a > e:
print(a, "is the largest number")
elif b > a and b > c and b > ... |
name=input("Please enter your full name(without any space): ").lower()
import random
result=[]
def get_random_letter():
for i in range(3):
letter= random.choice(name)
result.append(letter)
print(result, end='')
get_random_letter()
print(random.randrange(1000, 10000))
|
import random
print("Winning Rules of the Rock paper scissor game as follows: \n"
+"Rock beats scissors \n"
+"Paper beats rock \n"
+"Scissors beat paper \n"
+"If both users choose the same ob... |
#!/usr/bin/python3
import sys
NUM_VALORES= 4 #constantes definirlas con mayusculas
if len(sys.argv) != NUM_VALORES:
sys.exit("Usage: python3 calc.py operacion operando1 operando2")
funcion= sys.argv[1]
try:
op1 = float(sys.argv[2])
op2 = float(sys.argv[3])
except ValueError:
sys.exit("Los operandos han de ser f... |
# area of circle
# radius = int(input("Enter the radius "))
# area = 3.142*radius**2
# print("Area of circle is",area)
# format method
# print("Area of Circle is {0}".format(area))
# f-string method
# print(f"Area of circle is {area}")
# IF Statement
# age = int(input("Enter your age "))
# if age > 18:
# print("Yo... |
"""
Реализуйте endpoint, с url, начинающийся с /max_number ,
в который можно будет передать список чисел, перечисленных через / .
Endpoint должен вернуть текст "Максимальное переданное число {number}",
где number, соответственно, максимальное переданное в endpoint число,
выделенное курсивом.
"""
from flask import Fla... |
import os
from tkinter import *
from tkinter import filedialog
from tkinter import font\
root = Tk()
root.title('My title!')
# Icon bitmap location uncomment and add the path to your icon
# root.iconbitmap(./your/icon/path)
root.geometry("1200x660")
# set variable for open file name
global open_status_name
open_sta... |
def range_sum(numbers, start, end):
_sum = 0
for i in numbers:
if start <= i <= end:
_sum += i
return _sum
input_numbers = [int(x) for x in input().split(" ")]
a, b = [int(x) for x in input().split(" ")]
print(range_sum(input_numbers, a, b))
|
from machine import Pin
from utime import sleep_ms
class LED():
"""Wrap an RGB LED
Defines a number of colours to display
:param red_pin: The pin the Red LED is attached to
:param green_pin: The pin the Green LED is attached to
:param blue_pin: The pin the Blue LED is attached to
"""
OFF... |
nameUser = input("Введите ваше имя: ")
m = str(input("Введите месяц рождения (пример: март): "))
d = int(input("Введите ваш день рождения (пример: 6): "))
m = m.upper()
# birthday = input()
# birthmonth = input()
if m == 'ЯНВАРЬ' and d >= 1 and d <= 20:
zodiac = "Capricorn - Козерог"
if m == 'ЯНВАРЬ' and d >= 21 a... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
my_dict={}
print (type(my_dict))
# In[5]:
my_dic=set()
print (type(my_dic))
# In[10]:
my_dic={1:2,3:4}
my_dic
my_dic={1:2,3:4,5:['abc','def'],['xyz']:6}
my_dic
# In[12]:
my_dic={1.0:2,3:4}
my_dic
# In[14]:
dic={'Name':"Ankesh",'Age':24,'sex':'Male'}
dic
... |
# -*- coding: utf-8 -*-
import sys
def recursion(current_stair):
if current_stair<0: return 0
elif current_stair<3: return 1
else:
return recursion(current_stair-5)+recursion(current_stair-3)+recursion(current_stair-1)
if __name__ == '__main__':
stairs = int(sys.argv[1])
answer = recursion... |
#!/usr/bin/env python
NUMERO = float(raw_input ("escribe un numero: "))
CUADRADO = str(NUMERO ** 2)
print " ". join (CUADRADO[::-1])
|
#!/usr/bin/python
print "es cribe un numero"
ENTRADA = float(raw_input ("> "))
NUMERO = ENTRADA % 2
if ENTRADA == 0:
print "no es nada"
elif NUMERO == 0:
print "el numero es par"
else:
print "el numero es inpar"
|
# with out argumant function
# def deatilas ():
# print("My Name is Suraj Nayak Raghuvanshi " )
# deatilas()
# with argument function
# def deatils(name,roll,standerde):
# print("student name is ",name)
# print("student roll number is",roll)
# print("student class is ",standerde)
# deati... |
# 创建图
graph = {}
# start
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
# A
graph['a'] = {}
graph['a']['end'] = 1
# B
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['end'] = 5
# end
graph['end'] = {} # 终点没有任何邻居
# 创建开销的散列表
inf = float('inf')
costs = {}
costs['a'] = 6
costs['b'] = 2
costs['end'] = ... |
def qsort(arr):
if len(arr) < 2:
return arr
pivot, arr = arr[0], arr[1:]
smaller = []
bigger = []
for i in arr:
if i <= pivot:
smaller.append(i)
else:
bigger.append(i)
return qsort(smaller) + [pivot] + qsort(bigger)
if __name__ == '__main__':
... |
""""Vücut Kitle Endeksi Bulma"""""
print("############# VÜCUT KİTLE ENDEKSİ HESAPLAMA #############")
print("Boyunuzu Giriniz!")
a = int(input("Boy (cm) : "))
print("Kilonuzu Giriniz!")
b = int(input("Kilo (kg) : "))
print("Vücut Kitle Endeksi Hesaplanıyor...")
vc = b /((a/100) ** 2)
vc=round(vc,1)
print("Vucüt Kitle E... |
# Problem Set 4A
# Name: Margo
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for this part. Non-recu... |
s = ''.join(sorted(input()))
n = ''.join(sorted(input(),reverse=True))
if s < n:
print('Yes')
else:
print('No') |
# while 迴圈
n=1
while n<=3:
print (n)
n+=1
# 1+2+3+...+10
n=1
sum= 0 # 用來記綠累加的結果
while n<=10:
sum=sum+n
n+=1
print (sum)
# for 迴圈
for x in [3,5,1]:
print (x)
for x in "Hello":
print (x)
for x in range(5):
print (x)
for x in range(5,10):
print (x)
# 1+2+3+...+10
sum=0
for x in ra... |
num1=1.65646
num2=20.6545354
print('first Number is = {0:.3} Second Number is ={1:.3F}'.format(num1,num2))
# In more Simple Way
print(f'First Number is = {num1:.3} , second number is = {num2:.3f}')
|
def display_player(myDic):
for key,val in myDic.items():
print(f'I am {key} with {val} belt color')
def belt_count(myDic):
belts=list(myDic.values())
print(set(belts))
for belt in set(belts):
count=belts.count(belt)
print(f'{count} {belt} belt')
myDic={}
while True:
key=input("enter name of the n... |
# based on https://stackoverflow.com/questions/52491656/extracting-images-from-presentation-file
import click
import context
from pathlib import Path
from convert_lib.core_funs import Extract_Pics, extract_it
@click.command()
@click.argument("pptx_file", type=str, nargs=1)
@click.argument("media_directory", type=str, ... |
# try out elapsed time output
import time
startTime = time.time()
time.sleep(1)
elapsed = (time.time() - startTime)
print("Time taken: " + str(elapsed) + " seconds")
elapsed = 4650.13599992
elapsedTime = time.localtime( elapsed )
print ( time.asctime( elapsedTime ) )
dateTimeFormat = '%H hours... |
def find_treasure(t_map, row, col, curr_steps, min_steps):
if row >= len(t_map) or row < 0 or col >= len(t_map[0]) or col < 0 or t_map[row][col] == 'D' or t_map[row][col] == '#':
return None, min_steps
if t_map[row][col] == 'X':
curr_steps += 1
if min_steps > curr_steps:
min... |
wordsFile = open ("words.txt")
wordsList = wordsFile.readlines()
wordsList.reverse()
for i in wordsList:
print i.strip()
|
for i in range(int(input())):
line = input().split()
for item in line:
if "machula" in item:
pos = line.index(item)
if pos == 0:
line[2], line[4] = int(line[2]), int(line[4])
print("{} + {} = {}".format(line[4] - line [2], line[2], line[4]))
elif pos == 2:
lin... |
import math
B = float(input("Base do retângulo: "))
A = float(input("Altura do retângulo: "))
area = B * A
print(f"AREA = {area:.4f}")
per = B + B + A + A
print(f"PERIMETRO = {per:.4f}")
diag = math.sqrt(B ** 2 + A ** 2)
print(f"DIAGONAL = {diag:.4f}") |
from collections import deque
from .offer07 import Solution
def tree_to_list(root):
if root is None:
return []
results = []
q = deque()
q.append(root)
while q:
n = len(q)
new_node = 0
while n > 0:
n -= 1
node = q.popleft()
... |
from comparable import Comparable
from date import Date
class Person(Comparable):
"""
This class is immutable and inherits from Comparable
It uses composition by having a Date object for birthday
Please code this using private instance variables.
Each instance variable should have a getter, but no ... |
l_1-20 = len("onetwothreefourfivesixseveneightnineteneleventwelvethirteenfourteensixteenseventeeneighteennineteentwenty")
print(l_1-20)
for x in range(1,21):
if x == 1:
suma += len("one")
if x == 2:
suma += len("two")
if x == 3:
suma += len("three")
if x == 4:
... |
#variable strings and numbers
#basics in strings
#1.---uppercase,title,lower-----
# name="python"
# name=input("Enter Your Name ")
# print(name.upper())
# print(name.title())
# print(name.lower())
#2.Concatenation
# first="saravanan"
# last="adithiya"
# fullname= first+" "+last
# print(fullname)
#3... |
def addition(x, y):
return x+y
def add_arr(arr):
s = 0
for a in arr:
s+=a
return s
print(addition(2,3))
print(add_arr([1,2,3,4,5]))
|
a= int(input())
b= int(input())
c= int(input())
if a*b==c:
print("yes")
else:
print("no")
|
graph = {
1: {
2: 15,
3: 8
},
2: {
3: 3,
4: 2
},
3: {
2: 5,
4: 7,
5: 9
},
4: {
5: 9
},
5: {
4: 12
}
}
vertexes = [1, 2, 3, 4, 5]
start_vertex_input = int(input("Entire desired start ve... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 09:13:06 2021
@author: bing
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 16:20:18 2021
@author: bing
"""
class Node():
def __init__(self, num_lst):
self.numbers = num_lst
def set_numb... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 19 16:14:38 2016
@author: zhengzhang
"""
import dice_student
import math
import matplotlib.pyplot as plt
# import random_walk_helper
class Walker:
def __init__(self, directions=4, num_steps=10):
self.dice = dice_student.Dice(directions)
self.num_step... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 19:27:55 2020
@author: xg7
"""
##Problem 2
## 2.1
def pick_out_alphabets(s, idxes):
##-- You can modify the following code and --##
##-- please insert your code here --##
output = []
for idx in idxes:
output.append(s[id... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 7 11:09:16 2020
@author: xg7
"""
def int_to_hexa(int_code):
##modified the following to the tests
hex = "0123456789ABCDEF"
result = ""
while int_code:
result = hex[int_code % 16] + result
int_code //= 16
return ... |
import copy
def crossBridge(nums, crossed=[], currentTimeSpent=0, minTime=[float("inf")], path=[]):
'''
Parameters
----------
nums : list
number of people haven't crossed the bridge.
crossed : list
DESCRIPTION. people crossed the bridgeThe default is [].
currentTimeSpent : in... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 6 11:14:13 2019
@author: xg7
"""
class Bucketsort:
def __init__(self, sizeBucket):
self.sizeBucket = sizeBucket
self.buckets = {}
self.data = None
def _distributeElementsIntoBuckets(self):
"""
... |
class Person:
_object_set = set()
@property
def object_set():
return _object_set[:]
@property
def name(self):
return self._name
@name.setter
def name(self, value):
if isinstance(value, str):
self._name = value
@property
def birt... |
# Self Driving Car
# Importing the libraries
import numpy as np
from random import random, randint
import matplotlib.pyplot as plt
import time
import math
# Importing the Kivy packages
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellip... |
def make_bricks(small, big, goal):
if small + big*5 >= goal:
if (goal % 5 - small) > 0:
return False
else:
return True
else:
return False
|
def sum13(nums):
new_list = nums
while 13 in new_list:
if new_list[-1] == 13:
del new_list[-1]
else:
del new_list[new_list.index(13)+1], new_list[new_list.index(13)]
return sum(new_list)
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
name = "hello People, i am ratan"
print(name[-2:-8:-1])
first ="python"
second ="anaconda"
join = first + second
print(join)
alist = [10,10,30,40]
blist = ["unix","scala","spark","hadoop"]
#clist = [10,20,"unix,"scala",4000,56.44]
prin... |
# This is the class of the input root. Do not edit it.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def branchSums(root):
'''
Write a function that takes in a Binary Tree and returns a list of its branch sums ordered from leftmo... |
#taking input
age = int(input("Enter age of lily:"))
price = float(input("Enter price of a toy:"))
machine = float(input("Enter price of washing machine:"))
toys = 0 # counter to count toys
toys = int(toys)
for i in range(1, age+1, 2):
toys += 1
FT = toys*price #calculating price of toys
money = 0
#calculating do... |
val = 0
current_unit = 0
unit_convert = 0
result = 0
# input
val = float(input("Enter value for conversion :"))
current_unit = input("Enter unit of current value :")
unit_convert = input("Enter desired unit :")
# performing calculation
if unit_convert == 'kg' and current_unit == 'g':
result = val / 1000
if unit_... |
discount_overall = 0
discount = 0
# input
red = int(input("Enter number of red roses purchased: "))
white = int(input("Enter number of white roses purchased: "))
tulips = int(input("Enter number of tulips purchased: "))
season = input("Enter which season it is :")
holiday = input("is it holiday today??")
# calculatin... |
# list
numbers = []
count = 0
count = int(count)
# taking input
while count != 24:
numbers.append(input("Enter number : "))
count += 1
for i in range(0, len(numbers)):
if int(numbers[i])%2 != 0 and int(numbers[i])%5 == 0:
print(numbers[i])
|
# list
list1 = ["ali", "", "khan", "ahmend", "", "Tanveer", ""]
list2 = []
count = 0
count = int(count)
# copying list 1 int list 2
for i in range(0, len(list1)):
if list1[i] != "":
list2.append(list1[i])
count += 1
print(list2) |
# taking input
num_1 = int(input("Enter First Number :"))
num_2 = int(input("Enter Second Number :"))
num_3 = int(input("Enter third Number :"))
num_4 = int(input("Enter Fourth Number :"))
num_5 = int(input("Enter Fifth Number :"))
num_6 = int(input("Enter Sixth Number :"))
num_7 = int(input("Enter Seventh Number :"))
... |
# -*- coding:utf-8 -*-
import types
class Employee(object):
def __init__(self, username, age):
self.username = username
self.age = age
def __getattribute__(self, attr):
return super(Employee, self).__getattribute__(attr)
def __getitem__(self, attr):
return super(E... |
# -*- coding:UTF-8 -*-
from string import Template
def format(**args):
tmpl = 'My name is %(username)s, age is %(age)d!'
return str(tmpl % args)
def format_2(**args):
tmpl = 'My name is ${username}, age is ${age}!'
#tmpl = 'select * from user where username = ${username} and password = ${password... |
import random
wbank = ['u','r','a','butt','i','am','the','boy','we','like','to','scream','u','r','a','butt','i','am','the','boy','we','like','to','scream','u','r','a','butt','i','am','the','boy','we','like','to','scream']
ccap = 10 #have this be a user inputted variable.
def sentencegen (words,hardcap): #tak... |
import unittest
from advanced_oop import Rectangle, Triangle, Circle
class Test(unittest.TestCase):
r1 = Rectangle(10, 10)
t = Triangle(10, 10)
c = Circle(10)
def test_common_color(self):
self.assertEqual(self.r1.show_color(), 'Black')
self.assertEqual(self.t.sh... |
import math
# Base class.
class Shape():
def __init__(self):
# Initialization for each class prints that a new shape has been created.
print("You created a shape!")
# All classes below call upon the otherwise meaningless Shape class.
class Circle(Shape):
# Each shape re... |
a = {1:'eins', 2:'zwei'}
print(f"This is very crappy code. It does not look good. Lorem Ipsum. I'm running out of words here. What is this? It's a {a[1]}!!!!")
for i in a:
if True:
print(
i
)
print('REVIEW ME')
print('REVIEW ME TOO') |
#!/usr/bin/python
from math import *
print "Introduzca un numero: "
num = int (raw_input());
mitad = num / 2;
if ((mitad % 2) == 1):
print "El numero introducido es el doble de un numero impar"
print "\n"
|
#!/usr/bin/python
#!encoding: UTF-8
#Para la primera combinación
for i in range(1,4):
if (i == 1):
print "El valor de i es", i
print "y ejecuto la sentencia stmt1"
elif (i == 2):
print "El valor de i es", i
print "y ejecuto la sentencia stmt2"
elif (i == 3):
print "El valor de i es", i
print "y ejecuto ... |
#!/usr/bin/python
print "Introduzca un numero: "
a = int (raw_input());
print "Introduzca otro numero: "
b = int (raw_input());
tmp = a
a = b
b = tmp
print "El valor de la primera variable es", a, "y el de la segunda es", b
print "\n"
|
#!/usr/bin/python
from math import *
print "Introduzca la cantidad de euros: "
euros = float (raw_input());
print "Introduzca la tasa de interes: "
tasa = float (raw_input());
print "Introduzca el n de anios: "
anios = float (raw_input());
interes = euros * ((tasa / 100.0) * anios);
capital = euros + interes
print "E... |
#!/usr/bin/python
#!encoding: UTF-8
from math import *
print "Introduzca la cantidad de euros: "
euros = int (raw_input());
bil500 = euros / 500;
euros = euros % 500;
bil200 = euros / 200;
euros = euros % 200;
bil100 = euros / 100;
euros = euros % 100;
bil50 = euros / 50;
euros = euros % 50;
bil20 = euros / 20;
euros... |
#!/usr/bin/python
from math import *
print "Introduzca el valor del producto: "
precio = float (raw_input());
pvp = precio + (precio * (21.0 / 100.0));
print "El valor total del precio %.2f es %.2f" % (precio, pvp)
print "\n"
|
# sum_numbers1.py
#
# ICS 32A Fall 2019
# Code Example
#
# This function sums the numbers in a flat list of integers. By "flat list",
# I mean that the list no sublists (i.e., every element is an integer).
def sum_numbers(numlist: [int]) -> int:
'''Adds up the integers in a list of integers'''
total = 0
... |
r = range(1,10)
index = 0
total = 0
while index < len(r):
total += r[index]
index += 1
print('The sum is', total)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.