text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
ramp.py
This script generates the image that creates the Mach band visual illusion.
You begin by creating the M-file named ramp.m that will generate the visual input (see
Figure 16.2). The input will be a 64 3 128 matrix whose values represent the intensity or
brightness of the image. You w... |
import numpy as np
import pandas as pd
from functools import partial
from multiprocessing import Pool
def parallelize(data, func, num_of_processes=8):
data_split = np.array_split(data, num_of_processes)
pool = Pool(num_of_processes)
data = pd.concat(pool.map(func, data_split))
pool.close()
pool.jo... |
# /usr/bin/python
# -*- coding: utf-8 -*-
"""
:mod:`highlight` -- Highlight Methods
===================================
.. module:: highlight
:platform: Unix, Windows
:synopsis: highlight document snippets that match a query.
.. moduleauthor:: Noah Gift <noah.gift@gmail.com>
Requirements::
1. You will nee... |
#this script prompts the user for a number "n", then returns the nth number in the Fibonacci sequence
def fib(nth):
last = 0
total = 1
for i in range(nth):
total += last
last = total-last
return total
n = eval(input("Enter a number, n, to see the nth Fibonacci number"))
print (fib(n-1)) |
import Tkinter as tk
def write_slogan():
update_label("Hello again")
def update_label(message):
print("Tkinter is easy to use!")
label.config(text=str(message))
root = tk.Tk()
root.title("Awake")
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
... |
"""
This module solves (certain types of) cryptarithmetic problems.
"""
from csp import *
import itertools
import re
class Cryptarithmetic(ConstraintSatisfactionProblem):
"""
The cryptarithmetic solver.
This one only solves decimal domain puzzles, and only puzzles with two
addends and a sum.
""... |
a = int(input("How many rectangles : "))
count = 1
total = 0
while a:
wdt = int(input("Width {}:".format(count)))
hgh = int(input("Height {}:".format(count)))
for u in range(hgh):
for k in range(wdt):
print('*',end='')
print()
a-=1
count += 1
... |
__Author__ = "CNTSP"
import re
def delete(f_list,f_index):
"""
删除列表元素
:param f_list: 输入列表
:param f_index: 输入要删除的运算符的位置
:return:
"""
# 列表的删除有先后顺序
del f_list[f_index+1]
del f_list[f_index]
del f_list[f_index-1]
return f_list
def add(f_list):
"""
加法计算
:param f_lis... |
# program to calculate how long it takes to calculate the product of first 1000000 numbers.
import time
import numpy
def calcProd():
#calculates product of first 100,000 numbers
product = 1
for i in range(1, 100000):
product = product * i
return product
startTime = time.time()
prod = calcProd()
endTime = time.... |
import random
def GetNum(n):
a = []
while n > 0 :
b = random.randint(0,10*n)
a.append(b)
n -= 1
return a
def Merge_Sort(alist):
n = len(alist)
if n <= 1:
return alist
mid_index = n//2
left_list = Merge_Sort(alist[:mid_index])
right_list = Merge_Sort(ali... |
def NumJewelsInStones(J, S):
"""
:type J: str
:type S: str
:rtype: int
"""
J = list(J)
S = list(S)
count = 0
for i in range(len(J)):
for j in range(len(S)):
if J[i] == S[j]:
count += 1
return count
if __name__ == '__main__':
J = "aAb"
... |
# 删除一个字符串所有的a,并复制所有的b
def str_remove(str):
n = len(str)
count = 0
i = 0
j = 0
while i < len(str):
if str[i] == "a":
str= str[:i] + str[i+1:]
i -=1
i +=1
while j < len(str):
if str[j] =="b":
count +=1
j +=1
return str,count... |
import numpy as np
import random
def GetNum(n):
a = []
while len(a) < n:
b = random.randint(1, 10*n)
a.append(b)
return a
def Bubblesort(alist):
"""冒泡排序"""
n = len(alist) - 1
# i代表下标
for i in range(n):
count = 0
for j in range(n-i):
if alist[j] >al... |
def sortArrayByParity(A):
"""
:type A: List[int]
:rtype: List[int]
"""
even = []
odd = []
for i in A:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
A = even.extend(odd)
return A
if __name__ == '__main__':
A = [1,2,3,4]
a = sortArra... |
# 如果a+b+c = 1000 a^2+b^2 = c^2 如何求出a,b,c的可能组合
# 方案一
import time
# start_time = time.time()
# for a in range(0,1001):
# for b in range(0,1001):
# for c in range(0,1001):
# if a+b+c == 1000 and a**2 + b**2 == c**2:
# print("a=%d,b=%d,c=%d"%(a,b,c))
# end_time =time.time()
# print("... |
class LinearMap(object):
def __init__(self):
self.items = []
def add(self,k,v):
self.items.append((k,v))
def get(self,k):
for key,val in self.items:
if key == k:
return val
raise KeyError
class BetterTable(object):
def __init__(self,n=100):... |
"""To Map A -> D, m ->p likewise
String is string parameter
String parameter can be string or para or word
"""
import string
def String_Amaze(String):
NewString = ' '
for word in String:
if word == ' ':
Ascii = ord(word)
else:
for pun in string.punctuat... |
fname=input("Enter a file name :")
if len==0:
fname='mbox-short.txt'
fhand=open(fname)
for line in fhand:
line=line.strip().upper()
print(line)
|
number1 = int(raw_input("Enter number of sweets:"))
number2 = int(raw_input("Enter number of bags:"))
whole_answer =number1 // number2
remainder_answer = number1 % number2
print("You will require ", whole_answer,"number of bags")
print("You will have reminder of :",remainder_answer,"sweets")
|
value=int(input("Enter a value:"))
total=1
while value!=0:
total=value*total
value=value-1
print("Factorial =",total)
|
total=0
for num in range(101):
total=total+num
print(total)
for i in range(5, -1, -1):
print(i)
|
print(" ")
print(" --------- ###### EXERCISE 12 ########## --------- ")
print(" ")
print("Practicing print!")
print("Hello Word!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay!! Printing.')
print("I'd much rather you 'not'.")
print('I "Say" do not touch this.')
print(" ")
... |
#0 1 1 2 3 5 8 13 21 34
def fib1(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return fib1(n-1) + fib1(n-2)
def fib2(n):
fib_sequence = []
for i in range(n+1):
if len(fib_sequence) == 0:
fib_sequence.append(0)
elif len(fi... |
import sys
INDENT = 2
class CompilationEngine:
'''A compilation engine for the Jack programming language'''
def __init__(self, tokenizer, ostream):
'''Initialize the compilation engine
@tokenizer the tokenizer from the input code file
@ostream the output stream to write the code to'''
self.tokenizer = toke... |
__author__ = 'Lancewer'
#judge a num is larger smaller or equals 0
def foo(x):
if x > 0:
print 'The number %d is larger than 0' % x
elif x < 0:
print 'The number %d is smaller than 0' % x
else:
print 'The number %d is equals to 0' % x
foo(10)
foo(-1)
foo(0)
i = int(raw_input('Enter... |
def find_triplets(lst, sum):
all_triplets = []
l = len(lst)
for i in range(l-1):
s = dict()
for j in range(i + 1, l):
x = sum - (lst[i] + lst[j])
if x in s.keys():
all_triplets.append([x, lst[i], lst[j]])
else:
s[lst[j]] = ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head == None:
return head
n = 0
node = hea... |
# This is the program to print odd number in python
for i in range(1,30):
if(i % 2 != 0):
print(i)
|
revenue = int(input('Какова выручка фирмы? '))
costs = int(input('Какие издержки у фирмы? '))
profit = revenue - costs
if revenue > costs:
print(f'Фирма работает с прибылью. Рентабельность - {round(profit / revenue, 2)}')
elif costs > revenue:
print('Фирма работает в убыток.')
else:
print('Фирма работает в ... |
from random import randint
# otvet = int(input('Четное число или нечетное: '))
# n_comp = randint(1, 2)
# if otvet != 1 and otvet != 2:
# print('введите число 1 или 2')
# elif otvet == n_comp:
# print('Выйграл')
# else:
# print('Проиграл')
n = 5 # кол-во попыток
k = 0 # счетчик
for m in range(n)... |
from matplotlib import colors
import pandas as pd
import numpy as np
import os
import csv
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from math import sqrt
#filename = r"C:\Users\ReSEC2021\OneDrive - Wilfrid Laurier University\slideanalysis\gpr_out.csv"
filename = r"C:\Users\ReS... |
def merge_sort(array):
n = len(array)
if n <= 1:
return array
mid = n/2
left = array[0:mid]
right = array[mid:]
left = merge_sort(left)
right = merge_sort(right)
newArray = merge(left, right)
return newArray
def merge(left, right):
array = []
ileft = 0
iright = 0
while ileft < len(left) and iright < le... |
import re
cadena = "Vamos a aprender expresiones regulares en Python. Python es un lenguaje de sintaxis sencilla"
# Buscamos una cadena dentro de otra, 1º parametro cadena a buscar
# 2º parametro cadena donde se realizara la busqueda, devuelve un
# objeto si lo encuentra o None si no.
print(re.search("aprender", cad... |
import sqlite3
miConexion = sqlite3.connect("GestionProductos")
miCursor = miConexion.cursor()
# Le damos un id unico inreppetible, y hacemos que se incremente solo
# Con UNIQUE le decimos que no puede estar repetido el valor de ese campo
# miCursor.execute('''
# CREATE TABLE PRODUCTOS(
# ID INTEGER PRIMA... |
from tkinter import *
from tkinter import filedialog
root = Tk()
def abreFichero():
# Por default nos abre la carpeta de Documentos, pero se cambia con initialdir
# Por default nos muestra todas las extenciones peor se cambia con filetypes
fichero = filedialog.askopenfilename(title="Abrir", initialdir="C:... |
# Traemos la libreria encargada de la GUI
from tkinter import *
# Creamos la ventana
root = Tk()
# Creamos el Frame dentro del root y con unas medidas
miFrame = Frame(root, width=500, height=400)
# Empaquetamos el Frame
miFrame.pack()
# Creamo un label. le especificamos el contenedor padre
miLabel = Label(miFrame, t... |
#Given the integer N - the number of minutes that is passed since midnight - how many hours and minutes are displayed on the 24th digital clock?
#the program should print two number: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59)
#for example, if N=150, then 150 minutes have passed ... |
"""numbers=[1,2,3]
numbers.insert(1,50)
print(numbers)
#list comprehension
new=[1,2,3]
out=[item**2 for item in new]
print(out)"""
#dynamic slicing scheme
"""nos=[0,1,2,3,4,5,6,7,8,9,10]
for i in range(len(nos)):
print(nos[:11])
window_size=3
nos1=[0,1,2,3,4,5,6,7,8,9]
for i in range(len(nos1)-(window_size-1)):
... |
# Link to my solution on CheckiO:
# https://py.checkio.org/mission/stair-steps/publications/hawkinmogen/python-3/find-all-possible-paths-then-return-max-sum/share/bd8981336b990aa673a1bb92473b304c/
def allPaths(current, end, possibleSteps, path, result):
# Returns all possible permutations of staircase paths....
... |
import os
import pathlib
module_path = pathlib.Path(__file__)
common_filename = module_path.parent.joinpath("common.txt")
common_file = open(common_filename, "r")
a = common_file.readlines() #"\n"
common_list = []
for word in a:
word = word.replace("\n", "")
common_list.append(word)
# how to handle numbe... |
def comparehalves(input_string):
str_len = len(input_string)
global front
global back
if (str_len % 2 != 0):
front = input_string[0:int(str_len / 2)+1]
back = input_string[(int(str_len / 2)) + 1:]
else:
front = input_string[0:int(str_len / 2)]
back = input_string[int(str_len / 2)... |
import numpy as np # necessary for matrix manipulation
class NeuralNetwork():
def __init__(self):
# Seed the random number generator
np.random.seed(1)
# Set synaptic weights to a 3x1 matrix,
# with values from -1 to 1 and mean 0
self.synaptic_weights = 2 * np.random.ran... |
import sqlite3
conn = sqlite3.connect("books.sqlite")
cursor = conn.cursor()
sql_query = """
CREATE TABLE book (
id integer PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
first_sentence text NOT NULL,
published integer NOT NULL
)"""
cursor.execute(sql_query)
sql_ins... |
import codecademylib3_seaborn
import pandas as pd
from matplotlib import pyplot as plt
healthcare = pd.read_csv("healthcare.csv")
# Inspecting healthcare dataframe
print(healthcare.head(500))
# Checking all unique dianoses in our dataset
print(healthcare['DRG Definition'].unique())
# Grabbing only the rows in the d... |
import numpy as np
import math
import matplotlib.pyplot as plt
from numpy import random
def gaussian(x, mean, variance):
const = 1/(((2*math.pi)**0.5)*sigma)
y = math.e**((-0.5*(sigma**2))*((x - mean)**2))
return y*const
def likelihood(x, mean):
p = 1
for i in x:
p *= gaussian(i, mean, 1)... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 17:41:20 2021
@author: MOSS
"""
'''
To gain access to a specific string character, you use its index:
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(alphabet[0], alphabet[1], alphabet[25])
a negative index will start from the right
'''
'''
string are immutable, y... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 15:26:36 2021
@author: MOSS
"""
'''
You can determine whether a value is found within a container,
such as a dictionary or list, using in and not in, which are known
as membership operators. The yield Boolean values
prices = [5, 15, 20]
print(15 in prices)
yields: ... |
n=int(input("Enter a number:"))
to=0
while(n>0):
dg=n%10
to=to+dg
n=n//10
print("The total sum of digit is:",to)
|
#first two and last two
def both_ends(s):
if len(s)<=2:
return ""
else:
a = s[0:2]+s[len(s)-2:]
return a
print(both_ends("bannan"))
|
# Given two strings .Print all the interleavings of the two strings.
# Interleaving means that the if B comes after A .It should also come after A in the interleaved string.
# ex-
# AB and CD
# ABCD
# ACBD
# ACDB
# CABD
# CADB
# CDAB
def interleave(prefix,str1,str2):
if prefix is None:
return
len1 = len... |
# CoderJelly
# Write a method to determine if the bit-wise representation of an integer is a palindrome.
m = 9
n = 0
orig = m
while m:
k = m & 1
n = n << 1
n = n ^ k
m = m >> 1
print n == orig
#alternate:
n = bin(orig)[2:]
if n!=n[::-1]:
print 'NO'
else:
print 'YES' |
# Author: coderjelly
# Problem Statement: On a positive integer, you can perform any one of the following 3 steps.
# 1.) Subtract 1 from it. ( n = n - 1 ) , 2.) If its divisible by 2, divide by 2.
# ( if n % 2 == 0 , then n = n / 2 ) , 3.) If its divisible by 3, divide by 3.
# ( if n % 3 == 0 , then n = n / 3 ).
... |
# The longest Increasing Subsequence (LIS) problem is to find the length of the longest
# subsequence of a given sequence such that all elements of the subsequence are sorted
# in increasing order.
# For example, length of LIS for { 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6
# and LIS is {10, 22, 33, 50, 60, 80}.
de... |
# coding=utf-8
from collections import defaultdict
def counting_sort(A, key=lambda x: x):
"""
计数排序
:param A:
:param key:
:return:
"""
B, C = [], defaultdict(list)
for x in A:
C[key(x)].append(x)
for k in range(min(C), max(C)+1):
B.extend(C[k])
return B
if __n... |
def maxLen(arr):#1
max_len = 0#2
for i in range(len(arr)):#3
curr_sum = 0#4
for j in range(i, len(arr)):#5
curr_sum += arr[j]#6
if curr_sum == 0:#7
max_len = max(max_len, j-i+1)#8
return max_len#9
//DESCRIPTION:
Create a Python function that, given an ... |
"""
Implement two methods for computing closest pairs and two methods for clustering data.
Then compare these two clustering methods in terms of efficiency, automation, and quality.
"""
__author__ = 'liuyincheng'
import math
import alg_cluster
def pair_distance(cluster_list, idx1, idx2):
"""
Helper function... |
string = input("Enter your string: ")
n = input("Enter the # of rows: ")
n = int(n)
index = []
for i in range(n):
index.append(i)
for i in range(n-2,0,-1):
index.append(i)
print(index)
round_len = 2*n-2
string_len = len(string)
map_list = [None]* string_len
for i in range(string_len):
temp = i % round_len
map_list[... |
#Put a class named "Board": This class will represent a checkers board.
#This class will handle all the different pieces moving, leading specific pieves, deleting specific pieces, rawing itself on the screen.
import pygame
from .constants import BLACK, ROWS, RED, SQUARE_SIZE, COLS, WHITE, BLUE, GREEN
from .piec... |
"""
Modulo Collections - Counter (contador)
counter -> recebe um iteravel como parametro e crfia um objeto do tipo collections counter que é parecido
com o dic, contendo chave e elemento da lista passada como parametro e como valor a quantidade de ocorrencias
desse elemento
# Exemplo 1, numeros
lista = [1,1,2,2,2,3,3... |
def chiper(s: str) -> str:
result = ''
for c in s:
if c.islower():
result += chr(219-ord(c))
else:
result += c
return result
print(chiper('aBc'))
|
#Tic-Tac-Toe Two Revengance Featuring Dante from Devil may cry, & Knuckles
def winningBoard(list1):
winner = False
#Checks rows for a horizontal victor
count= 0
for x in list1:
if list1[count][0] == list1[count][1] == list1[0][2] and list1[count][0] !='':
winner= lis... |
#Casey Wenner
#Homework4
#Is it prime?
import math
x= int(input("Enter a positive integer: "))
count = x-1
Nprime=0
while count > 1:
if(x%count)==0:
Nprime=Nprime+1
count=count-1
if Nprime > 0:
print("No, ", x," is not prime.")
else:
print("Yes, ", x," is prime.")
|
## CSP Toolset
#Set of tools e.g. visualisation, graph creation etc for collective shortest paths problem
import networkx as nx
import random
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import math
# import scipy
# import pydot
from collections import defaultdict
from math import sqrt
i... |
import re
# 그루핑
p = re.compile("(ABC)+")
m = p.search("ABCABCABCABC OK?")
print(m.group(1))
# ()를 통해 그루핑을 하고, 인덱스를 통해 해당 그룹의 문자열만 가져올 수 있다.
p = re.compile(r"(\w+)\s+((\d+)[-]\d+[-]\d+)")
m = p.search("park 010-1234-1234")
print(m.group(1))
print(m.group(2))
print(m.group(3))
# 재참초(Backreferences)
p = re.compile(r'... |
# 문자열 정의하는 방법 4가지
a = "Hello Python"
b = 'Hello Python'
c = """Hello Python"""
d = '''Hello Python'''
print("\"Hello Python\" = " + a)
print("\'Hello Python\' = " + b)
print('"""Hello Python""" = ' + c)
print("'''Hello Python = '''" + d)
# 문자열의 연산
head = "Hello "
tail = "Python!"
# 더하기
print(head + tail)
# 빼기 는 오류난다... |
# recursion - a function calling itself
'''
def wish():
global i
i += 1
print('Hi Moni',i)
wish()
i = 0
wish()
'''
# find factorial of num using recursion
# set terminating condition # check file20
def fact(n):
if n == 0:
op = 1
else:
op = n * fact(n - 1)
return op
n = 4
... |
"""
Author: Brady Trenary
Program: assign_average.py
"""
def switch_average(entry):
my_dict = {'A': 'You entered an A!',
'B': 'You entered a B!',
'C': 'You entered a C!',
'D': 'You entered a D!',
'F': 'You entered an F!'
}
result = m... |
from space import Space
import time
import os
import numpy as np
'''
class to make the user decide how to use the simulation
'''
class initializing(object):
def __init__(self):
self.select=-1
print("Welcome to Hakon's space-simulator")
time.sleep(2)
os.system('cls' if os.name == '... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3, 4]].values
# Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters = i, ... |
# In a given grid, each cell can have one of three values:
# the value 0 representing an empty cell;
# the value 1 representing a fresh orange;
# the value 2 representing a rotten orange.
# Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
# Return the minimum number... |
import tkinter as tk
from tkinter import messagebox
# def show(): # show() user defined function
# messagebox.showinfo("message","sumthing is error !")
def sum1():
a=int(t_a.get())
b=int(t_b.get())
c=a+b
messagebox.showinfo("sum",f"sum of 2 numbers = {c}")
def subract():
a=int(t_... |
def maxValue(vector):
"""[This function takes a vector and returns the largest absolute value of that vector]
Arguments:
vector {[list]} -- [this is a list of numbers]
Returns:
[newMax] -- [this is the largest number from the numbers in the vector]
"""
newMax = 0
"This... |
"""
编写代码测试类属性实例属性 ,类方法静态方法实例方法,分析区别以及调用逻辑
"""
class Teacher():
"""
first demo
"""
is_ok = True
def __init__(self,name,age):
self.name = name
self.age = age
def getname(self):
print(self.name)
# 类方法
@classmethod
def cmethod(cls):
print(cls.__do... |
import types
class Teacher():
"""
demo01
"""
__slots__ = ('name', 'age', 'addr', 'move')
def __init__(self, name, age):
self.name = name
self.age = age
def getname(self):
print(self.name)
@property
def sage(self):
return self.age
@sage.setter
... |
def getinfo(self):
print("id", self.id)
print("name", self.name)
Goods = type("Goods", (), {"id": 1, "name": "hcy", "getinfo": getinfo})
def getname(self):
print(self.name)
Food = type("Food", (Goods, ), {"id": 2, "name": "zzz", "getname": getname})
g1 = Goods()
f1 = Food()
g1.getinfo()
f1.getinfo()
f... |
import random, logging
import board
inserted = False
fork_field_for_blok = []
ile_forkow = 0
ile_blokad_forkow1 = 0
ile_blokad_forkow2 = 0
def computer_move_difficulty(player, opponent, difficulty, game_round):
# Makes computer move according to the selected difficulty level
if difficulty == 1:
computer_move_diff... |
#!/usr/bin/python3
import sys
dict = {}
arr = []
for i in sys.argv:
if i not in dict and i != sys.argv[0]:
arr.append(i)
dict[i] = 1
for i in arr:
print(i, end=' ')
print("")
|
#
# Example file for variables
#
# Declare a variable and initialize it
# x=5.5
# print(x)
# # re-declaring the variable works
x='acv'
# print(x)
# # ERROR: variables of different types cannot be combined
# print('acv ' + str(5.5))
# Global vs. local variables in functions
def someFunction():
global x
x=5
... |
# Print factorial of the input number
# Not going with recursive approach
# because the max size of heap space is 8
# in the platform ide .
def fact(a):
if a <= 1: return 1
ans = 1
while a > 1:
ans *= a
a -=1
return ans
t =int(input())
while t >0:
n = int(input())
print(fact(n)... |
# Count the number of even and odd elements in an array
# Print out their difference
t =int(input())
n = list(map(int,input().split()))
i,j=0,0
for k in n:
if k%2==0:
i+=1
else :
j+=1
print("".join(["READY FOR BATTLE" if i > j else "NOT READY"]))
|
# Primality Check of a Number.
def status(a):
if a < 2:
return 'no'
elif a ==2:
return 'yes'
for i in range(2,int(a**1/2) + 1 ):
if a%i==0:
return 'no'
return 'yes'
t = int(input())
while t>0 :
n =int(input())
print(status(n))
t-=1
|
# Program to find 2nd largest
# number among 3 numbers entered by the user.
def sec_largest(a,b,c):
smallest = min(min(a, b), c)
# min(a,b,c) is allowed in python.
largest = max(max(a, b), c)
# max(a,b,c) valid in python
return a ^ b ^ c ^ smallest ^ largest
# Method to arrange elements
t = in... |
def main():
t = int(input())
while(t>0):
t-=1
a =input().split(" ")[0]
b = input().split(" ")[0]
res = [x for x in a if x in b]
if len(res):
print("Yes")
else:
print("No")
if __name__ == "__main__":
main()
|
from graph import Graph
def earliest_ancestor(ancestors, starting_node):
pass
# What traversal method would best be used?
# Since we want to go as deep as possible into the connections,
# A Depth First Traversal should be used
# We can use Recursion in that case
## PROBLEM SOLVING!!!!!!
# 1.) Describe the pro... |
import datetime
from math import *
def simpson_Method(func, a, b, epsilon):
print("Simpson method is going by the formula - (h/3)*(f(a)+2*sigma(from j=1 to last even)*f(X2j)+4*sigma(from j=1 to last odd)*f(X2j-1)+f(b))")
sol1 = 2 * epsilon
sol = 0
def run(func, a, b, slices):
sl... |
def main():
try:
number_file = open("numbers.txt", "r")
except Exception as errorGenerated:
print("file is not found:", errorGenerated)
else:
total = 0
number_of_lines = 0
line = number_file.readline()
while line != "":
number_of_lines += 1
... |
import pickle
def open_file():
output_file = open('mailing_list.dat', 'wb')
return output_file
def make_mailing_list():
mailing_list = {}
validation = 'y'
while validation == 'y':
name = input('Enter a name in small letter to add his or her email'
'address: ')
... |
def ask_for_expenses():
monthly_loan_payment = float(input("How much do you pay for your loan" + "every month:"))
monthly_insurance_payment = float(input("How much do you pay for your insurance" + "Every month:"))
monthly_gas_payment = float(input("How much do you pay " + "For Gas every month: "))
... |
import math
class Circle:
#construct a circle object
def __init__(self, radius = 1):
self.radius = radius
def getPerimeter(self):
return 2*self.radius*math.pi
def getArea(self):
return self.radius * self.radius*math.pi
def setRadius(self, radius):
s... |
import turtle
##import Screen
##import RawTurtle
##screen=Screen()
##turtle=RawTurtle(screen)
t=turtle.Pen()
#t.forward(50)
#t.left(90)
#t.forward(50)
#t.left(90)
#t.forward(50)
#t.left(90)
#t.forward(50)
##estrella
##t.reset()
##a=int(input("numero: "))
##an=180/a
##an2=180-an
##t.reset()
##for x in range(a):
## t.for... |
class Calculator(object): #hesap makinesi objemi oluşturdum
def __init__(self,a,b): #dışarıdan 2 parametre alcam bu parametreler benim attributelarım
self.a = a
self.b = b
def addition(self): #toplama behaviorım, classın kendi içindeki parametreleri kullanarak çalışan bir method
... |
# *args, enumerate
def itrrgs(*args):
"""
DOCSTRING: функция печатает нумерованй список аргументов
INPUT: args
OUTPUT: print(el)
"""
for el in enumerate(args, 1):
print(el)
itrrgs((-1 + 0j), 1, 2.2, True, None, 'String', [3, 4],
(5, 6, 6.5), {7: 'seven', 8: 'eight'}, {9, 10},... |
"""Урок 5 Задание 2
Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить
подсчет количества строк, количества слов в каждой строке.
"""
with open("text_2.txt", "r", encoding='utf-8') as f_obj:
usefulness = [f'{line}. {" ".join(count.split())} - {len(count.split())} слов' for line, coun... |
# 1 ---------------------------------------------------------
mynums = [100, 200, 50]
def myargs(*args):
"""
DOCSTRING: функция удваивает аргументы и выводит их сумму
INPUT: args
OUTPUT: sum(args) * 2
"""
return f'результат вычисления - {sum(args) * 2}.'
print(myargs(100, 200, 50))
print(su... |
"""урок 3 задание 2
Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя:
имя, фамилия, год рождения, город проживания, email, телефон.
Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о
пользователе одной строкой.
"""
# вариант через *args
def us... |
# 1st day of month is which day of year
#day 1 of 1901 is tueday
#day day 6 is sunday
nod=[31,28,31,30,31,30,31,31,30,31,30,31]; # number of days in month
nodleap=[31,29,31,30,31,30,31,31,30,31,30,31]; # no. of days in leap month year
i=1;
day=[1];
dayleap=[1];
for year in range(1,101):
months=nod;
if year%4==... |
from math import sqrt as sqrt;
from math import floor as floor;
from math import factorial as f;
import sys;
def is_prime(a):
return all(a%i for i in range(2,a));
#with open("54.txt") as file:
# for line in file:
# data.append(line.split(' '));
# def is_palindrome
tot=9999;
flag=0;
def sum_digits(n):... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 10:26:50 2021
@author: Teja Kalidindi
"""
import unittest
from Calculator import scientific
class TestSum(unittest.TestCase):
def test_add(self):
a = 1
b = 1
result = scientific.add(self,a,b)
self.assertEqual(result, 2)
def test... |
def sum(lon):
list_sum = 0
for val in lon:
list_sum += val
return list_sum
def index_of_smallest(lon):
if not lon:
index = -1
else:
index = 0
for i in range(len(lon)):
if lon[i] < lon[index]:
index = i
return index
|
# 🚨 Don't change the code below 👇
print("Welcome to Daniel's Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperoni? Y or N ")
extra_cheese = input("Do you want extra cheese? Y or N ")
# 🚨 Don't change the code above 👆
#Write your code below... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.