text stringlengths 37 1.41M |
|---|
# Given a square matrix, calculate the absolute difference between the sums of its diagonals.
# Complete the diagonalDifference function which takes a integer array as a parameter and return an integer denoting the absolute difference between the diagonal sums.
# Constraints
# Raw Input Format
# The first line co... |
import sys
import re
import itertools as ite
import random
'''
args = str(sys.argv[1])
args_split = args.split(" ")
number = args_split[0]
numbers = [] #List to hold the numbers from Command Line
calc = args_split[1] #Variable to hold the number to evaluate expressions to (gotten from Command Line)
'''
num,... |
""" OPeradores encadenados """
menor = 1 <2 and 2 < 3
print (menor)
menor_2 = 1 < 2 < 3
print(menor_2)
mayor = 3 > 2 > 1
print(mayor)
""" Comprobar si un número se encuentra entre 0 y 100 """
numero = 30
if numero >=0 and numero <= 100:
print(f"El número {numero} se encuentra entre 0 y 100")
else:
print(f"... |
from typing import List
students = "mario, fernando"
def menu():
print("--APLICACION CRUD: INSCRIPCION ESTUDIANTES--")
print("="*50)
print("Escoja su opción: ")
print("[C] - Crear estudiante" )
print("[R] - Listar estudiantes" )
print("[U] - Actualizar estudiante" )
print("[D] - Borrar es... |
"""
Escribir un programa qwue pregunte el nombre completo del usuario en consola
y después muestre por pantalla el nombre completo del usuario tres veces,
una con todas la letras minúsculas, otra con todas la letras mayuúsculas
y otra con la primera letra del nombre y de los apellidos en mayúscula.
El suario puede int... |
#!/usr/bin/dev python3
# -*- coding: utf-8 -*-
"""
使用list和tuple
"""
"""
list
Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b = ['1', '2', '3', '4']
print(a) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(b) # ['1', '2', '3', '4']
# 用len()函数可以获得list元素的个数
print(len(a)) # 10
print... |
#!/usr/bin/env python3
# 命令行直接运行py文件的方法
# 在Windows上是不行的,但是在Mac和Linux上可以,方法是在.py文件的第一行加上一个特殊的注释
# 在linux命令行运行Python,需要通过命令给x.py以执行权限:
# chmod 744 x.py
# 用print()在括号中加上字符串,就可以向屏幕上输出指定的文字。
print('hello, world') # hello, world
# print()函数也可以接受多个字符串,用逗号“,”隔开,就可以连成一串输出,print()会依次打印每个字符串,遇到逗号“,”会输出一个空格
print('wang', 'da'... |
#!/usr/bin/env python3
# --*-- coding: utf-8 --*--
"""
切片
取一个list或tuple的部分元素是非常常见的操作
"""
# 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环
# 对这种经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了切片(Slice)操作符,能大大简化这种操作
# 取前3个元素,用一行代码就可以完成切片
l = [1, 2, 3, 4, 5]
# [1, 2, 3]
print(l[:3]) # 从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素, 如果第一个索引是0,可以省略
print(l[0... |
# Python Ver: 3.9
#
# Author: Britnee Murrin
#
# Purpose: create a user interface to create a one line webpage, using Tkinter
#
from tkinter import *
import tkinter as tk
import webbrowser
# import associated module files
import webpage_main
import webpage_func
# define user interface design and structure
def load_g... |
# Python Ver: 3.9
#
# Author: Britnee Murrin
#
# Purpose: create a user interface to create a one line webpage, using Tkinter
#
from tkinter import *
import tkinter as tk
import webbrowser
# import associated module files
import webpage_gui
import webpage_func
# create user window
class ParentWindow(Frame):
def ... |
#
# Create a program that transfers files from one folder to another
# program iterates through files to transfer files only modified current day
#
import shutil
import os
import time
# set where the source of the files are
source = '/Users/Britnee Murrin/OneDrive/Desktop/FolderA/'
# set the destination path
destina... |
meal = {
"entree": "pesto chicken",
"drink": "fizzy water",
"dessert": "ice cream"
}
# print(meal["dessert"]);
# print("Tonight I will have %s for dinner, with %s for dessert" % (meal["entree"], meal["dessert"]))
# # If the key dessert is found in the dictionary meal
# # THEN print the first statement
... |
# -*- coding: utf-8 -*-
#função recebe um arquivo de cadastro e devolve uma lista de dicionarios com cada cadastro
def parse_cadastros(cadastrados):
cadastros_list = []
#separando as linhas
cadastros_raw = cadastrados.split('\n')
#tirando elemento nulo
cadastros_raw.pop()
for cadastro in cada... |
# A very basic representation of a GUI
# This is a sample of a very basic GUI screen. It displays a window with a button.
# Author: Selina Dennis, 2010-2016
from Tkinter import *
# A mostly pointless GUI Application created to show some of the basic
# widgets available in Tkinter. The name of your class should... |
import turtle
#import winsound
wn=turtle.Screen()
wn.title("pong by SAKSHI")
wn.bgcolor("white")
wn.setup(width=800,height=600)
wn.tracer(0)
#Score
score_a=0
score_b=0
# paddle A
paddle_a=turtle.Turtle() # small T is module name capital T is a class name
paddle_a.speed(0) # this is not the speed for paddle moves o... |
def scatter_add(a, slices, value):
"""Adds given values to specified elements of an array.
It adds ``value`` to the specified elements of ``a``.
If all of the indices target different locations, the operation of
:func:`scatter_add` is equivalent to ``a[slices] = a[slices] + value``.
If there are mu... |
# Chapter 1: Linear models
# Author: Jesús Urtasun - 2020
# Exercise 1: Load data
import numpy as np
import matplotlib.pyplot as plt
# Load datasets
print("\nLoad datasets")
xy_training = np.load("../data/linear_training.npy")
xy_testing = np.load("../data/linear_testing.npy")
print("train set:\n{}\ntest set:\n{}".f... |
# Have to come up with a way to count the number of words from the attempt
# Have to also come up with a way to calculate WPM based on whether or not the attempt == phrase
# Have to come up with a way to get number of correct words from attempt compared to the phrase
from phrase import Phrase
test = Phrase("Try this... |
"""Counting letters in a string."""
__author__ = "730397389"
# Begin your solution here...
letter = str(input("What letter do you want to search for?: "))
word = str(input("Enter a word: "))
i = 0
counter = 0
while i < len(word):
if letter == word[i]:
counter = counter + 1
i = i + 1
else:
... |
import argparse
from datetime import datetime
def get_arguments():
parser = argparse.ArgumentParser(description='Calculate number of days between two dates')
parser.add_argument('starting_date',
help='Starting date; should be in the format "dd/mm/year"')
parser.add_argument('end_da... |
import math
class HeartbeatHistory():
def __init__(self, maxSampleSize):
if maxSampleSize < 1:
raise ValueError("MaxSampleSize must be >= 1, got " + str(maxSampleSize))
self.maxSampleSize = maxSampleSize
self.intervals = list()
self.intervalSum = 0.0
self.squared... |
import turtle
import time
class Snake:
STARTING_POSITIONS = [(0, 0), (-10, 0), (-20, 0)]
MOVE_DISTANCE = 10
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
def __init__(self, ):
self.snake = []
self.set_body()
self.head = self.snake[0]
def set_body(self):
for ... |
from swampy.TurtleWorld import *
import math
world = TurtleWorld()
bob = Turtle()
susan = Turtle()
tom = Turtle()
bob.delay = 0.01
def polyline(t, n, length, angle):
"""Draws n line segments with the given length and
angle (in degrees) between them. t is a turtle.
"""
for i in range(n):
fd(t,... |
# https://programmers.co.kr/learn/courses/30/lessons/42579
def solution(genres, plays):
play_count = {}
play_count_rev = {}
categorized = {}
length = len(genres)
answer = []
for i in range(length):
genre, count = genres[i], plays[i]
if genre not in categorized:
... |
# https://www.hackerrank.com/challenges/time-conversion/problem
def timeConversion(s):
hour = s[0:2]
minute = s[3:5]
second = s[6:8]
is_afternoon = True if s[8:] == "PM" else False
return convert_to_time(hour, minute, second, is_afternoon)
def convert_to_time(hour, minute, second, is_afternoon... |
# https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
visited = []
... |
# https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.queue = None
self.dict = ... |
# https://leetcode.com/problems/maximum-depth-of-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.queue = None
self.depth = {}
... |
from valid import *
from human import Human
def setup():
print("\033c")
print("Please enter in the following information: ")
name = input("What is your name: ")
age = int(input("What is your age: "))
while not validSetup(age):
age = int(input("What is your age: "))
gender = input("what is your gender:... |
# handle negation
import csv
def getCompanyName():
companies = []
# NSE Companies list
reader = csv.DictReader(open('/home/varshav/work/PycharmProjects/nse_mapping.csv', 'rb'), delimiter=',')
for row in reader:
company_name = row.get('Company')
words = company_name.lower().split(" ")
... |
# https://classroom.udacity.com/courses/ud513/lessons/7122604912/concepts/79198839630923
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self... |
#python3
# Problem description
# 2SAT problem is special case of n-sat problem and is reduced to linear graph-algorithm
# We should introduce implication for each "or" clause: x || y. The implication is x => y.
# we build implicaitons in form: !x => y which means "if x is zero, y should be one"
# now we build directed... |
#!/usr/bin/python
# coding: utf8
"""
Структура данных SET.
"""
class Set(object):
"""
Множество.
Мтетоды:
- - Разность множеств
+ - Объединение множеств
/ - Пересечение множеств
// - Семмитричная разность множеств.
"""
def __init__(self, value=None):
se... |
from typing import Tuple
filename = "input.txt"
NUM_ROWS = 128
NUM_COLS = 8
def bin_part(letters: str, num_total: int) -> int:
cur = list(range(num_total))
for letter in letters:
if letter in ("F", "L"):
cur = cur[: len(cur) // 2]
elif letter in ("B", "R"):
cur = cur[l... |
# Tree
class TreeNode:
def __init__(self,elem=None,lchild=None,rchild=None):
self.elem=elem
self.lchild=lchild
self.rchild=rchild
class Tree:
def __init__(self,root=None):
self.root=root
def append(self,elem):
node=TreeNode(elem)
q=[self.root]
whi... |
'''
并查集 Disjoint Set
应用:连接问题(Connectivity Problem)
- 判断一个图,是否存在环(连通)
- 判断网络中节点间的连接状态
- 数学中集合类的实现
操作:O(h) h为树的高度
- 查(根) :find_root(x)
- 并(根) :union(x,y)
- 判(集合):isConnected(x,y)
优化:压缩查找路径 (Path Compression)
- find_root
+ 压缩查找节点到根这条路径上的跳级节点,指向根(压缩一半)
+ 压缩查找节点到根这条路径上所有节点,都指... |
from Functions import *
import random as rnd
def main():
file_name = "or.txt"
training_x, training_y, m, num_atrib = load_data(file_name)
mu = 0.1
num_iterations = 50
umbral = lambda x: 0.0 if x < 0.0 else 1.0
# pesos iniciales aleatorios
rnd.seed(1000)
#w = [random.uniform(-1,1) for... |
# This program asks the user to enter 20 names, separated by commas,
# into a string array,
# then sorts that array in alphabetical order and displays
# its contents.
# The program uses the "bubble sort" method.
# Funtion gets user input
def get_user_input():
list_of_names = []
separator = ","
list_of_name... |
def bubble(L):
"""Bubble sort
Parameters:
L (list): Unsorted list.
Returns:
L (list): Sorted list.
"""
swapped = None # set to None to kick start the sort.
while swapped == True or swapped == None:
# if previous iteration of bubble sort was done, or this is the fir... |
################################################ def csv_sort_dedup ###########################################################
import csv
import gzip
from operator import itemgetter
def csv_sort_dedup(input_file, output_file, sort_col_index=(0,),sort_col_type=[],tokeep = 'first'):
'''
Warning: not fully va... |
#
# 2588.곱셈
# (세 자리 수) × (세 자리 수)는 다음과 같은 과정을 통하여 이루어진다.
# (1)과 (2)위치에 들어갈 세 자리 자연수가 주어질 때 (3), (4), (5), (6)위치에 들어갈 값을 구하는 프로그램을 작성하시오.
# 입력
# 첫째 줄에 (1)의 위치에 들어갈 세 자리 자연수가, 둘째 줄에 (2)의 위치에 들어갈 세자리 자연수가 주어진다.
# 출력
# 첫째 줄부터 넷째 줄까지 차례대로 (3), (4), (5), (6)에 들어갈 값을 출력한다.
#
# a=int(input())
# b=int(input())
# temp=b
# while ... |
def solution(ball, order):
answer = []
for i in range(len(order) - 1, -1, -1):
for j in range(0, i + 1):
if order[j] == ball[0]:
answer.append(ball[0])
ball.pop(0)
order.pop(j)
break
elif order[j] == ball[-1]:
... |
def solution(depar, hub, dest, roads):
answer = 0
# 출발지 -> 물류센터 경우의 수 + 물류센터 -> 도착지 경우의 수
depar = route(depar, hub, roads)
des = 0
for r in roads:
des += route(hub, dest, roads)
answer = depar + des
return answer
def route(dep, des, roads):
print(dep, des, roads)
count = 0
... |
#!/usr/bin/python3
'''
Title: Find URLs
Version: 1.1
Created by: Jeremiah Bess - jeremiah.bess@gmail.com
Description: Script find and output all URLs in office documents
Resources:
* https://towardsdatascience.com/how-to-extract-data-from-ms-word-documents-using-python-ed3fbb48c122
Revisions:
1.0 - 23 Aug 2019 - Initia... |
import pandas as pd
import numpy as np
class UCFRecommender():
'''
Class: User Based Collaborative Filtering Recommendations
'''
def __init__(self, df, top_n=10):
self.top_n = top_n
self.df=df
self.user_item=self.create_user_item_matrix()
'''
1. Use the function below t... |
def Selection_Sort(Liste):
def min(Liste):
min = Liste[0]
index_min=0
for j in range(len(Liste)):
if Liste[j] < min:
min = Liste[j]
index_min = j
return index_min
for i in range(len(Liste)):
if len(Liste[i:])>1:
ind... |
import math
list = []
num = int(input('Co bao nhieu gia tri: '))
for n in range(num):
gia_tri = input('Nhap gia tri: ')
list.append(gia_tri)
a=print("Phan tu lon nhat :",max(list))
b=print("Phan tu nho nhat :",min(list))
|
#Spielen mit Datentypen
text=input("Gebe einen Text ein: ")
print("Du hast diesen Text eingegeben:", text)
text=text.upper()
print("Dein Text umgewandelt: ", text)
print("Datentyp Deiner Eingabe ist:", type(text))
#ab hier läuft es nur weiter, wenn eine Zahl eingegeben wurde
text=eval(text)+1000
print("Dein T... |
#Übung: Programm zum Prüfen, ob eingeben Userdaten (Login-Name, Passwort) in der User-Liste vorhanden sind
def login_prüfen(username_eingabe, password_eingabe):
# Funktion prüft, ob in der Liste ein passendes Paar zum übergebenen Paar vorhanden ist
# Teil 1: Aufbau der unveränderlichen User-Liste --> diese noc... |
'''
URL: https://practice.geeksforgeeks.org/problems/sum-of-numbers-or-number/0
Problem Name: Sum of two large numbers
Difficulty: Basic
Given two non-negative numbers X and Y. The task is calculate the sum of X and Y.
Input:
The first line of input contains an integer T denoting the number of... |
t = int(input()) #number of test cases
for i in range(t):
text = input().strip()
first = []
second = []
if len(text) % 2 == 0: #string contains even number of characters
first, second = text[:len(text)//2], text[len(text)//2:] #splitting string into half
first = list(first)
... |
# Implement a stack that has the following methods:
# push(val), which pushes an element onto the stack
# pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null.
# max(), which returns the maximum value in the stack curren... |
from random import randint, seed
# Code inspired by the post:
# https://runestone.academy/runestone/books/published/pythonds/Trees/BinaryHeapImplementation.html
# Retrieve top (min in case of MinHeap) --> O(1)
# Retrieve top + delete top --> O(logn)
# Insert element --> O(logn)
# Useful for priority queues, schedule... |
# Given a function that generates perfectly random numbers between 1 and k (inclusive),
# where k is an input, write a function that shuffles a deck of cards represented
# as an array using only swaps.
# It should run in O(N) time.
# Hint: Make sure each one of the 52! permutations of the deck is equally likely.
f... |
# Imagine we have a probability distribution as follows
# pr = [0.2, 0.3, 0.1, 0.4] correspoding to numbers
# n = [0, 1, 2, 3]
# write a function that draws k elements of this distribution
from random import random, seed
from collections import Counter
from typing import List
def binary_search(cum_sum, low, high, va... |
mountains = {
"Mount Everest": 8848,
"K2": 8611,
"Kangchenjunga": 8586,
"Lhotse": 8516,
"Makalu": 8485,
}
print("Mountain names:")
for name in mountains.keys():
print(f"\t{name}")
print()
print("Mountain heights:")
for height in mountains.values():
print(f"\t{height}")
print()
print("Moun... |
#Modul to make geometry object 2d
#Which have feature to prints =
#1. Square
#2. Rectangle
#3. Right triangle
#4. Equilateral traingle
#function to print square object
def printSquare (side):
for i in range(side):
#To print loop star without a newline
print("* "*side)
#function to ... |
"""
This program takes an interger number 'n' and print
the pattern below in 'n' rows
*
* *
* *
* *
* *
* *
*
"""
def main():
row = int(input("Enter Number of Rows: "))#take input from user
pattern(row)#calling function to print pattern
def pattern(row):
"""Purpose: This functi... |
def fun():
m=int(input('\nEnter number of element'))
print('Enter the element of list')
list2=[]
for j in range (m):
nli=input()
if nli=='[':
list2.append(fun())
print('Nested list end')
print('\nEnter the outer list element again')
else:
... |
#proggram to find maximum and minimum from vector
def main():
#taking input from user for demension of vector
d=int(input('Enter the number of element in vector: '))
#taking input form user from user
print('Enter the vector')
vector=[int(input()) for i in range (d)]
#print the vector
prin... |
#Program to find out Determinant of matrix
from copy import deepcopy
def main():
#Taking input from user for order of matrix
n=int(input("Enter the order of the matrix: "))
#declare list for matrix and taking input from user for element of matrix
print("Enter the elements of the matrix one by one:")
... |
#Program to check if graph is planer or not
#this program not work for K3,3
def main():
#taking total number vertex and edges from user
vertex=int(input("Enter the Total number of vertex in the graph: "))
edges=int(input('Enter the Total number of edges in the graph: '))
#max edge of vertex
max=ve... |
class queue:
def __init__(self,size):
self.size=size
self.list1=[]
self.front=0
self.rear=-1
def enqueue(self,element):
if (self.front==0 and self.rear==(self.size-1)) or (self.rear+1==self.front and self.rear!=-1):
print(" QUEUE IS FULL ")
print... |
#program for recurrence relation T(n)=2T(n/2)+1. i.e. Merge Sort
import math
#function to merge the two sub list
def merge(left_numList,right_numList,numLIst):
i=0
j=0
k=0
#merging two sub list
while i<len(left_numList) and j<len(right_numList):
if left_numList[i]<right_numList[j]:
... |
'''
program to
a. to count frequency of items in a given list and return the frequency.
b. In a, also return the position of each item in the given list
'''
def main():
n=int(input('Enter number of element in list'))#Taking input for number of element in list
list1=[]#create empty list
print('Enter the ele... |
class stack:
#constructor
def __init__(self):
self.stacks=[]
#Function to push element in stack
#paramater: element which is push to stack
#return nothing
def push(self,element):
#push element to stack
self.stacks.append(element)
#function to pop the last/... |
def main():
num=int(input('Enter the number'))#taking number from user as input
if checkHappyNumber(num)==True: #calling the function and checking if its retuen true or not
print(num,'is Happy Number') #print the statement if condition is true
else:
print(num,'is not Happy Number') #pri... |
'''
Program to find tge sum of nth terms of given series
e^x = 1+x/1!+x^2/2!-x^3/3!+.........
'''
def main():
n=int(input('Enter the nth term: '))#take input from user for nth term
x=int(input("Enter the X value: "))#take input from user for values of
findSum(n,x)#calling function to find out sum of series
... |
#program to find out sum of the diagonal element of matrix
def main():
n = int( input("Enter Square matrix Size : ")) #asking number of rows from user for matrix
#declaration of list for matrix
matrix=[[0 for j in range (0 , n)] for i in range (0 , n)]
#taking input from user for elements of matrix
... |
#essa versao da funcao recebe como argumentos
#os valores das matrizes nas posicoes i,j, bem como
#os indices de i,j.
#a funcao armazena o resultado na matriz
#result, passada por referencia
def add(val1, val2, i, j, result):
result[i][j] = val1 + val2
def unroll(args, func, method, res):
#itera em ... |
import tkinter as tk
import random
root=tk.Tk()
root.title("Guessing Random number")
root.resizable(0,0)
# width and height of application
width=500
height=600
root.geometry(f"{width}x{height}")
title_lbl=tk.Label(root,text="Guessing Number",font=('times new roman',30,'bold'),bg='grey',fg='white')
title_lbl.pack()
... |
# The ipaddress module includes classes for working with IPv4 and IPv6 network addresses.
# The classes support validation, finding addresses and hosts on a network, and other common
# operations.
# The most basic object represents the network address itself. Pass a string, integer, or byte
# sequence to ip_addre... |
# A Future represents the result of work that has not been completed yet. The event loop
# can watch for a Future object’s state to indicate that it is done, allowing one part of an
# application to wait for another part to finish some work.
# A Future acts like a coroutine, so any techniques useful for waiting fo... |
#!usr/bin/env/python3
# The optional initializer argument is placed at the front of the sequence and processed
# along with the other items. This can be used to update a previously computed value with
# new inputs.
import functools
def do_reduce(a, b):
print('do_reduce({}, {})'.format(a, b))
return a +... |
class MyIterator(object):
"""
Contstructor
"""
def __init__(self, letters):
self.letters = letters
self.postion = 0
def __iter__(self):
"""
Returns itself as an iterator
"""
return self
def __next__(self):
"""
Returns the next letter in sequence or
raise StopIteration
"""
... |
#!usr/bin/env/python3
"""Mix-in is a class that defines only a small set of addtional methods for its child
to provide. It don't define thier own instance attributes nor require their __init__ constructor to bec called
"""
class ToDictMixin(object):
def to_dict(self):
return self._traverse_dict(self.__d... |
import time
import asyncio
async def main():
print(f'{time.ctime()} Hello')
await asyncio.sleep(1.0) # wainting for one minute
print(f'{time.ctime()} Goodbye!')
# asyncio.run(main()) # using asycio.run in the func avoid more stuffs like get_event_loop() etc
loop = asyncio.get_event_loop()
c... |
# The ThreadPoolExecutor manages a set of worker threads, passing tasks to them as they
# become available for more work. The next example uses map() to concurrently produce a set
# of results from an input iterable. The task uses time.sleep() to pause a different amount
# of time to demonstrate that, regardless of ... |
# The first step when using argparse is to create a parser object and tell it which arguments
# to expect. The parser can then be used to process the command-line arguments when the
# program runs. The constructor for the parser class (ArgumentParser) takes several arguments
# to set up the description used in the h... |
def detectCapitals(word):
return word == word.upper() or word == word.lower() or word == word.capitalize()
print(detectCapitals('FlaG')) |
# zip() stops when the first input iterator is exhausted. To process all of the inputs, even if
# the iterators produce different numbers of values, use zip_longest().
# By default, zip_longest() substitutes None for any missing values. Use the fillvalue
# argument to use a different substitute value.
from iter... |
#!usr/bin/env/python3
# The reduce() function takes a callable and a sequence of data as input. It produces a
# single value as output based on invoking the callable with the values from the sequence and
# accumulating the resulting output.
import functools
def do_reduce(a, b):
print('do_reduce({}, {})'.fo... |
# A question mark (?) is another wildcard character. It matches any single character in that
# position in the name.
import glob
for name in sorted(glob.glob('example?.txt')):
print(name)
for name in sorted(glob.glob('dir/*[0-9].*')):
print(name) |
#!usr/bin/env/python3
# Accept Function Instead of Classes for Simple Interface
from collections import defaultdict
# missing keys
def log_missing():
print('Key added')
return 0
current = {'green': 12, 'blue': 3}
increments = [
('red', 5),
('blue', 17),
('orange', 9),
]
results = defaultdict(log... |
import socket
import sys
# Create a TCP/IP socket.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port on the server
# given by the caller.
server_address = (sys.argv[1], 10000)
print('connecting to {} port {}'.format(*server_address))
sock.connect(server_address)
try:... |
#!usr/bin/env/python3
"""Prefer Public Attribute Over Private Ones
Public Attribute can be accessed by anyone using
the dot operator on the object
"""
class MyObject(object):
def __init__(self):
self.public_field = 5
self.__private_field = 10
def get_private_field(self):
return self.__private_... |
def longestSubstring(word):
dict_ = {}
start = 0
results = 0
for index, value in enumerate(word):
if value in dict_:
start = max(start, dict_[value] + 1)
dict_[value] = 1
results = max(results, index - start + 1)
return results
|
#!usr/bin/env/python3
"""Telecommunication Data Bundle Purchase Menu"""
# By Linux(Software Engineer)
import random
from functools import wraps
OPTIONS = ['BigTime Xtra', 'Fuse Xtra', 'Xtra Unlimited Calls']
OPTIONS_ONE = ['25MB + 25MB @50p', '65MB + 65MB @1GH', '150MB + 150MB @2GH']
def decorator(func):
... |
#!usr/bin/env/python3
"""Python program to find the element occurring odd number of times"""
def getOddOccurrence(arr):
# initialize result
res = 0
# Traverse the array
for element in arr:
# XOR with the result
res = res ^ element
return res
# Test array
arr = [2,3,5,4,5,2,4,3,5,2,4,4,2]
... |
class Map:
def __init__(self):
# variables de class
self.nb_tiles_X = 12 # int : nb de tuiles sur X
self.nb_tiles_Y = 12 # int : nb de tuiles sur Y
self.file_map_content = "" # string : contenu du fichier lvl.txt
self.lvl = []
... |
import numpy as np
import matplotlib.pyplot as plt
from interpolation import accurate_model
N = 1000
I0 = 1
r_beta = 1
M = 1000
def get_approx_func(bound):
def approx_func(x):
return 1000 / (1 + 999 * np.power((1 + -x / M), M))
return approx_func
if __name__ == "__main__":
bound = input("Ple... |
message = "Hello Eric, would you like to learn some Python today?"
print(message)
name = "hayley simmons"
print(name.title())
name = "hayley simmons"
print(name.upper())
print(name.lower())
first_name = "hayley"
last_name = "simmons"
full_name = f"{first_name} {last_name}"
print(full_name)
first_name = "hayley"
las... |
import itertools
# Interesting material: https://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in-a-list-sum-up-to-a-certain-number
# Challenge: given a list of integers, find the product of the integers that sum to 2020. part1: 2 integers that sum, part 2: 3 integers that sum.
with open('inpu... |
def main():
with open('directions.txt', 'r')as file:
directions = [row.strip() for row in file]
bearings = ['N','E','S','W']
print(f"Part 1: {Part1(directions, bearings)}")
print(f"Part 2: {Part2(directions, bearings)}")
def Part1(directions, bearings):
move_count = {}
for bearing in bearings:... |
#!/usr/bin/env python
#-*-coding=utf8-*-
import url_manager
import html_output
import html_parser
import sys
import html_downloader
class SpiderMain(object):
def __init__(self):
self.urls = url_manager.UrlManager() #url管理器
self.downloader = html_downloader.HtmlDownloader() #网页下载器
self.parser = h... |
def appleQ():
apple_Question = int(input("How many apples do you want to buy? "))
return apple_Question
def orangeQ():
orange_Question = int(input("How many oranges do you want to buy? "))
return orange_Question
def price(apple_Number, orange_Number):
apple_Price = apple_Number * 20
orange_Pr... |
#This is our help-function file reader. The user may input 'help-function' wih or without a parameter
#In doing so, the proper text file with detailed information will be printed onto the console
def function_showFunc(fileName="help-function"):
try:
with open("help/" + fileName + ".txt", 'r') as helpFile:
... |
class Stack(object):
def __init__(self):
# initializing stack list
self.item = []
# print length of the stack if instance called like len(stack)
def __len__(self):
return len(self.item)
# every call with value will be pushed to the stack
def push(self, value):
se... |
def insertionSort(arr, s, e):
for j in range(s+1, e+1):
key = arr[j]
i = j - 1
while i >= s and arr[i] > key:
arr[i + 1] = arr[i]
i = i - 1
arr[i + 1] = key
def _quicksort(arr, s, e):
if (e - s) > 2:
q = partition(arr, s, e)
_quicksort(arr, s, q-1)
_quicksort(arr, q+1, e)
... |
def printSpiral(matrix):
row = len(matrix)
col = len(matrix[0])
curRow = 0
curCol = 0
while curRow < row and curCol < col:
for i in range(curCol, col, 1):
print(matrix[curRow][i])
curRow += 1
for i in range(curRow, row, 1):
print(matrix[i][col-1])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.