text stringlengths 5 121k |
|---|
lst1 = [6,9,3,5,7]
lst2 = [9,6,4,2,0,7,2]
print("lst1=",lst1)
print("lst2=",lst2)
a = len(lst1)
b = len(lst2)
if a == b:
print("SAME LENGTH")
else:
print("NOT SAME LENGTH")
s1 = sum(lst1)
s2 = sum(lst2)
if s1 == s2:
print("SUM IS SAME")
else:
print("SUM IS NOT SAME")
lst1 = set(lst1)
lst2 = s... |
newFile = open("text.txt","a")
newFile.write("Python programming…! \n")
newFile.close()
readFile = open("text.txt","r")
print(readFile.readlines())
readFile.close()
|
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
from keras import backend as K
(X_train, y_train), (X_test, y... |
__author__ = 'ElevenVan'
print(range(5))
lists= list(range(5))
print(lists)
|
from unittest import TestCase
from palindrome import palindrome
class PalindromeTests(TestCase):
def test_even(self):
self.assertTrue(palindrome("toot"))
def test_odd(self):
self.assertTrue(palindrome("tot"))
def test_simple(self):
self.assertTrue(palindrome("stunt nuts"))
... |
import pandas as pd
df = pd.read_csv("iris.data")
df.shape()
df.head()
'''
Entire table is a data frame and
The basics of indexing are as follows:
Operation Syntax Result
Select column df[col] Series
Select row by label df.loc[lab... |
values=[]
op=[]
def opt(a1,a2,opp):
if opp=='+':
return a1 + a2
if opp=='-':
return a1 - a2
if opp=='*':
return a1 * a2
if opp=='/':
return a1//a2
def check(op):
if op in ('+','-'):
return 1
elif op in ('*','/'):
return 2
else:
return 0
braces=['(','{','[']
braces1=[']','}',')']
... |
def main():
print("Greetings! \nPlease make use of my contact book by completing the following steps: \na) Add three new contacts using the following format: Name : Number \nb) Make sure your contacts have been arranged in alphebetical order.\nc) Delete a contact.\nd) Search for an existing contact.")
... |
"""
Please calculate the first n numbers of a fibonacci series.
n = 8
0,1,1,2,3,5,8,13
"""
def fibonacci(n):
if(n == 1):
return 1
if(n == 0):
return 0
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(7)) |
import sys
import binascii
data = binascii.unhexlify(sys.stdin.read().strip())
output = []
for byte in data:
bits = format(byte, '0>8b')
for c in bits:
if c == '0':
output.append('01')
elif c == '1':
output.append('10')
else:
assert(False)
prin... |
zhang = ["张三", 18, "man"]
lisi = ["李四", 28, "female"]
laowu = ["老五", 34, "gay"]
feiwu = ["废物", 189, "freak"]
Lu = [zhang, lisi, laowu, feiwu]
def Creat_NewName():
New_One = []
newname = input("新的名字:")
New_One.append(newname)
newage = int(input("年龄:"))
New_One.append(newage)
newsex = input... |
"""
2.4 Partition
Write code to a parttion a linked list around a value x, such that all nodes
less than x come before all nodes greater than or equal to x.
If x is contained within the list, the values of x only need to be
after the elements less than x.
The partition element x can appear anywhere in the "right pa... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_excel('apartment_prices.xlsx')
print(df.head())
price = df['Price']
size = df['m2']
Property = df['Property']
apartments = [100, 110, 120, 130, 140, 150]
mean_size = round(np.mean(size), 4)
mean_price = round(np.mean(price), 4)
... |
Y = (lambda g: (lambda x: g(x(x)))(lambda x: g(x(x))))
Z = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))
G = (lambda r: (lambda n: 1 if n == 0 else n * (r(n - 1))))
factorial = (lambda f: (lambda x: f(lambda v: x(x)(v)))(lambda x: f(lambda v: x(x)(v))))(
lambda r: ... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return head
if k... |
class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
if not A:
return 0
bpUp = [1 for _ in range(len(A))]
bpDown = [1 for _ in range(len(A))]
result = 0
for i in range(1, len(A)):
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
seq = [root]
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
self.currentMaxDepth = 0
... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
cur = head
root = ListN... |
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
if not pushed or not popped:
return True
stack = [pushed.pop(0)]
while pu... |
class Solution(object):
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
class TreeNode(object):
def __init__(self, char, isWord = False):
self.char = char
self.isWord ... |
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
result = 0
negative = x < 0
if negative:
x = -x
while x > 0:
result = result * 10 + x % 10
x = x // 10
if negative:
result... |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
s = s[::-1]
words = s.split()[::-1]
result = ""
for word in words:
result += word + " "
return result.strip()
s = Solution()
print(s.reverseW... |
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
s = s.replace(" ", "")
tmp = s.split("+")
result = 0
for str in tmp:
t = str.split("-")
re = None
for str2 in t:
sta... |
class Solution:
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0;
s = Solution()
print(s.canWinNim(5)) |
class Solution(object):
def findLength(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
if not A or not B:
return 0
result = 0
board = [[0 for _ in range(len(B)+1)] for _ in range(len(A)+1)]
for i in range(1... |
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
array1 = [1] * length
for i, num in enumerate(nums[:-1]):
array1[i+1] = array1[i] * num
right = 1
for ... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
start = head
end = head
while end.next:
... |
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
return pow(x, n)
s = Solution()
print(s.myPow(2, 10)) |
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
if not indexes:
return S
if not S:
... |
getal1 = 1
getal2 = 2
getal3 = 3
def som(*x):
return sum(x)
print(som(getal1,getal2,getal3)) |
uren = float(input('Hoeveel uren heb je gemaakt? ' ))
loon = float(input('Hoeveel verdien je per uur?'))
print(uren,'uur werken levert',(uren*loon),'euro op') |
def make_shirt(size, message):
print("The size of shirt is "+size.upper()+".")
print("The message printed on the shirt is "+message+".\n")
make_shirt('XL','sunshine on the beach')
make_shirt(size = 'XL',message = 'sunshine on the beach')
def make_shirt(size = 'large',message = 'I love python'):
print("... |
'''Consider this puzzle: by starting from the number 1 and repeatedly
either adding 5 or multiplying by 3, an infinite amount of new numbers
can be produced. How would you write a function that, given a num-
ber, tries to find a sequence of such additions and multiplications that
produce that number? For example, the n... |
number=int(input("Enter the number: "))
if number%3==0 and number%5==0:
print("Consultadd - Python Training")
elif number%5==0:
print("Python Training")
elif number%3==0:
print("Consultadd")
else:
print("u are worng")
|
row = 0
while row < 5:
col = 0
while col < 5:
print("*", end="")
col += 1
row += 1
print()
|
from yahoo_finance import Share
import pandas as pd
import os
""" A collection of functions to gather and perform basic processing on historical
stock data from Yahoo. Uses Pandas dataframes objects to organize data
"""
def generate_csv(symbol, start_date, end_date, file_name=''):
""" Generates a csv of historica... |
'''
lists = [9, 2, 4, 7, 75, 33, 64, 1, 445]
def bubble_sort(lists):
# 冒泡
count = len(lists)
for i in range(0, count):
for j in range(i + 1, count):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
return lists
print(bubble_sort(lists))
print(dir(b... |
import math
import os
import random
import re
import sys
def hourglassSum(arr):
max_sum = -63
for i in [0, 1, 2, 3]:
first_row = arr[i]
second_row = arr[i + 1]
third_row = arr[i + 2]
for j in [0, 1, 2, 3]:
first_sum = first_row[j] + first_row[j+1] + first_row[j+2... |
__author__ = 'yunge'
'''
Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:
All elements < k are moved to the left
All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.
Example
If nums = [3,2,2,... |
def greet():
print("hello")
greet()
def add1(x,y):
z=x+y
print(z)
add1(2,3)
def add2(b,c,a=12):
print(a+b+c)
add2(5,5)
def read(*n):
for x in n:
print(x)
read(1,2,3)
"""def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
r=fact(5)
p... |
class Magazine:
def __init__(self, Author, Viewers, Cost, Name):
self.Author = Author
self.Viewers = Viewers
self.Cost = Cost
self.Name = Name
class publishingHouse:
def __init__(self, magazineCollection):
self.magazineCollection = magazineCollection
def findMinimu... |
"""
Github link: https://github.com/Hoanganh270400/CP1404-practicals
"""
from taxi import Taxi
def main():
taxi = Taxi("Prius 1", 100)
taxi.drive(40)
print(taxi.__str__())
print("Taxi's current fare: {}".format(taxi.get_fare()))
taxi.start_fare()
taxi.drive(100)
print("Taxi detail - Name: ... |
list = []
number_1 = int(input("Number: "))
list.append(number_1)
number_2 = int(input("Number: "))
list.append(number_2)
number_3 = int(input("Number: "))
list.append(number_3)
number_4 = int(input("Number: "))
list.append(number_4)
number_5 = int(input("Number: "))
list.append(number_5)
print("The first ... |
import re
import string
import random
class PasswordGenerator:
def __init__(self, charset, length):
self.charset = charset
self.length = int(length)
self.charset_arr = []
self.password = []
def set_charset(self):
if re.search('u',self.charset) o... |
import math
name = "Eugene"
print("Hello World", name)
year = 2020
print("Today is", year, "year.")
a=5; b=3
r = a + b
print ("a =", a,"b =", b, ": a + b =", r)
if ( a>b ):
print ("a>b")
else:
print ("a<=b")
print("Чай")
text = input("введите текст:")
print("текст =", text)
pi = math.acos(-1)
print("Число ПИ ... |
with open('inputFile.txt', 'r') as inStr, open('outputFile.txt', 'w') as outStr:
sentence = inStr.read()
sentence = sentence.split()
adjective = input('Enter an adjective: ')
noun1 = input('Enter a noun: ')
verb = input('Enter a verb: ')
noun2 = input('Enter an noun: ')
for... |
'''
Read in text from a .zip file in JSON
and convert it to a table in Postgres.
'''
import sys
import os
import zipfile
import json
import pandas as pd
from pandas.io.json import json_normalize
import sqlalchemy
from sqlalchemy import create_engine
import summary_stats
'''
Reads in JSON files from input_path
and ... |
from pathlib import Path
from pytube import YouTube
list = []
print("Enter URLs (terminate = 'STOP')")
while True:
url = input("")
if url == "STOP":
break
list.append(url)
for link in list:
video = YouTube(link)
for stream in video.streams:
print(stream)
num = input("\nplease... |
data = ['ram', 'sita', 2342, 'hari', 34.5]
print(dir(data))
|
with open("text.txt") as file:
print(file.read() + "\n")
class TranslationResource(object):
def __init__(self, text):
self.open = True
self.text = text
def french(self):
self.request_translation()
return "Bonjour"
def spanish(self):
self.request_transla... |
def my_generator(x):
for i in range(x):
yield i
print(next(my_generator(10)))
print()
for i in my_generator(10):
print(i)
print()
try:
my_string = "Hi"
iterator = iter(my_string)
print(next(iterator))
print(next(iterator))
print(next(iterator))
except:
print("No more el... |
languages = ["java", "javascript", "typescript", "python", "csharp"]
for index, language in enumerate(languages):
print(index, language)
print()
starting_index = 1
for index, language in enumerate(languages, starting_index):
print(index, language)
print()
language_tuple = list(enumerate(languages, starting... |
list = ['blue','orange','green']
print(list)
new = input('mau moi: ')
list.append(new)
print(list)
vt = int(input('nhap vi tri muon xem:'))
print(list[vt-1]) |
import random
count = 0
while True:
num1 = random.randint(1,30)
num2 = random.randint(1,15)
saiso = random.randint(-3,3)
sum = num1 + num2 + saiso
print("{} + {} = {}".format(num1, num2, sum))
ans = input("T or F?").lower()
if saiso == 0:
if ans == "t":
print("Correct"... |
sach = {
'name':'dragon ball',
'year':'2014',
'char':'Son Goku, Picollo, Gohan,...'
}
sach['conutry'] = 'Japan'
print(sach)
for x in sach:
print(x,'-',sach[x])
sach['name'] = 'a'
sach['year'] = 1999
sach['char'] = ['b', 'f', 'r']
sach['country'] = 'c'
print(sach)
print(sach['char'][1])
for x i... |
"""
Copy paste these instructions in there. (copy out everything highlighted)
Look through the "links" variable and see if you can find some image covers.
Edit Proj_01_08 to make the loop in proj_01_08 print out the path to the images for all of the book cover thumb images.
"""
import requests
from bs4 import Beautifu... |
def diagonalDifference(arr):
n = len(arr)
left_diagonal_sum = 0
right_diagonal_sum = 0
for i in range(0, n):
left_diagonal_sum += arr[i][i]
right_diagonal_sum += arr[i][n-1-i]
return abs(left_diagonal_sum - right_diagonal_sum)
|
def checkMembership(M, data):
for i in range(0, len(M)):
for j in range(0, len(M[0])):
if (M[i][j] == data):
return (i, j)
m1 = [[0,1,2,3], [4,5,6,7], [8,9,10,11], [12,13,14,15]]
print(checkMembership(m1, 4))
print(4 in m1) |
import random
def get_gess():
return list(input("What is your GUESS ?"))
def generates_code():
digits=[str(num) for num in range(10) ]
random.shuffle
return digits[:4]
def generate_clues(code,user_guess):
if user_guess == code:
return " CODE CRACKED"
clues=[]
for ind... |
"""
IO common functions
"""
__all__ = ['bufcount', 'ensdir', 'ensfile', 'remove_file']
import os
import os.path
def bufcount(filename):
"""
Counts the number of lines in a file quickly.
Code from (with minor change):
http://stackoverflow.com/questions/
845058/how-to-get-line-c... |
""""
Common operations and queries regarding a numbers' digits.
These are largely imported from various project euler problems.
"""
from math import floor, log10
def filter_numbers_with_digits(numbers, good_digits):
"""
Returns a new list w/numbers that only have digits in good_digits.
For e... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelEncoder_X = LabelEncoder()
X[:, 3] = labelEncoder_X.fit_trans... |
def sumList(list):
'''
objective: to compute sum of list
input parameters:
list: consist of elemnts of which sum has to be found
return value: sum of elements of list
'''
if list == []:
return 0
else:
return(list[0]+sumList(list[1:]))
prin... |
import time
import board
import busio
import adafruit_si7021
import RPi.GPIO as GPIO
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_si7021.SI7021(busio.I2C(board.SCL, board.SDA))
reading = 0
pin_to_circuit = 4
def rc_time(pin_to_circuit):
count = 0
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(... |
import random
def run():
print("********************************")
print("** Welcome to Guess-a-Number! **")
print("********************************")
print("")
points = 1000
lost_points = 0
total_tries = 0
secret_number = random.randint(1, 100)
print("Set the ... |
import random;
player = input("Choose")
player = player.lower()
print ("your choice:" + player)
computerChoice = random.randint(0,2)
if computerChoice == 0:
computer = "rock"
print("computer choose:Rock")
elif computerChoice == 1:
computer = "paper"
print("computer choose:Paper")
elif computerChoice ==... |
import string
import random
def rs_generator(string_size=12, alphanumeric_characters=string.ascii_lowercase + string.digits):
return ''.join(random.SystemRandom().choice(alphanumeric_characters) for _ in range(string_size))
print(rs_generator(6))
|
def square(x):
return x*x
def main():
for i in range(10):
print(f"{i} time {i} is {square(i)}")
if __name__=="main":
main()
|
def hello():
return "Hello, World!"
def add(num, number):
return num + number
nums = add(3,4)
print(nums)
def ran(num, number=10):
return num + number
nums = ran(3)
print(nums)
def m_num(a,b):
return a-b
a=3
b=4
minus = m_num(b,a)
|
ss_list=[5,7,300,90,24,50,75]
print("Hello, my name is Hiep and these are my sheep sizes")
print(ss_list)
print("Now my biggest sheep has size", max (ss_list), "let's shear it")
ss_list.remove(max(ss_list))
print("After shearing, here is my flock")
print(ss_list)
for i in range (1,5):
print(i, "month(s) has passe... |
"""
Created on Tue Feb 18 11:17:23 2020
@author: cherryb
"""
import random
nBox = 50
n = 1000
scoreLoyal = 0
scoreSwap = 0
for i in range(n):
listBox = []
listBox = list(range(1, nBox+1))
ferrariBox = random.choice(listBox)
chosenBox = random.choice(listBox)
if... |
def evenFibSum(N):
nextval = 0
sum = 0
plist = [0,1]
while(nextval<N) :
plist.append((plist[-2]+plist[-1]))
nextval = plist[-1]
if (nextval % 2 ==0) : sum += nextval
return sum
print(evenFibSum(100))
|
import RPi.GPIO as GPIO
class gpio():
def _init_(self):
pass
def init_gpio(self,num,flag):
self.num=num
GPIO.setmode(GPIO.BOARD)
if flag == 1:
GPIO.setup(num,GPIO.OUT)
elif flag == 0:
GPIO.setup(num,GPIO.IN)
def gpio_high(s... |
def main():
print("this is the functions.py file ")
for i in inclusive_range():
print(i)
def inclusive_range(*args):
numargs = len(args)
if numargs < 1: raise TypeError('required atleast one argument')
elif numargs == 1:
stop = args[0]
start = 0
step = 1
elif numargs == 2:
(start, stop) = args
step ... |
fh = open('lines.txt')
for line in fh.readlines():
print(line)
|
'''This is an example of processing file and using the csv module to extract data from it.'''
import csv
import os
DATAFILE = "745090.csv"
def parse_file(datafile):
name = ""
data = []
with open(datafile, 'rb') as f:
'''method #1
source = f.readline().split(",")
name = sou... |
import os
import requests
import argparse
def getProperUrlFormat(sitename):
if 'http://' not in sitename and 'https://' not in sitename:
url = 'https://{}'.format(sitename)
else:
url = sitename
url = url.replace('http://','https://')
return url
def check_if_robots_sitemap_exists(url):
robots_url = '{}/robot... |
from Library.task import Task
class Section:
def __init__(self, name):
self.name = name
self.tasks = []
def add_task(self, task: Task):
if task in self.tasks:
return f"Task is already in the section {self.name}"
self.tasks.append(task)
return f"Task {task.... |
import time
def decorator(func):
def wrapper(*args,**kw):
print(time.time())
func(*args,**kw)
return wrapper
@decorator
def f1(func_name):
print('this is a function ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('this is a function ' + func_name1)
pr... |
from math import *
print("The analytical integral of e^x from -1 to 1 is:", (exp(1)-exp(-1)))
print("Input the max number of rectangles")
N=int(input())
def eee(x):
return exp(x)
Areas=[]
AreasE=[]
for i in range(5,N):
Area=0
for k in range(i):
Area+=eee(-1+2/i*k)*2/i
Areas.append(Ar... |
"""
Created on Fri Feb 8 20:18:20 2019
@author: chenna
"""
import numpy as np
import matplotlib.pyplot as plt
n=np.linspace(0,200,200)
x=5*np.sin(2*np.pi*n)
fig=plt.figure()
ax1=fig.add_subplot(3,1,1)
ax2=fig.add_subplot(3,1,2)
ax3=fig.add_subplot(3,1,3)
no=np.sin(2*np.pi*6000*n)
x1=x+no
p=input("Order of the syst... |
import socket
import sys
import ipaddress
def scan_host(ip_addr, start_port, end_port):
print('[*] Starting TCP port scan on host %s' % ip_addr)
tcp_scan(ip_addr, start_port, end_port)
print('[+] TCP scan on host %s complete' % ip_addr)
def scan_range(network, start_port, end_port):
... |
first_number = input('first name: ')
secound_number = input('second name: ')
bsa = first_number + secound_number
print(f'welcome to our B.S.A {bsa} ')
|
import time
import os
count_mins = int(input('How much time do you need? '))
sec=0
mins=0
while sec<=60:
os.system('clear')
print(f'{mins} minutes {sec} seconds')
time.sleep(1)
sec+=1
if sec==60:
mins+=1
sec=0
if mins == count_mins:
print('Stop the clock!')
... |
name = "Amit Sinha"
age = 40
height = 160
weight = 170
eyes = "black"
color = "brown"
print("lets talk about %r." % name)
print("he is %s inch tall." % ( round(height/2.54, 2)))
print("He is %r kg heavy." % weight)
print("Ohh, He is too heavy")
print("He is got %r eyes and %r color." % (eyes, color))
print("If I ... |
from sys import argv
script, first, second, third = argv
print( "The script is called:", script )
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
age = input("put input your age]")
print("your age is", age)
|
import socket
host = 'localhost'
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
print("The sever is listening for client request on port ", port)
connection, address = s.accept()
print("Connection has been established from ", str(address))
try:
fileNam... |
import socket
host = 'localhost'
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
print("The sever is listening for client request on port ", port)
connection, address = s.accept()
print("Connection has been established from ", str(address))
connection.send(... |
class LengthConversion:
value = {"mm": 0.001, "cm": 0.01, "m": 1, "km": 1000, "inch": 0.0254,
"ft": 0.3048, "yd": 0.9144, "mi": 1609.344}
def convertToMetres(self):
return self.x * LengthConversion.value[self.valueUnit]
def __init__(self, x, valueUnit="m"):
self.x = x
... |
def removeKFromList(l, k):
i = 0
j = 0
b = []
print(l)
while i < len(l):
if l[i] == k:
b.append(i)
i = i + 1
while j < len(b):
del l[b[j]]
j = j + 1
return l
l = [3, 1, 2, 3, 4, 5]
k = 3
removeKFromList(l, k) |
def find_min_cost(x, y, s):
cost = 0
prev = ''
start = 0
for i in range(0, len(s)):
if s[i] != '?':
start = i
prev = s[i]
break
for i in range(start+1, len(s)):
current = s[i]
if current == '?':
continue
... |
div=int(input("Enter dividend: "))
divs=int(input("Enter divisor: "))
try:
assert divs!=0, "You can not divide by zero"
quo=div/divs
print(f"Result: {quo}")
except:
print("You should not try to divide by zero")
|
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
ATAQUE DOS
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
from scapy.all import *
src = raw_input("Introduce la IP atacante: ")
victima = raw_input("Introduce l... |
def input_member(input_file):
while True:
inName = input('멤버를 입력하세요.(종료는 q) : ')
if inName.lower() == 'q':
break
else:
with open(input_file, 'a', encoding='utf-8') as i: i.write(inName+'\n')
print('저장되었습니다.')
def output_member(output_file):
with open(output... |
a = 1
while a <= 10:
print(a,end='\t')
a += 1
x=0
while x<10:
x+=1
if x % 2 ==0:
continue
print(x)
while True:
print('반복시작')
answer = input('끝내려면 x')
if answer == 'x':
break
print('반복종료') |
from random import randint
def gbb_game(you_n):
com_n = randint(1,3)
if com_n-you_n ==1 or com_n-you_n ==-2:
result = 1
elif com_n-you_n == 0:
result = 2
elif you_n>3 or you_n<0:
print('다시입력')
return
else:
result = 3
return result,com_n
def input_num... |
def main():
print('The program calculates the average length of words in a sentence.')
sentence = input('Enter a sentence: ').rstrip()
words = sentence.split()
average = (len(sentence) - (len(words) - 1)) / len(words)
print('Your average length of words is {0:.2f}.'... |
from random import randrange
def main():
print('This program simulates random walk inside a side walk')
n = int(input('How long is the side walk? '))
squares = [0]*n
results = doTheWalk(squares)
print(squares)
def doTheWalk(squares):
n = len(squares)
pos = n // 2
while pos >= 0 ... |
def main(aList):
newList = []
for i in range(len(aList)):
if aList[i] not in newList:
newList.append(aList[i])
return newList
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.