text stringlengths 37 1.41M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 8 17:32:05 2020
@author: Ana
"""
#Napišite program koji će N puta ispisati poruku „
#Pozdrav!” i vrijednost kontrolne varijable. Korisnik unosi N.
N = int(input("Unesite broj: "))
for i in range(0 , N):
print(i,"Pozdrav")
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 15 16:50:14 2020
@author: Ana
"""
#Učitati niz X od n članova ispisati one članove niza X koj
#i su veći od prvog (zadnjeg) člana niZA.
lista = []
n = int(input("Unesite niz"))
for j in range(0,n):
broj = int(input("Unesite niz"))
lista.append(broj)
po... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 16 13:42:14 2020
@author: Ana
"""
#Napišite program u kojem se učitava
# prirodan broj, koji se zatim ispisuje u inverznom
# (obrnutom) poretku znamenaka. Ne pretvarati početni broj u string.
#Koristite funkciju „Obrni” koja prima jedan broj i v
#raća broj u inverznom po... |
import random
import sys
def script():
registry = random.randint(100, 2000)*99
print("Welcome to the Intergalactic Banking Clan Account Directory.")
print()
print("Now searching Registry #", registry)
print()
print("Standard systems have Accounts labled: 0-100")
print()
runtime... |
def input_tuple(a, b, c):
try:
user_input = str(input(a)).split(c)
tuple_result = list()
for x in range(0, len(b)):
tuple_result.append(b[x](user_input[x]))
return tuple(tuple_result)
except:
return ()
def input_tuple_lc(a, b, c):
try:
user_input... |
def compute_Pythagoreans(n):
try:
n = int(n)
pythagoreans = [(a, b, c) for a in range(1, n + 1) for b in range(1, n + 1) for c in range(1, n + 1) if
(a * a + b * b == c * c)]
return pythagoreans
except:
return []
print(compute_Pythagoreans(input("Enter n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 17:04:41 2018
@author: csolje
"""
FirstName = "Chris" # input("Enter your name: ")
def printName(name):
print("Hello", name, "how are you")
printName(FirstName)
printName("Henrik")
|
# open text file containg the words and add them to an array
hangman_words = []
hangman_text = open("hangmanwordlist.txt")
for word in hangman_text:
hangman_words.append(word.strip().lower())
hangman_text.close()
# make a function to return a string containing secret and guessed letters
def update_word(secret, ... |
from succ import Succ
Root = {'value': 1, 'depth':1}
def BFS_Tree(node):
nodes = [node]
visited_nodes = []
while len(nodes) > 0:
current_node = nodes.pop(0)
visited_nodes.append(current_node)
nodes.extend(Succ(current_node))
return visited_nodes
print(BFS_Tree(Root))
|
import sys
# Takes in an array of arguments, and return a dictionary of key-value pairs.
# For example ["--input=a","--output=b"] will result in
# {"input":"a", "output":"b"}
def parse_flag(arg_list):
result = {}
for arg in arg_list:
if arg[0:2] != "--" :
continue
equal_position = a... |
# receive input as integer
z = int(input('Enter integers : '))
print(z+1)
# casting practice
a=1
print(type(a))
x='1'
y='2'
print(x+y)
# lab 2-3-1
i=1234
s='1234'
print(i==s)
s=int(s)
print(i==s)
# lab 2-3-2
print('What is your name?')
x = input()
print('Hi! '+x)
print('The length of your name is:')
print(len(x))
... |
# Merge sort
def mergeSort(array):
if len(array) == 1:
return array
middleIdx = len(array) // 2
leftHalf = array[:middleIdx]
rightHalf = array[middleIdx:]
return mergeSortedArrays(mergeSort(leftHalf), mergeSort(rightHalf))
def mergeSortedArrays(leftHalf, rightHalf):
sortedArray = [None]... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def isEmpty(self):
if self.head == None:
return True
else:
return False
def enqueue(self, val):
cur = Node(val)
if self... |
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("welcome")
def open():
global my_image
top = Toplevel()
top.title("New window")
my_image = ImageTk.PhotoImage(Image.open("koro.png"))
my_label = Label(top, image=my_image)
my_label.pack()
btn = Button(top, text='... |
from tkinter import*
root=Tk()
root.title("hello")
def show():
mylabel=Label(root,text=var.get()).pack()
var=StringVar()
checkbtn=Checkbutton(root, text="check this box",
variable=var, onvalue="On",
offvalue="Off")
checkbtn.deselect()
checkbtn.pack()
myButton=Button(roo... |
#!/usr/bin/python3
n = int(input())
count = 0
while n // 100 != 0:
if n % 100 == 0:
count = n // 100
n = 0
else:
count += n // 100
n %= 100
if n // 20 != 0:
count += n // 20
n %= 20
if n // 10 != 0:
count += n // 10
n %= 10
if n // 5 != 0:
count += n // 5
... |
"""
Core class.
Node provides graphviz node creation and edge establishment interface.
A node can only have one parent, zero or more children.
"""
class Node:
def __init__(self, id, label="", parent=None, eLabel=""):
self.id = id
self.label = label
self.parent = parent
self.childre... |
***
Executed in leetccode: Yes
Challenges: Initially array was going out of bounds. Resolved it.
Time complexity: O(N)
Space complexity: O(N) with left and right array and O(1) using right variable
Comments: Given below.
***
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
length... |
import pandas as pd # We are working with dataframes and csv files
from fbprophet import Prophet
import matplotlib.pyplot as plt
#Read in NYT dataset
df = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us.csv")
#What will be the number of cases in the future?
df_deaths = df.groupby("date"... |
# The purpose of this script is to map the global positivity rates from February 2020 to the present. There is an animated feature so that users can view the dates across different periods in time. It reads in the data from owid covid data and isolates the columns "positive_rate", "location", and "date" and filters out... |
import time
problem_number = 30
test_input = 4
test_solution = 19316
problem_input = 5
def is_sum(power, number):
result = 0
for char in str(number):
result += power[int(char)]
return result == number
#Solution
def solution(limit):
result = 0
power = [i**limit for i in rang... |
import math, random
def generate_class_code(total_digits,existing_codes) :
digits = ''.join([str(i) for i in range(0,10)])
code = ""
while True:
for i in range(total_digits) :
code += digits[math.floor(random.random() * 10)]
if code not in existing_codes:
p... |
# # 1. 通过用户输入数字,计算阶乘。(30分)
# a=int(input("请输入数字:"))
# jie=1
# sum=0
# i=1
# # 3=1*1+1*2+2*3=9
# # 3*2*1
# while i<=a:
# jie=jie*i
# i+=1
# print(jie)
# # 将一个列表的数据复制到另一个列表中,并反向排序输出。
# list=[]
# list1=[]
# import random
# for i in range(5):
# list.append(random.randrange(10))
# print(list)
# list1=list
# prin... |
"""Write a program that will add 5 and loop until it reaches a number GREATER
than 100. It should then spit out the result AND tell the user how many times
it had to add 5 (if any)"""
def add5(io):
oi = 0
while io < 100:
io = io + 5
oi = oi + 1
print(io)
print(oi)
add5(5)
"""Write a pro... |
#!/usr/bin/python3
def matrix_divided(matrix, div):
"""
matrix_divided() - divides all elements of a matrix.
matrix: matrix list
div: number to divide each element in the matrix
Return: a new list matrix
"""
if type(matrix) != list:
raise TypeError(type_err)
for lis in matrix:
... |
#!/usr/bin/python3
def uniq_add(my_list=[]):
sum = 0
uniq = set(my_list)
uniq = list(uniq)
for i in range(len(uniq)):
sum += uniq[i]
return sum
|
#!/usr/bin/python3
def complex_delete(a_dictionary, value):
keys_to_be_del = []
if value not in a_dictionary.values():
return a_dictionary
for k, v in a_dictionary.items():
if v == value:
keys_to_be_del.append(k)
for key in keys_to_be_del:
if key in keys_to_be_del:
... |
#!/usr/bin/python3
"""Function number_of_lines"""
def number_of_lines(filename=""):
"""return the number
of lines in a text file
"""
with open(filename, encoding="utf-8") as file:
text = file.readlines()
return len(text)
|
#string quotes
#A string as a sequence of characters not intended to have numeric value. In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeabl... |
#Listas-- conjunto de datos almancenados en una variable.
#para crear una lista el nombre=[ele1,ele2...eleN]
#las listas son MUTABLES--PUEDE CAMBIAR
Estudiantes=['Yessica','Ariel','Gisela','Jesus']
notas=['Jesus',4.7,True]
#insertar elemento en una lista APPEND,LO HACE AL FINAL DE LA LISTA
Estudiantes.append('prof... |
if 5 > 2:
print('5 é de fato maior que 2')
else:
print('5 não é maior que 2') |
from tkinter import *
##creando la raiz:
root = Tk()
# con grid se imagina como cuadricula
label = Label(root, text="Nombre muy largo")
label.grid(row=0, column=0, sticky="e", padx=5, pady=5) #sticky es para que se justifique el texto al este, north, suth..
entry = Entry(root)
entry.grid(row=0, column=1, padx=5, pady... |
import sqlite3
conexion = sqlite3.connect("ejemplo.db")
# para ejecutar coigo sql
cursor = conexion.cursor()
#1. crear tabla
#cursor.execute("CREATE TABLE usuarios (nombre VARCHAR(100), edad INTEGER, email VARCHAR(100))")
# 2. insertar un registro a la tabla
#cursor.execute("INSERT INTO usuarios values ('Walter',29... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 12:34:46 2020
@author: DiSoJi
"""
import numpy as np
import perceptron_model as perceptron
import activation_functions as act_funcs
"""
print("Start")
#This area is in case you want to test something before starting everything
#Just erase the semicolons... |
"""
Defines how the style of the input text is to be parsed into a complete book.
This depends upon the formatting of the input, and needs to be customized
based on the style that it was originally written.
"""
class StyleSheet(object):
def __init__(self):
object.__init__(self)
def update_section(se... |
import numpy as np
from scipy.integrate import solve_ivp
def orbit_from_equations(a,e,i,O,w,t0,tf,ts):
'''
Propagates orbit using direct equations.
Returns position and velocity vectors of a satellite.
Parameters:
a (float): Semi-major axis
Larges... |
#!/bin/python3
denominations = [
200,
100,
50,
20,
10,
5,
2,
1,
]
def numdenoms_(index, n):
if len(denominations) <= index or n < 0:
return 0
if n == 0:
return 1
return sum([
numdenoms_(dex, n - val)
for [dex, val]
in enumerate(denominations)
if index <= dex
])
def numdenoms(n): return nu... |
#!/bin/python3
from itertools import permutations as perms
from functools import reduce as reduce
def maybePan(candidate):
try:
digits = {*list(range(10))} # Make a set containing every digit
for digit in candidate: # Ensure that each digit only occurs 1 time at maximum
digits.remove(int(digit)) #
... |
# -*- coding:utf-8 -*-
import datetime
import calendar
def MonthRange(year=None, month=None):
"""
:param year: 年份,默认是本年,可传int或str类型
:param month: 月份,默认是本月,可传int或str类型
:return: firstDay: 当月的第一天,datetime.date类型
lastDay: 当月的最后一天,datetime.date类型
"""
if year:
year = int(year)
... |
"""An API, or application programming interface, is an interface which, to put it generally, allows a user to send data to an application from another, or receive
data in an application from another. The Blue Alliance has an API called TBA API that can be used to request data about FRC. The data is returned in a format... |
# LECAVELIER Maeva - POUEYTO Clement G2
#Projet Version ++++ 1.6
import random
from turtle import *
from IA import *
nbAllum=0
ordiRetire=0
endgame=0
n=random.randint(1,2)
###########################################################################
#TIRE LES REGLES ALEATOIRES
########################################... |
from random import random, choice
from math import sqrt
# This generator simulates a "chaos game"
def chaos_game(n, shape_points):
# Initialize the starting point
point = [random(), random()]
for _ in range(n):
# Update the point position and yield the result
point = [(p + s) / 2 for p, s ... |
from math import atan2
def counter_clockwise(p1, p2, p3):
"""Is the turn counter-clockwise?"""
return (p3[1] - p1[1]) * (p2[0] - p1[0]) >= (p2[1] - p1[1]) * (p3[0] - p1[0])
def polar_angle(ref, point):
"""Find the polar angle of a point relative to a reference point"""
return atan2(point[1] - ref[1]... |
class Node:
def __init__(self):
self.data = None
self.children = []
def create_tree(node, num_row, num_child):
node.data = num_row
if num_row > 0:
for i in range(num_child):
child = create_tree(Node(), num_row-1, num_child)
node.children.append(child)
r... |
def verlet(pos, acc, dt):
prev_pos = pos
time = 0
while pos > 0:
time += dt
next_pos = pos * 2 - prev_pos + acc * dt * dt
prev_pos, pos = pos, next_pos
return time
def stormer_verlet(pos, acc, dt):
prev_pos = pos
time = 0
vel = 0
while pos > 0:
time +=... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if ... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def maxLevelSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
a = [root]
l... |
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
for ch in s:
if ch != ']':
stack.append(ch)
continue
sss = []
while stack:
v = stack.pop... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
"""
:type root: TreeNode
:type val: int
... |
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
dic = dict()
... |
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
m = {0: 0, 1: 0, 2: 0}
for n in nums:
m[n] = m.get(n) + 1
for i in range(m[0]):
nums[i... |
class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = []
for s in S:
if s == '(':
stack.append(s)
else:
v = 0
while stack:
last = st... |
class Solution(object):
def canMakeArithmeticProgression(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
sa = sorted(arr)
diff = sa[1] - sa[0]
for i in range(2, len(sa)):
if sa[i] - sa[i - 1] != diff:
return False
retu... |
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
sn = sorted(nums)
res = sn[0] + sn[1] + sn[2]
min_distance = abs(res - target)
for i in range(len(sn) - 2):
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
r... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if root ... |
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
return matrix and \
[*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])
def test_spiral_order():
s = Solution()
assert [1, 2, 3, 6, 9, ... |
class Solution(object):
def findAndReplacePattern(self, words, pattern):
"""
:type words: List[str]
:type pattern: str
:rtype: List[str]
"""
res = []
for word in words:
if len(word) == len(pattern):
d1, d2 = {}, {}
m... |
from functools import cmp_to_key
class Solution(object):
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
if sum(nums) == 0:
return "0"
def compare(x, y):
return int(y + x) - int(x + y)
sns = sorted([str(s) f... |
class Solution(object):
def getRow(self, rowIndex):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1, 1]
r = [1, 1]
for n in range(2, rowIndex + 1):
row = []... |
class Solution(object):
def longestWord(self, words):
"""
:type words: List[str]
:rtype: str
"""
sws = set(words)
ws = sorted(words, key=lambda x: len(x), reverse=True)
find = ""
length = 0
for word in ws:
if find and len(word) < le... |
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
if len(nums) * len(nums[0]) != r * c:
return nums
res = []
for i in range(len(nums)):... |
class Solution(object):
def subtractProductAndSum(self, n):
"""
:type n: int
:rtype: int
"""
p, s = 1, 0
while n:
a = n % 10
p *= a
s += a
n = n // 10
return p - s
def test_subtract_product_and_sum():
s = S... |
class Solution(object):
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
d = {}
for i in range(len(nums)):
a, b, c = d.get(nums[i], (0, 0, 0))
a = a + 1
if a == 1:
b = i
els... |
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 0:
return False
num = self.division(num, 2)
num = self.division(num, 3)
num = self.division(num, 5)
return num == 0 or num == 1
def di... |
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
... |
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
for i in range(0, len(s)):
if s[i] == s[len(s) - 1 - i]:
continue
if self.is_palindrome(s[i + 1:len(s) - i]):
return True
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.whole_tilt = 0
... |
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
length = len(nums)
for i in range(0, length - 1):
if nums[i] != 0:
continue
k = i
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
ret... |
class Solution(object):
def sortString(self, s):
"""
:type s: str
:rtype: str
"""
ss = sorted(s)
res = []
while ss:
ss, taken = self.walk(ss)
res.extend(taken)
if ss:
ss, taken = self.walk(ss[::-1])
... |
class Solution(object):
def powerfulIntegers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
xx = self.sqrt(x, bound)
yy = self.sqrt(y, bound)
res = set()
for i in range(0, xx):
a = p... |
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def postorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
res = []
if root is None:
... |
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.factor = 1000000
self.buckets = [False] * self.factor
def add(self, key):
"""
:type key: int
:rtype: None
"""
self.buckets[key % self.f... |
class Solution(object):
def largestPerimeter(self, A):
"""
:type A: List[int]
:rtype: int
"""
a = sorted(A)[::-1]
first = 0
second = a[0]
third = a[1]
for i in range(2, len(a)):
first = second
second = third
... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
re... |
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = {'M': 1000, 'D': 500, 'C': 100,
'L': 50, 'X': 10, 'V': 5, 'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i + 1]]:
... |
class Solution(object):
# 要注意是最长前缀!!!
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
i = 0
done = False
while i < len(strs[0]):
v = strs[0][i]
for j in rang... |
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
res = [[] for _ in range(numRows)]
row, down = 0, True
for i in range(len(s)):
res[row]... |
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
start, end = 0, 0
for i in range(1, len(s)):
if s[i] != s[0]:
end += 1
else:
if self.repeated(s, end - start + 1):
... |
class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
d = {}
for move in moves:
d[move] = d.get(move, 0) + 1
return d.get('U', 0) == d.get('D', 0) and \
d.get('L', 0) == d.get('R', 0)
def test_jud... |
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
r = []
for i in range(left, right + 1):
if self.is_self_dividing(i):
r.append(i)
return r
de... |
import heapq
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class CmpNode:
def __init__(self, node):
self.node = node
self.val = node.val
def __gt__(self, another):
return self.val > another.val
class Solution(obj... |
class Auto:
tuneado = False
def __init__(self, puertas=None, color=None):
self.pertas = puertas
self.color = color
if puertas is not None and color is not None:
print(f'Se ha creado un auto con {puertas} puertas y color {color}.')
else:
print('Se ha creado... |
#v = quantidade de numeros no vetor
#ai elevado a 2
#formula: 2^v - 1 = x
#soma dos numeros elevados ao que tem no vetor
def calculateFormula(sommatory):
return pow(2,sommatory) - 1
n = int(input())
numbers = list(dict.fromkeys(list(map(int,input().split()))).keys())
##v = len(numbers)
##for i in numbers:
## ... |
import sqlite3
from sqlite3 import Error
import MySQLdb
class database:
def execute_sql(self, sql):
self.conn = self.create_connection()
self.cur = self.conn.cursor()
self.cur.execute(sql)
self.conn.commit()
def create_sqlite_connection(self, db_file):
""" create a da... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 27 16:47:28 2018
@author: Administrator
"""
def list2string(spam):
s = spam[0]
for i in range(len(spam)-2):
i += 1
s += ', '+spam[i]
s += ' and '+spam[len(spam)-1]
print(s)
spam = ['apples','bananas']
list2string(spam) |
#!/usr/bin/python
# This program is to convert the band gap to the wavelength corresponding light.
import math
gap=float(input('Please input the gap(in ev) '))
ee=1.60217662 *10**-19 # elementary charge
cc=299792458.0 # speed of light
hh=6.62607004*10**-34 #Planck's constant
wl=hh*cc/gap/ee *10**9 # in nano mete... |
'''
http://developer.51cto.com/art/201403/430986.htm
常见的排序算法
2017-10-12
'''
class QuickSort:
def quickSort(self, nums):
'''
快速排序
'''
self.quickSortDetail(nums, 0, len(nums) - 1)
return nums
def quickSortDetail(self, nums, left, right):
if left >... |
import shlex, re
from typing import List
def split(s):
if '"' not in s:
return s.split(' ')
try:
return list(shlex.split(s))
except ValueError:
pass
def check_message(message: str, banned_words: List[str]):
for bw in banned_words:
if bw.startswith('re:'):
if... |
def findDelimitor(inputString):
for c in inputString:
if not( c.isdigit() or c.isalpha()):
return c
return ""
def findThingy(time, arrayDate, arrayFormat):
for i in range(0, 3):
if time == arrayFormat[i]:
return arrayDate[i]
return ""
def convert(inputString)... |
""" This program will open the quiz in an interactive window and have the user
complete the quiz through the web application."""
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__) # Create instance of web application
questions = {"What is the fifth month of the year?":"May",... |
'''
By Jason Krone for Khan Academy
Implementation of subset sum Utils
'''
BASE_TUPLE = (True, 0, 0)
def subset_sum_within_range(nums, n, delta):
'''
returns a subset of the given numbers that sum within the given range
(n - delta, n + delta) if such a subset exists. Otherwise, returns None
'''
... |
from Components.Component import Component
import sqlite3
class Database(Component):
"""
A database class that implements database creation and methods to read and write from the database.
"""
def __init__(self):
"""
Initializes a Database object, calls the parent constructor... |
# coding: utf-8
# In[1]:
import matplotlib.pyplot as plt
# In[2]:
get_ipython().magic(u'matplotlib inline')
# In[3]:
import numpy as np
# In[4]:
graph = []
min_val = 100
for i in range(1,10000000):
x = np.random.rand()
y = np.random.rand()
val1 = (x+y)/(x*1.0)
val2 = x/(y*1.0)
diff = ab... |
import random #imports random nuber
import os
playercount=0
compcount=0
while True:
print("\n\t\t\t\t!!!ROCK PAPER SCISSOR GAME!!!")
#displaying score
print("\nSCORE:")
print(f"computer:{compcount} player: {playercount} ")
#game algorithm
def game(comp,player):
if comp==player:
... |
#You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#... |
#Write a function to find the longest common prefix string amongst an array of strings.
#
# If there is no common prefix, return an empty string "".
#
# Example 1:
#
#
#Input: ["flower","flow","flight"]
#Output: "fl"
#
#
# Example 2:
#
#
#Input: ["dog","racecar","car"]
#Output: ""
#Explanation: There is no commo... |
import tkinter as tk # for the UI
import requests # I was having problems with the PIP on on my desktop It worked on my laptop But I test it on the replit IDE.
def getWeather(canvas):
# zip = textField.get()
api = "https://api.openweathermap.org/data/2.5/weather?zip=90210,us&appid=09d000cd760c0414... |
class Matrix:
def __init__(self, data):
self.data = data
def __str__(self):
return '\n'.join('\t'.join([f'{itm:04}' for itm in line]) for line in self.data)
def __add__(self, another):
try:
m = [[int(self.data[line][itm]) + int(another.data[line][itm]) for it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.