text stringlengths 37 1.41M |
|---|
'''
Given arrival and departure times of trains on a single day in a railway platform, find out the minimum number of platforms required so that no train has to wait for the other(s) to leave.
You will be given arrival and departure times in the form of a list.
Note: Time hh:mm would be written as integer hhmm f... |
'''
Leetcode Link:https://leetcode.com/problems/sum-of-square-numbers/
Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False
'''
class S... |
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
# def count_th(word):
def count_th(word, count = 0):
# TBC
... |
# 问题: 想创建一个内嵌变量的字符串, 变量被它的值所表示的字符串替换掉
# 解决方案: format(), format_map(), vars()
s = '{name} has {n} messages.'
print(s.format(name='GG', n=37))
name = 'sss'
n = 25
print(s.format_map(vars()))
# vars() 应用于实例对象的例子
class Info:
def __init__(self, name, n):
self.name = name
self.n = n
a = Info('CC', 20)
... |
# 问题: 希望构造一个返回多个值的函数
# 解决方案: return val1, val2, val3
# 实际上返回的是一个元组tuple, 先创建一个元组然后返回
a = 1, 2
print(a, type(a)) |
# 问题: 现在有多个字典或映射, 想将它们从逻辑上合并为一个单一的映射后执行某些操作,
# 比如查找值或检查某些键是否存在
# 解决方案: collections 模块中的 ChainMap
from collections import ChainMap
a = {'x':1, 'z':3}
b = {'y':1, 'z':4}
c = ChainMap(a, b)
print(c)
print(c['z'])
# ChainMap类只是在内部创建了一个容纳这些字典的列表
# 并重新定义了一些常见的字典操作来遍历这个列表,
# 大部分字典操作可用
print('len(c) is ', len(c))
prin... |
# 问题: 想将print()函数的输出重定向到一个文件中去
# 解决方案: 在print()函数中指定file关键字参数
with open('test.txt', 'wt') as f:
# 注意,文件要是以二进制打开, 打印就会报错
print('Hello world', file=f) |
# 问题: 想在字节字符串上执行普通的文本操作
data = bytearray(b'hello world')
print(data[:5])
print(data.startswith(b'hell'))
print(data.split())
print(data.replace(b'hello', b'yep'))
# 文本字符串和字节字符串的区别
text_string = 'Hello world'
byte_string = b'Hello world'
print(text_string[0], byte_string[0])
# 字节字符串如果被打印的话
print(byte_string)
print(byt... |
# 问题: 需要将数字格式化后输出
# 解决方案: format
x = 1234.56789
print(format(x, '0.2f')) # 不固定长度, 2位小数浮点数
print(format(x, '>10.1f')) # 固定10位chars, 右对齐, 1位小数浮点数
print(format(x, '<10.1f')) # 左对齐
print(format(x, '^10.1f')) # 居中对齐
print(format(x, ',')) # 千分位用,
print(format(x, '0,.1f'))
print(format(x, 'e'))
print(format(x, '0.2E')... |
# 问题: 需要用复数
# 解决方案: complex(real, image) 或者 带有后缀j的浮点数
a = complex(2, 4)
b = 3 - 5j
print(a, b, type(a), type(b))
print(a.imag, b.imag, a.real, b.real)
print(a.conjugate())
print(abs(a))
print('-'*100)
# 用 cmath 进行数学计算
import cmath
print(cmath.sin(a))
print(cmath.exp(a))
print('='*100)
# 用 numpy 也可以处理复数
import numpy... |
# 问题: 有一个被其他python代码使用的callable对象, 可能是一个回调函数或处理器
# 但是参数太多了, 导致调用时出错
# 解决方案: functools.partial() 固定函数的某些参数, 然后返回一个新的callable对象,
# 新的callable接受未赋值的参数, 然后和之前固定的参数合并起来,
# 将所有参数传递给原始函数
from functools import partial
def spam(a, b, c, d):
print(a, b, c, d)
s1 = partial(spam, 1)
s1(2,3,4)
s2 = ... |
# 和上一问题一样, 如果可迭代对象的元素超过变量个数时, 会报错
# 解决办法用 *变量名
records = (60, 65, 75, 80, 83, 90)
def drop_first_last(records):
first, *middle, last = records
return sum(middle)/len(middle)
r = drop_first_last(records)
print(r)
# 小案例
records = ('Dave', 'dave@email.com', '773-123-121', '857-123-1111')
name, email, *phone_n... |
# 问题: .*是贪婪匹配,会找最长的
# 解决方案: .*? 非贪婪匹配, 找短的
import re
str_pat1 = re.compile(r'"(.*)"')
text1 = 'Computer says "no."...'
text2 = 'Computer says "no." Phone says "yes."....'
print(re.findall(str_pat1, text1))
print(re.findall(str_pat1, text2))
print('-'*50)
str_pat2 = re.compile(r'"(.*?)"')
print(re.findall(str_pat2, te... |
nombre = "Ivan Pinduisaca"
edad = 28
print ("Mi nombre es {} y tengo una edad de ".format(nombre, edad)) |
''' 1) I am going to take deck of cards using API
2) pick the hand of cards using deck-id'''
import requests
import json
class Cards_API:
#test class
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
"""Returns a human-read... |
Importing libraries:
from sklearn.tree importimport seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import chi2
from sklearn.feature_selection import SelectKBest, SelectPercentile
%matplotlib inline DecisionTreeClassifier
import os
import numpy as np # linear algebra
i... |
import sys
import os
import argparse
description = """
Program that succeeds if the output in f is a proper list, in order, and is \
consistent with the added/removed statements.
"""
def parse_output_file(ops_file, final_list):
s = set()
s.add(-1)
actual_remaining_elements = []
# process ops fil... |
"""
Checking each algorithm for correctness by comparing the result
with in-built sorted function
"""
from random import shuffle
from sorting_algorithms import insertion_sort, quicksort, heap_sort, bucket_sort, introsort
# Create a shuffled array of size 5000
arr = list(range(5000))
shuffle(arr)
# Compare each algor... |
import tkinter as tk
from pytube import YouTube
window = tk.Tk()
window.geometry('500x300')
window.resizable(0,0)
window.title("Youtube Video Downloader")
tk.Label(window, text ="Youtube Video Downloader", font ="arial 20 bold").pack()
link = tk.StringVar()
tk.Label(window, text ="Paste Link Here:", font ="arial 15 ... |
class Node:
pass
import math
def make_node(data,left,right):
ans=Node()
ans.data=data
ans.left=left
ans.right=right
return ans
def make_link(data,next):
ans=Node()
ans.data=data
ans.next=next
return ans
def f(l,depth):
if l is None:
return None,None
data=l.data
if... |
def is_prime(num: int) -> bool:
""" Возвращает True, если аргумент - простое число"""
if (num % 2 == 0) or (num % 10 == 5):
return False
for s in range(3, num - 1):
if num % s == 0:
return False
return True
def next_prime(previous_prime: int, prime_num_list: list) -> int:
... |
#Lab Assignment 1.5
#Write a Python program to evaluate the power function using while loop.
# taking value of base and exponent from user
base = int(input(" Please Enter any Positive Integer : "))
exponent = int(input(" Please Enter Exponent Value : "))
#checking if the value of exponent is not negative
if (... |
import math
class point:
def __init__(self,x=0,y=0):
self.x = float(x)
self.y = float(y)
def distance_origin(self):
return ((self.x ** 2)+(self.y ** 2))**0.5
def distance_other(self,o,p):
dx = (self.x - o)
dy = (self.y - p)
return ((dx **... |
#Lab Assignment 4.5
#Write a Python function that takes two lists and returns True if they have at least one common member.
#creation and appending the elements into lst by user
lst = []
num = int(input("Enter the number of elements you want to enter in first list: "))
for i in range(num):
number = in... |
#Lab Assignment 3.5
#Write a Python program to print the even numbers from a given list.
#creation of list
lst = []
#Taking input from users and appending those numbers into the list.
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers... |
import numpy as np
print("=============================================================")
n1 = int(input("Enter the lower bound limit of array: "))
n2 = int(input("Enter the upper bound limit of array: "))
arr = np.arange(n1,n2,10)
print("\n=============================================================")
print... |
#lab Assignment 2.6
#Write a program called time.py that prompts the user to enter the current time in HH:MM format, and then prints a message that states the time in a sentence.
# take the time input from user and use split() function with ":" as a delimiter or separator
a,b=[int(n) for n in input("Enter a time (... |
import sys
import random
import json
# Command line parameters
number1= sys.argv[1]
number2= sys.argv[2]
number3= sys.argv[3]
number4= sys.argv[4]
number5= sys.argv[5]
number6= sys.argv[6]
# Input error check. We can accept only digits and avoild literals
if number1.isdigit() != True or number2.isdigit() != True or... |
def longest_common_sub(s1, s2):
n = len(s1) + 1
m = len(s2) + 1
L = [[0] * m for i in range(n)]
for i in range(n):
for j in range(m):
if i == 0 or j == 0:
L[i][j] = 0
elif s1[i - 1] == s2[j - 1]:
L[i][j] = L[i-1][j-1] + 1
else:
L[i][j] = max(L[i-1][j], L[i][j-1])
return L[n-1][m-1]
s1 = "AG... |
#!/usr/bin/python
import sys
total=0
count=0
# Loop around the data
# It will be in the format key\tval
# Where key is the product name, val is the sale amount
#
# The highest individual sale for each separate store will be presented,
# then the key will change and we'll be dealing with the next store
for line in s... |
class Animal():
def __init__(self,**args):
self.nombreCientifico = args["nombreCientifico"] if "nombreCientifico" in args else ""
def setNombreCientifico(self,nombreCientifico):
self.nombreCientifico = nombreCientifico
def setNombreComun(self, nombreComun):
self.nombreComun = no... |
def hey(phrase):
"""Bob, A teenager chat bot.
Parameters
------------
phrase: str
Phrase that is said to bob.
Returns
-----------
str
Bob answers 'Sure.' if you ask him a question.
He answers 'Whoa, chill out!' if you yell at him.
He answers 'Calm down, I kn... |
"""
ATM Controller module
"""
import bank_module
class ATM(object):
def __init__(self):
super()
self._bank_instance = bank_module.BankAPI()
self._cash_bin = CashBin()
self._curr_card = None
self._authorized = None
self._accounts_list = None
self._account = ... |
# -*- coding: utf-8 -*-
# 排序算法
print(sorted([5, 1, 3, 6, -21, 1000]))
# 2.按照绝对值大小排序
print(sorted([1, 5, -100, 2, 4, -300], key=abs))
# 3.字符串排序(1)区分大小写
print(sorted(['1', '2', '3', 'a', 'Z']))
# 3. 字符串排序(2)不区分大小写
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
# 3. 字符串排序,不区分大小写,且进行反向排序
print(sorted(['bob... |
# -*- coding: utf-8 -*-
L = [ x * x for x in range(10) ]
G = ( x * x for x in range(10) )
#print (L)
#print (G)
#print (next(G))
#print (next(G))
#print (next(G))
g = ( x * x for x in range(10) )
#for n in g:
# print (n)s
# 输出斐波那契数列
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield(b)
a, b... |
from socket import *
# Create a TCP server socket
# (AF_INET is used for IPv4 protocols)
# (SOCK_STREAM is used for TCP)
serverSocket = socket(AF_INET , SOCK_STREAM)
# Choose a server port and bind the serverSocket to the server address and port number
# Fill in start
port_number = 6789
serverSocket.bind(('', port_... |
def add(x, y):
return x + y
operand1 = 1
operand2 = 2
print(f"The sum of {operand1} and {operand2} is {add(operand1, operand2)}")
|
import math # to round numbers
class GeoCoordinateConverter:
'''Convert latitude and longitude within a geogrpahic region
to xy coordinates corresponding to the pixels in an image.
Note: units per degree (x_per_lon and y_per_lat) are determined
exogenously and passed as parameters. So, the ultimate s... |
from sys import argv
from os.path import exists
#We'll copy contents of one file to another
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
#How could we do these on one line?
indata = open(from_file).read()
print "The input file is %d bytes long" % len(indata)
#Exists returns... |
mahsulotlar = ['anor','uzum','olma','gosht','non','suv','piyoz','sabzi','guruch','un']
royxat =[]
bor_mahsulotar = []
yoq_mahsulotlar = []
print('5 ta mahsulot kiriting:')
for n in range(1,6):
mahsulot = input(f'{n}-mahsulotni kiriting')
royxat.append(mahsulot)
for m in royxat:
if m in mahsulotlar:
... |
son = int(input('Juft son kiriting:'))
if son%2 ==0:
print("Raxmat")
else:
print('Bu son juft emas') |
from intersect import *
class DBException(Exception):
def __init__(self, value):
self._value = value
def __str__(self):
return str(self._value)
# street database
class street_db(object):
def __init__(self):
self._db = dict()
def add(self, street_name, coords):
... |
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
''' The unicorn baked(verb) a cake(singular noun) for his friend the elephant(noun). Unfortunately, the cake(noun used before) had brie(noun) in it,
to which his friend was allergic to. His friend began to run(verb) uncontrollably and ran away to the local bakery. The unicorn ran(verb) after his friend
where he found... |
"""
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected ... |
import os
import pathlib
import re
from PIL import Image
class Steganography:
"""Steganography class responsible for hiding text inside images"""
def __init__(self, path: str, end: str = None) -> None:
"""Initialize the class
Args:
path (str): Path to the image that will hide th... |
'''
UW - Data Manipulation at Scale: Systems and Algorithms
Assignment 3: Thinking in MapReduce
Problem 2: Relational Join
Implement a relational join as a MapReduce query.
Example:
$ python join.py records.json
'''
import MapReduce
import sys
mr = MapReduce.MapReduce()
# =============================
# Do not ... |
from structure.enums.AutoNumber import AutoNumber
class Classes(AutoNumber):
ALCHEMIST = ()
MAGICIAN = ()
RANGER = ()
THIEF = ()
WARRIOR = ()
def by_name(self, name):
name = name.upper()
if name == 'ALCHEMIST':
return self.ALCHEMIST
if name == 'MAGICIAN':
... |
#!/usr/bin/env python
'''Module for zeroes at the end'''
def zeroes_end(test_array):
'''function definition to move zeroes at the end'''
array_length = len(test_array)
count = 0
test_array.sort()
for i in test_array:
if i != 0:
test_array[count] = i
count += 1
... |
#!/usr/bin/env python
'''Module for Finding Minimum node'''
class Node:
'''Initialization of Node Class'''
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def insert(node, data):
'''Function Definition to insert node'''
if node is None:
re... |
#!/usr/bin/env python
'''Module for Linked List'''
class Node:
'''Initializing Class'''
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
''' defining class of linked list'''
def __init__(self):
self.head = None
def push(self, new_data):
... |
#!/usr/bin/env python
'''Module for Breadth First Search'''
from collections import defaultdict
class Graph:
'''Find shortest path to every node in the graph'''
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, edge_1, edge_2):
'''adding an edge to the graph'''
... |
#!/usr/bin/env python
'''Module for equal brackets'''
def matches(left, right):
'''Function definition for matching parenthesis'''
if left == '(' and right == ')':
return True
elif left == '{' and right == '}':
return True
elif left == '[' and right == ']':
return True
els... |
lst=["what","is","your","name"]
print(" ".join(lst))
#or
lst=["what","is","your","name"]
for i in lst:
print(i,end=" ") |
#to convert celsius to fehrenheit
celsius=37.5
fahrenheit=(celsius*1.8)+32
print("%0.1f degree celsius is equal to %0.1f degree fahrenheit"%(celsius,fahrenheit))
|
#to find which number occurs in maximum times in a given list
list=[3, 4, 0, 0, 0, 6, 2, 0, 6, 7, 6, 0, 0, 0, 9, 10, 7, 4, 4, 5, 3, 0, 0, 2, 9, 7, 1]
x=max(list,key=list.count)
print(x)
#or
a=[3, 4, 0, 0, 0, 6, 2, 0, 6, 7, 6, 0, 0, 0, 9, 10, 7, 4, 4, 5, 3, 0, 0, 2, 9, 7, 1]
d={}
for i in a:
d... |
#For tuple
#write a program which accepts a sequence of comma-seperated numbers from console and generate a list and a tuple
input=input("enter the number")
list=[]
for i in input.split(","):
list.append(i)
print(list)
print(tuple(list))
#Write a program to generate and print another tuple whose values ... |
#find the duplicate number--------------------O(n^2) notation
numbers=[3,6,2,4,3,6,8,9]
for i in range(len(numbers)):
for j in range(i+1,len(numbers)):
if numbers[i]==numbers[j]:
print(numbers[i])
break |
#write a program to print the first half value in one line and the last half value in other line
input=(1,2,3,4,5,6,7,8,9,10,11)
print(input[:5])
print(input[5:10])
x=(1,2,3,4,5,6,7,8,9,10,11)
print(x[-5:])
print(x[-5:-1])
print(x[::-1])
print(x[-1]) |
#To find square root
x=float(input("enter the number"))
y=x**0.5
print("the square root of %0.3f is %0.3f"%(x,y))
|
#simple calculator using int concept
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
print(""""select your method
1.add
2.sub
3.mul""")
method=int(input("enter your method"))
a=int(input("number1"))
b=int(input("number2"))
if method==1:
print(add(a,b))
el... |
#Create a program to add even number as a seperate set from the exist set
st={23,512,24,75,46,91}
sum=0
lst=[]
for i in st:
if(i%2)==0:
lst.append(i)
sum=sum+i
print(set(lst))
print(sum)
|
#Initialize your list (L = []) and follow the commands given over lines.
#Each command will be of the commands given above. The extend() method will not be used. Each command will have its own value(s) separated by a space.
#Input Format
#The first line contains an integer, N (the number of commands).
#The N subs... |
# To add a new cell, type '#%%'
# To add a new markdown cell, type '#%% [markdown]'
#%%
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from matplotlib import cm
from matplotlib.ticker import FormatStrFormatter
#%%
data = np.loadtxt(open("X:\Skule\AI\EX1\ex1data1.txt", "r"), delim... |
#for i in range (2):
# print("Rahaf Zorba")
# number1 = 4
# print(number1)
# number2 = 2
# print(number2)
# num = [3,2,1]
# for i in num:
# print(i)
# print(i*2)
# #print()
"""
for i in range(2):
print(i*2)
"""
import turtle
# turtle.goto(100,100)
# this draws a square on the screen
turtle.begin_fill()
turtle.pen... |
import sqlite3
class UserdbManagement:
management_instances_created = 0
def __init__(self):
self.check_number_of_instances()
"""
Here we start all the points necessary to start this class
We need to connect to the database
and get the last ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 11:26:50 2019
@author:Luis
"""
suma = 1
segundasuma = 0
numero = eval(input("que se valor te intesa saber de la serie sucesion de finonachi ? "))
for i in range (numero-1):
total = suma + segundasuma
suma = segundasuma
segundasuma=total
print(total)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 15 20:38:18 2016
@author: primer.sfc
#容器和列表生成式的区别[] 和()
L = [x * x for x in range(10)]
print(L)
g = (x * x for x in range(10))
print(g)
for n in g:
print(n)
def fib(max):
n,a,b = 0,0,1
while n<max:
print(b)
a,b = b, a + b
n=n+1
re... |
def get_user_input(string, seek=1):
## string that is the value the user is entering
## if seek == 1 (default) enter float
## if seek == 2 enter string
## if seek == 3 enter integer
while True:
try:
if seek == 1:
val = float(raw_input('Enter %s: ' %(string)))
break
elif seek == 2:
val = str(raw... |
#Test use only
#Fibonacci sequence
Fibonacci = []
n = int(input("Please input number n "))
cout_num = 1
while cout_num <= n:
if cout_num == 1:
Fibonacci.append(0)
elif cout_num == 2:
Fibonacci.append(1)
else:
Fibonacci.append(Fibonacci[cout_num-3]+Fibonacci[cout_num-2])
cout_num... |
## Challenge 2: PyPoll
#
# # Notes to self:
# The file has a header.
# We need to calculate the following:
# 1. The total number of votes cast --> Simply report the sum of all the votes.
# 2. A complete list of candidates who received votes --> need a find the unqiue names from row[... |
#Import the random library
import random
#Print the game title
print("Let's Play Rock Paper Scissors!")
#Specify the three possible options
options = ["r", "p", "s"]
#Specify the computer Selection
computer_choice = random.choice(options)
#Requesting the user's choice
user_choice = input("What is your choice: (r)oc... |
from math import erf, sqrt
if __name__ == '__main__':
samples = int(input())
mean = int(input())
stdt_dev = int(input())
perc = float(input())
z = float(input())
stdt_sample = stdt_dev / sqrt(samples)
print(round(mean - stdt_sample * z, 2))
print(round(mean + stdt_sample * z, 2))
|
from Result import Result
class BaseException(Exception):
"""A Base Exception that all other Exceptions derive from."""
def __init__(self, code, desc):
self.code = code
self.desc = desc
def __str__(self):
return '{} {}'.format(str(self.code), str(self.desc))
def to_result(sel... |
# Name: Michael Long
# Course: CSC 480
# Instructor: Daniel Kauffman
# Assignment: Tile Driver I
# Term: Summer 2021
import queue
from typing import List, Tuple
class Heuristic:
@staticmethod
def get(tiles: Tuple[int, ...]) -> int:
"""
Return the estimated distance ... |
import random
myWords = ["hangman", "computer", "school", "math", "english"]
mysteryWord = random.choice(myWords)
#choice = input(" Type a word: ")
#if choice == myWords:
#print("Its a match")
#else:
#print("Not a match")
# How to check if a letter is in a word
#letter = input("Enter a letter: ")
... |
# worst-case: O(n²)
# avg-case: O(n²)
# best-case: O(n²)
def selectionSort(input):
for fillslot in range(len(input)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if input[location]>input[positionOfMax]:
positionOfMax = location
temp = input[fi... |
#encoding=utf-8
#朴素贝叶斯用于文档的分类
import numpy as np
# 构建测试数据
def load_data_set():
posting_list=[
['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
... |
from flask import jsonify, abort, make_response
questions = []
answers = []
all_questions_answers = []
class Questions():
"""
This class deals with all qestion related tasked, for users who attempt to fetch:
- fetch all questions
- fetch a specific questions or
- post all question
"""
def... |
intTest=1
print(intTest)
print(type(intTest))
stringTest="hello world"
print(stringTest)
print(type(stringTest))
c = True
print(type(c)) # <class 'bool'> -- 布尔型
e = [10, 20, 30]
print(type(e)) # <class 'list'> -- 列表
f = (10, 20, 30)
print(type(f)) # <class 'tuple'> -- 元组
h = {10, 20, 30}
print(type(h)) # <class 'set'> ... |
#Random number guessing game
#12JULY2020
#CTI-110 P5HW1 - Random Number
#Brian Telega
import random
def main():
print('MAIN MENU \n---------------\n 1) Play Game \n 2) Exit')
choice = input()
if choice == '1':
random_num()
if choice == '2':
exit(0)
def random_num():
number... |
#Program provinding the comparison of two rectangles area's
#18June2020
#CTI-110 P3T1-Area of a Rectangle
#Brian Telega
#Get the dimensions of R1.
length1 = int(input('Enter the length of rectangle 1:'))
width1 = int(input('Enter the width of rectangle 1:'))
#Get the dimensions of R2
length2 = int(input('Enter the le... |
def solution(s):
def check(s):
stack = []
while s:
stack.append(s.pop(0))
while True:
if len(stack) >= 2:
if stack[-1] == ']' and stack[-2] == '[':
stack.pop()
stack.pop()
... |
def solution(left, right):
answer = 0
def divisor(n):
answer = 1
for i in range(1,n):
if n % i == 0:
answer += 1
return answer
for num in range(left,right+1):
n = divisor(num)
if n % 2 == 0:
answer += num
... |
import board
import digitalio
# There are 16 registers on the Max7219
#It’s then a matter of sending commands to the Max7219 via the data in, clock and load line.
#For instance, to display the number 4 on digit 1 we would send the command 0x104 (0x01 : use
#digit 1, 0x04 : display the number 4). Which might look som... |
from tkinter import *
import time
# setting window
window = Tk()
window.minsize(width=300, height=100)
window.title("My First GUI Program")
# #
# # Label
# my_label = Label(text="Hiii", font=("Arial", 24, "bold"))
# my_label.pack()
# #
# # Using button
# def button_function():
# my_label.config(text=f"{input.get()}... |
# Modifying tuple contents with list
list1 = [('venky', 1), ('victory', 2), ('boom', 3)]
list2 = [4, 5, 6]
res=[(i[0],j) for i,j in zip(list1,list2)]
print(res) #[('venky', 4), ('victory', 5), ('boom', 6)]
|
s="hello world"
l=[]
for x in range(len(s)):
if s[x] in s[x+1:] and s[x] not in l:
l.append(s[x])
print(l)
|
'''
Hackerrank :https://www.hackerrank.com/challenges/itertools-product/problem
You are given a two lists A and B. Your task is to compute their cartesian product X.
Example
A = [1, 2]
B = [3, 4]
AxB = [(1, 3), (1, 4), (2, 3), (2, 4)] '''
from itertools import product
a=list(map(int,input().split()))
b=list(... |
s="python is best for AI and python is best for ML"
target="python"
print(s.find(target)) # it will give the first occurence of substring i.e 0 index else returns -1
print(s.rindex(target)) # it will give the last occurece of substring i.e 26th index else Throws Error
print(s.rfind(target)) # it will give the las... |
# Escribe un programa que pida un texto por pantalla, este texto lo pase como
# parámetro a un procedimiento, y éste lo imprima primero todo en minúsculas
# y luego todo en mayúsculas.
def mayusculas(texto_mayusculas):
texto_mayusculas = texto_mayusculas.upper()
return texto_mayusculas
def minusculas(texto_... |
x=int(input("enter the 1st number"))
y=int(input("enter the 2nd number"))
def add_sub(x,y):
c=x+y
d=x-y
return c,d
result=add_sub(2,3)
print(result)
2 |
def binarysearch(list,n):
l=0
u=len(list)-1
while l<=u:
mid=l+u//2
if (list[mid]==n):
return True
else:
if(list[mid]>n):
u==list[mid]
else:
l==list[mid]
list=[1,2,3,4,5,6,7,8]
n=4
if(binar... |
def fminele(heap,n):
minele=heap[0]
for i in range(1,n):
minele=min(minele,heap[i])
return minele
n=10
heap = [20, 18, 10, 12, 8,
9, 3, 5, 6, 8]
print(fminele(heap,n))
|
def print_matrix(game_matrix, grid_size):
for i in range(0, grid_size):
for j in range(0, grid_size):
print(game_matrix[i][j], end = " ")
print("")
def check_grid_for_winner(game_matrix, grid_size):
#Check diagonals
win_first_diagonal = game_matrix[0][0]
win_second_diagon... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 4 12:58:40 2021
@author: IBTIHAL
"""
def filtrered(phrase,n):
phrase=phrase.split()
filtrer = filter(lambda x: len(x)>n, phrase)
return list(filtrer) |
class Chips():
def __init__(self):
pass
def new_game_chips(self):
'''
Chips given while starting a game
'''
return 500
def available_bets(self,chips=500):
'''
Bets available for the player to choose from.
'''
lst = [20,50,100,250,500... |
def show_card(suite):
num_values = [str(i) for i in range(2,11)]
new_values = ['J','Q','K','A']
card_values = num_values + new_values
suites = {"spade":"♠","heart":"♥","clubs":"♣","diamond":"♦"}
sym=suites[suite]
for i in card_values:
print('-------')
print(f'|{sym} |')
... |
# https://leetcode.com/problems/kth-largest-element-in-an-array/
# Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
# Example 1:
# Input: [3,2,1,5,6,4] and k = 2
# Output: 5
# Example 2:
# Input: [3,2,3,1,2,4,5,5,6] and k =... |
# https://leetcode.com/problems/merge-two-binary-trees/
# Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
# You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum nod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.