text stringlengths 37 1.41M |
|---|
a = [10,20,30]
# add with append() method
a.append(40)
print(a)
# add with insert() method
a.insert(2, 50)
print(a)
# with method extend()
a.extend([66,77,88])
print(a)
# append will always count a data as one data
b = [10,20]
b.append([30,40])
print(b)
# if list added by extend() method, the string will be input ... |
# Filtering List
a = [1,-3,4,-2,5,7,-4]
b = [1,2,3,4,5,6]
# Filtering Negative Number
negatif = [i for i in a if i < 0]
print(negatif)
# Filtering positive number
positive = [i for i in a if i > 0]
print(positive)
# Filtering ganjil genap
c = ['genap' if i % 2 == 0 else 'ganjil' for i in b]
print(c)
# Filtering squ... |
cart = []
f = open('input').read()
santa = f[::2]
robo_santa = f[1::2]
def santa_tracker(nick):
x = 0
y = 0
counter = 0
for i in nick:
# print(i)
# write arrow to x/y. Save every step.
# Compare new step to all old steps: if duplicated, do not increment counter
if i ==... |
from __future__ import print_function
import json
import requests
import urllib
# TODO: do I need urllib?
# Fall back to Python 2's urllib2 and urllib
from urllib2 import HTTPError
from urllib import quote
from urllib import urlencode
import config
# OAuth credentials
CLIENT_ID = config.YELP_CLIENT_ID
CLIENT_SECRET ... |
import hashlib, binascii, os
import csv
from tkinter import messagebox
PSEUDOS_FILE = "pseudos.csv"
PSEUDO_DEFAULT_INPUT = "Enter Username"
# hash : the simple hash of password
def hash(password) :
hash_object = hashlib.sha512( password.encode() ).hexdigest()
return hash_object
# pseudoIsExiste : the pseudo ... |
import sqlite3
# Create a database in RAM
db = sqlite3.connect('mydbCommune.db')
# Creates or opens a file called mydb with a SQLite3 DB
db = sqlite3.connect('mydbCommune.db')
####################################################"DROP ALL TABLE"###############################################
cursor = db.cursor()
curs... |
print(1)
# This is a comment
# The below code sets a variable to equal a value notice how this variable does not use single quotes
a = 1
b = 2
# We will now print both variables
print(a,b)
# Now lets add two variable together
print(a+b)
# What happens if you try to add a string and an integer
c = '3'
print(a+c)
# You... |
x=float(input("Введите число: "))
def f(x):
pass
if -2.4<=x<=5.7:
return pow(x,2)
else:
return 4
print(f(x))
|
import csv
with open('strInput.csv', 'r') as csv_file:
csv_reader=csv.DictReader(csv_file) #read from the strInput csv file
with open('strTransactions.csv', 'w', newline='') as new_file:
fieldnames = ['Date', 'Time', 'Transaction No.', 'Status', 'Store No.', 'Location Code', 'POS Terminal No.',
... |
numbers = [1, 3, 7, 4, 3, 0, 6, 3, 7 ,8 ,4 ,4 ,4 ,6 ,7 ,6 ,5 ,4, 5, 4, ]
harf = ["a", "g", "h", "k", "l", "m", "f" , "d" , "s" ]
print(max(numbers))
print(max(harf))
print(numbers.count(3))
most_frequent = max(numbers, key = numbers.count) # Burada max() fonksiyonu keyi olarak count belirledik, ve listenin içinde en ç... |
"""Task : Find out if the given word is "comfortable words" in relation to the ten-finger keyboard use.
A comfortable word is a word which you can type always alternating the hand you type with (assuming you type using a Q-keyboard and use of the ten-fingers standard).
The word will always be a string consisting of on... |
import datetime
today = datetime.datetime.now()
date = "{today.month}/{today.day}/{today.year}".format(today=today)
print(date)
print("Welcome To Internet Banking")
Bank = input("customer's Bank: ")
Account_Name = input("Account Name: ")
Account_Number = int(input("Your Account Number: "))
initial_balance = flo... |
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == 0: return True
stack = []
matching = {")" : "(", "]" : "[", "}" : "{"}
for p in s:
# if p is a close bracket,
if p == ')' or p == ']' or p == '}':
# return False if th... |
# Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
# Machine 1 (sender) has the function:
# string encode(vector<string> strs) {
# // ... your code
# return encoded_string;
# }
# Machine 2 (receiver) ... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 13:56:39 2018
@author: Roland
"""
# WORK STREAM =================================================================
# Generate population --> Grow Food --> Move Individuals --> Eat Food
# IMPORT PACKAGES =================================================... |
import speech_recognition as sr
import turtle
from word2number import w2n
r = sr.Recognizer()
skk = turtle.Turtle()
#Opening file and including basic libraries
file = open('output.py','w')
file.write("import turtle\n")
file.write("skk = turtle.Turtle()\n")
skk.pensize(5)
file.write("skk.pensize(5)\n")
skk.shape('turt... |
#!/usr/bin/env python
# coding=utf-8
import threading
import time
# 线程共享全局变量
g_cnt = 100
def start_routine_a():
global g_cnt
g_cnt = 1024
print 'routine a %d' % g_cnt
def start_routine_b():
global g_cnt
print 'routine b %d' % g_cnt
def start_routine_c(arg):
arg.append(4)
print arg
... |
#!/usr/bin/env python
# coding=utf-8
# value1 can be access by 'from private import *'
value1 = 100
# _value2 can not be access by 'from private import *'
_value2 = 200
class Person():
def __init__(self):
self.__age = 9
self.__name = 'anonymous'
def get_age(self):
print '%s age is %... |
#!/usr/bin/env python
# coding=utf-8
import urllib
import urllib2
# using baidu to search keyword
# url prefix
tmp_url = "http://www.baidu.com/s"
# enter the keyword for searching
keyword = raw_input("Enter the keyword: ")
# encode the keyword for url
query = {'wd': keyword}
kw = urllib.urlencode(query)
# baidu s... |
#!/usr/bin/env python
# coding=utf-8
# 三种形式多任务: 进程,线程,协程
# 本例即为协程
# 只要task1和task2切换足够快
# 就相当于有两个任务同时运行
def task1():
while True:
print('task one running---')
yield None
def task2():
while True:
print('task two running+++')
yield None
t1 = task1()
t2 = task2()
# main loop
... |
from .neuron import Neuron
import numpy as np
class IFNeuron(Neuron):
firing_threshold = 0
current_potential = 0
def __init__(self, firing_threshold):
self.firing_threshold = firing_threshold
def reset(self, inputShape):
"""
Resets the neuron to resting state
wi... |
import os,sys
#Name of the first level folder
val = input ("Enter the Parent folder:")
#confirmation if the name is correct
print (val)
#change accoring to your preference
path = ("C:\\Users\\darshanr\\Documents\\PythonTesting\\Testfolder\\"+str(val))
#complete path of where the folder will be created
print ("F... |
from typing import List
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
res = []
for num in nums:
if len(res) < k:
heapq.heappush(res, num)
elif num > res[0]:
heapq.heappop(res)
heapq.he... |
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n // 2):
for j in range((1 + n) // 2):
(
matrix[i][n - 1 - j],
matrix[n - 1 - j][n - 1 - i],
... |
from typing import List
"""
交换过的元素还需要做判断
"""
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i, left, right = 0, 0, len(nums) - 1
while i <= right:
if i < left:
i += 1
... |
# The data we need to retrieve
# 1. The total number of votes casted.
# 2. A complete list of candidates who received votes.
# 3. The percentage of votes each candidate won.
# 4. The total number of votes each candidate won.
# 5. The winner of the election based on popular vote.
import csv
import os
'''file_to_upload... |
"""
Contains the main loop of the game and core functions
"""
import sys
sys.path.append('../')
from command_line_parser.textParser import *
from game_state import *
import misc.miscDescriptions
def main_main():
print "Welcome to The Haunted Python Mansion"
print "Main Menu"
print "[1] Start New Game"
... |
# Unit8_불과 비교, 논리 연산자 알아보기
# 연습문제: 합격 여부 출력하기(practice_operator.py)
korean = 92
english = 47
mathematics = 86
science = 81
print(korean >= 50 and english >= 50 and mathematics >= 50 and science >= 50)
# 심사문제: 합격 여부 출력하기(judge_comparison_logical_operator.py)
# 표준 입력: 90 80 85 80
# 표준 출력: False
korean, english, mathe... |
# 함수가 호출될 때마다 1씩 감소
def countdown(n):
number = n + 1 # 입력받은 숫자부터 시작해 값이 1씩 감소해야 하니까 1을 더함.
def count():
nonlocal number # countdown 함수의 지역변수 number 값을 변경할 수 있도록 만들어줌.
number -= 1
return number
return count # 함수를 반환할 때는 이름만 반환
n = int(input())
c = countdown(n) # 여기서 c는 클로저 함수 / 함수 ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 2 22:09:01 2021
@author: JAQUELINA SANCHEZ
Implementacion del metodo de Newton Raphson
"""
def funcionFX(x):
return (x**4-6.4*(x**3)+6.45*(x**2)+20.538*x-31.752)
#derivada 1 de f(x)
def primerDerivada(x):
return (4*(x**3)-19.2*(x**2)+12.9*x+20.538)
#derivada 2... |
import string
import re
def universal_finder(filename, find_list):
# filename is name of receipt txt file from receipt image
# find_list is list of target words
marked_list = [] # List of lines that contains target words
found_words = [] # List of target words that were triggered
# Open f... |
def binary_exponentiation(x,n,m):
if(n == 0):
return 1
elif(n%2 == 0): # IF n is even
return binary_exponentiation(x**2 % m, n/2, m)
else: # if n is odd
return (x * binary_exponentiation(x**2 % m, (n-1)/2, m)) % m
def binary_exponentiation_it(x,n,m):
result = 1
while... |
from urllib.parse import urlparse
from urllib.request import Request, urlopen
def read_text_method(request):
"""Overwrites the default method for reading text from a URL or file to allow :class:`urllib.request.Request`
instances as input. This method also raises any :exc:`urllib.error.HTTPError` exceptions ra... |
import pandas as pd
csv = 'btc'
def pandasclean(csv):
df = pd.read_csv('cryptodata/'+ csv +'usd.csv',parse_dates=['Date'],usecols=[1,2,3,4,5])
df = df.set_index('Date').sort_index(ascending=True)
df.dropna(inplace=True)
return df
print(pandasclean(csv)) |
# -*- coding: utf-8 -*-
the_count =[1, 2, 3, 4, 5]
fruits = ['apples', 'orange', 'pears', 'apricots']
change =[1, 'pennies', 2, 'dimes', 'quarters']
# This first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# same as above
for fruit in fruits: #遍历列表
print "A fruit... |
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next = raw_input("> ")
if "0" in next or "1" in next :
how_much = int(next)
else:
dead ("Man, learn to tyoe a mumber.")
if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)
else:
weird_roo... |
from random import randint
YourAnswer = 0
Guess = randint(0,20)
j = 10
i = 0
print("Now let's guess the numnber between 0 to 19")
while i <10 and Guess != int(YourAnswer):
print("Come on you have %d times" %j)
YourAnswer = input("please input your answer:")
if int(YourAnswer)-Guess >0:
print("Bigger!... |
class Animal (object):
def __init__ (self,other):
self.other = other
print self.other
def show (self):
for line in self.other:
print line
def like (self):
self.mi = range(0,8)
return self.mi
# return self.other
myAnimal = Animal(["There are alot of anmimals",
"every one has there lifes",
... |
# -*- coding: utf-8 -*-
# create a mapping o f state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of status and sone cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add s... |
'''
Specification:
Class
get current temporary directory
load tar file and extract to temporary directory
overwrite tar file with temporary directory
'''
import sys
import os
import tempfile
import tarfile
import shutil
class TarfileHandler():
# Properties
tarFilePath = ''
tempDir = ''
#... |
# Time
import time
seconds = time.time()
print (seconds)
countdown = 5
while (countdown >= 0):
print (countdown)
countdown -= 1
time.sleep(1)
else:
print ("Vrmmmmm!")
# Multiplication Game
import random
print ("Welcome to the Multiplication Game\n")
# Generates two random numbers in variables.
rand1 = random.... |
import SuffixTree
import TreeNode
class TreeGhost(object): #non leaf nodes in boundary path
def __init__(self, node):
self.x = TreeNode.e #x value stays the same while e increases with each iteration
self.node = node
node.ghosts.add(self)
self.start = TreeNode.e #this will dete... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 24 17:40:32 2018
@author: longjiemin
"""
#
from random import randint
def insertion_sort(nums):
for i in range(1,len(nums)):
for j in range(i-1,-1,-1):
if nums[i] < nums[j]:
if j == 0:
sw... |
#2
#由两个堆栈组成的队列,add,poll,peek,
#问题:__repr__函数无反应
class de_list():
'''
dfsdf
'''
def __init__(self,nums):
self.stack1 = list(nums)
self.stack2 = list([])
for i in range(len(nums)-1,0-1,-1):
self.stack2.append(self.stack1[i])
def push(self,num):
sel... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 10 11:35:25 2018
@author: longjiemin
"""
#给定一个无序数组,求出需要排序的最短子数组长度
#难度:1星
#思路:进行两次遍历,一次从左至右,一次从右至左。每一次记录遍历书中的最小值,当arr[i]>min时,意味着min值必然要一到min值的位置,记录i的位置。
#但会两个索引位置,则其切片就只需要排列的部分。
def getminlen(arr):
min_index_left = -1
min_value_left = arr[0]
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 16 21:39:48 2018
@author: admin
"""
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
cur1 = pHead1
cur2 = pHead2
if cur1 is None: return cur2
if cur2 is None: return cur1
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 10:00:03 2017
@author: longjiemin
"""
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the ar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 20:18:35 2018
@author: admin
"""
#
#要求:时间N,空间1
#难度:一星
#思路:分析输出的特性,负累加和必然丢掉
#
#检测通过
def maxSum(nums):
max_sum = -float('inf')
cur = 0
if len(nums) == 0:
return None
for i in range(len(nums)):
cur += nums[i]
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 10:05:09 2018
@author: admin
"""
#题目:
#要求:
#难度:
#思路:审题,排序数组中,不降序,分析输入数据特点,寻找三元组则先固定住一个值,(第一个值),确定固定的含义
#要点:整理清楚解题思路,再写代码
#测试:已通过
def printUniquePair(arr,target):
left = 0
right = len(arr) -1
res = []
while left < right:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 15 11:39:49 2018
@author: longjiemin
"""
#斐波拉契序列的递归与动态规划
#补充题目1,,给定一个N,代表台阶数,一次可以跨2个或1个台阶,返回多少种走法
#假设成熟的母牛每年都会生一头小母牛,并且永远不会死,每一只小母牛3年之后成熟又可以生小母牛,假设第一年有一头
#小母牛,问年后牛的数量
#要求:时间复杂度(logN)
#难度:3星
#分析:使用传统的动态规划算法只能达到0(n),可以利用矩阵的特性,通过归并运算加快特性
class f():
def f1(s... |
from settings import messages
import os
import random
import time
import pygame
"""
KADI is a card game played by one person vs a computer opponent
the game is quite simple, the first person to finish his/her card-hand wins
"""
# global variables
# CENTER_CARD is the card that will always be at the center of the t... |
import turtle
def main():
window = turtle.Screen()
mike = turtle.Turtle()
make_square(mike)
turtle.mainloop()
def make_square(mike):
length = int(input("Tamaño del cuadrado: "))
for i in range(4):
make_line_and_turn(mike,length)
def make_line_and_turn(mike,length):
mik... |
mi_diccionario = {}
mi_diccionario['proweb'] = 9
mi_diccionario['android dev'] = 9
mi_diccionario['algoritmos'] = 8
#Iterar en llaves
for key in mi_diccionario.keys():
print(key)
for value in mi_diccionario.values():
print(value)
for llave,valor in mi_diccionario.items():
print("Llave: {} , Valor: {}"... |
def merge(list, p, q, r):
left = []
for i in range(p, q + 1):
left.append(list[i])
right = []
for j in range(q + 1, r + 1):
right.append(list[j])
i = 0
j = 0
for k in range(p, r + 1):
if i < len(left) and j < len(right) and left[i] <= right[j]:
list[k] =... |
import copy
class Node:
def __init__(self, value=None):
self.value = value
self.adj_list = []
adj_count = 0
self.up = None
self.down = None
self.right = None
self.left = None
self.posx = 0
self.posy = 0
def get_val... |
#nodes for storing both the number and value of squares on the sudoku board
class Node:
def __init__(self, x, y, value):
self.value = value
self.x = x
self.y = y
if self.value == "0":
self.domain = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
else:
... |
'''
Data types and functions translating between the (x,y) coordinate system and
latitude/longitude coordinates.
'''
import collections
import math
EARTH_RADIUS = 6378137
point = collections.namedtuple('point', ['x', 'y'])
coordinate = collections.namedtuple('coordinate', ['lat', 'lng'])
def midDistance(coord1,coo... |
from typing import Any, Callable
from fpe.asserts import AssertNonCallable, AssertWrongArgumentType
def flip(func: Callable[[Any, Any], Any]) -> Callable:
"""Decorator swaps arguments provided to decorated function.
Thus flip(f)(x, y) == f(y, x)
Borrowed from flip :: (a -> b -> c) -> b -> a -> c
""... |
__author__ = "Shashwat Tiwari"
__email__ = "shashwat1791@gmail.com"
class Solution:
def get_pascal_triangle(self, n):
line = [[0 for i in range(n+1)] for j in range(n+1)]
line[0][0] = 1
for i in range(n+1):
for j in range(i+1):
if j == 0 or j == i:
line[i][j] = 1
else:
line[i][j] = line[... |
__author__ = "Shashwat Tiwari"
__email__ = "shashwat1791@gmail.com"
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwis... |
__author__ = "Shashwat Tiwari"
__email__ = "shashwat1791@gmail.com"
from collections import defaultdict
class Graph:
def __init__(self, number_of_verticies):
self.graph = defaultdict(list)
self.time = -1
self.arrival = [-1]*number_of_verticies
self.departure = [-1]*number_of_verticies
def addEdge(self, ... |
__author__ = "shashwat tiwari"
__email__ = "shashwat1791@gmail.com"
class LIS:
"""
m[i] = max(m[j]) + 1 (for all j < i), if arr[i] > arr[j]
"""
def get_lis(self, arr):
lis = [1]*len(arr)
for i in range(1, len(arr)):
lis[i] = max([lis[j]+1 if (lis[j]+1 > lis[i] and arr[i] > arr[j]) else lis[i] f... |
__author__ = "shashwat tiwari"
__email__ = "shashwat1791@gmail.com"
class KnapSack:
def get_max_value(self, weights, values, capacity):
memo = [[None for i in range(capacity+1)] for j in range(len(weights))]
return self.helper(weights, values, capacity, len(weights)-1, memo)
def helper(self, weights, value... |
__author__ = "Shashwat Tiwari"
__email__ = "shashwat1791@gmail.com"
"""
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list... |
def Prime(num):
if num>=2:
for x in range(2,num):
if num%x==0:
print(num, "is not prime")
break
elif num%x!=0:
print(num,"is a prime")
break
else:
print("enter a number larger than 2")
-----------------------... |
import networkx as nx
def ruta():
graf = nx.DiGraph()
archivo = open("guategrafo.txt", "r")
contenido = archivo.readlines()
archivo.close()
for lineas in contenido:
string = lineas.split(" ")
graf.add_node(string[0])
graf.add_node(string[1])
graf.add_... |
import numpy as np # Useful because incoming images are numpy arrays
# import cv2 # Only used when run as main script
# A NOTE ON NOTATION:
# The way numpy numbers its arrays is
# right-handed, just like in math, but turned
# 90 degrees clockwise. That is, the pair
# (x,y) is:
# ----- Y
# | RIGHT IN NU... |
import argparse
from os import listdir
from os.path import isfile
import os
parser = argparse.ArgumentParser(description="Project root directory from where to count")
parser.add_argument('--dir', help="Path of the root")
args = parser.parse_args()
count = 0
def count_lines(current_path):
global count
l... |
# Program that reads in the string and outputs how long it is
# Author: Ante Dujic
inputString = input ("Enter a string: ")
lengthOfString = len (inputString)
print ("The length of {} is {}" .format (inputString, lengthOfString)) |
# Program that makes a list with 10 random numbers (20000 - 10000)
# Author: Ante Dujic
import numpy as np
minSalary = 20000
maxSalary = 80000
numberOfEntries = 10
np.random.seed (1)
salaries = np.random.randint (minSalary, maxSalary, numberOfEntries)
salariesPlus = salaries + 5000
salariesMult = salaries * 1.05
new... |
# Program that plots a histogram of the salaries
# Author: Ante Dujic
import numpy as np
import matplotlib.pyplot as plt
minSalary = 20000
maxSalary = 80000
numberOfEntries = 100
np.random.seed (1)
salaries = np.random.randint (minSalary, maxSalary, numberOfEntries)
plt.hist (salaries)
plt.show () |
# Program that checks variable type
# Author: Ante Dujic
# List of variables
i = 3
fl = 3.5
isa = True
memo = 'how now Brown Cow'
lots = []
# Checking variable type
print ('Variable {} is a type: {} and value: {}' .format ('i', type(i), i))
print ('Variable {} is a type: {} and value: {}' .format ('fl', type(fl), f... |
def double_char(str):
new = ""
for c in str:
new+=c*2
return new |
import math
i=0
sum=0
while i<100:
sum+=int(input())
i+=1
print(sum) |
def Excel(s):
L = len(s)
i = L
j = 0
Num = 0
print(i)
while i>0:
Num = Num + (26**j)*(ord(s[i-1])-64)
i = i - 1
j = j + 1
return Num
print(Excel("A"))
|
import unittest
import leap_year
class testCaseAdd(unittest.TestCase):
def test_volume(self):
self.assertEqual(leap_year.leapyear(2004),"is a leap year")
self.assertEqual(leap_year.leapyear(2012),"is a leap year")
self.assertEqual(leap_year.leapyear(2007),"is not a leap year")
self.... |
N = int(input())
for i in range(0,N):
turn = int(input())
if turn <= 1 or (turn%7 == 0) or (turn%7 == 1):
print("Second")
else:
print("First")
|
#!/bin/python3
import sys
def fib(n):
score = 0
if n == 0:
return 0
elif n == 1:
return 1
return fib(n-1) + fib(n-2)
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
tmp = []
for i in range(3,n,3):
f = fib(i)
if i <= n:
t... |
from operator import attrgetter # method for working with specific attributes of an object
class ShortestPath: # main class
def __init__(self, row, col, grid):
self.__row = row
self.__col = col
self.__matrix = [[0 for i in range(self.__col)] # matrix for grid input
... |
#visualização de dados
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,3,7,2,1]
titulo = "Gráfico de barras"
eixox = "Eixo X"
eixoy = "Eixo Y"
#legendas
plt.title(titulo)
plt.xlabel(eixox)
plt.ylabel(eixoy)
plt.scatter(x,y)
plt.plot(x,y)
plt.bar(x, y)
plt.show() |
# Time Complexities:
# Avg Worst
# Access O(n) O(n)
# Search O(n) O(n)
# Insert O(1) O(1)
# Delete O(1) O(1)
# Note: insertion is O(1) bc the operation is constant time (changing pointers). Unlike array where you have to shift elements. Finding the... |
from collections import defaultdict
class Graph:
def __init__(self):
# use defaultdict instead of dict bc when adding edges, if the edge not in graph,
# it will not raise error and add it to dict
# put list in constructor because the values of each key will be a list
# so this knows... |
from random import choice
with open('dictionary.txt', 'r') as f:
words = f.readlines()
list = {}
for i in words:
i = i.strip()
if len(i) in list:
list[len(i)].append(i)
else:
list[len(i)] = [i]
t = True
while t:
try:
i = raw_input('Enter a number between 1 and 28 that\'s not 26 or 27: ')
t = True
i... |
import re
from time import gmtime, strptime
def main():
age = input("Please Enter Birthdate (01/27/1998):")
while not re.match('\d\d/\d\d/\d\d\d\d', age):
age = input("Please Enter Birthdate (01/27/1998):")
date = gmtime()
age = strptime(age, "%m/%d/%Y")
print("Age In Seconds:", ((date.tm_year - age.tm_year... |
# -*- coding: utf-8 -*-
# #####################################
# @Author: Feyiz135
# @Time: 2017-05-07
# #####################################
"""
生成各种类型的随机数据
"""
import random
from datetime import date, datetime, timedelta
import string
def _gen_data(iterable, length, exc=None):
"""
:param iterable: 数据源
... |
def power(x,y):
if y==0:
return 1
elif x==0:
return 0
elif y%2==0:
return power(x,y/2)*power(x,y/2)
else:
y=(y-1)/2
return x*power(x,y)*power(x,y)
result=power(2,3)
print result
|
listw = ["hello", "hi", "hey", "super", "snehashish", "yaju", "yes"]
emlis = []
word = input()
for i in listw:
if word in i:
emlis.append(i)
print(emlis) |
import random
def print_board(a):
print(a[1], " | ", a[2], " | ", a[3])
print("-------------------")
print(a[4], " | ", a[5], " | ", a[6])
print("-------------------")
print(a[7], " | ", a[8], " | ", a[9])
def is_board_full(board):
return board.count(" ") == 1
def is_free(board,... |
class StringValidators(object):
def __init__(self):
self.inp = raw_input()
def check_is_any_num(self, inp):
for i in inp:
if i.isalnum():
return True
return False
def check_is_any_pha(self, inp):
for i in inp:
if i.isalpha():
... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
#N = int(raw_input())
factorial = lambda x : 1 if x<=1 else x*factorial(x-1)
N = 3
def factorial(x):
if x <=1:
return 1
else:
return x*factorial(x-1)
print(factorial(N))
|
#!/usr/bin/env python3
def sumarray(arr, total, pos):
if pos < len(arr):
total = sumarray(arr, total, pos+1) + arr[pos]
print(total)
return total
def sum2(arr):
total = 0
for i in range(0, len(arr)):
total = total + arr[i]
print(total)
return total
def sum3(arr):
total = 0 ... |
#!/usr/bin/env python3
import sys
import os
import json
import pathlib
from collections import deque
# Node of DLL
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Code for inserting data to tree
def insert(self, data):
if self.data:
if data < self.d... |
from disjoint_sets import DisjointSets
class Solution:
def findCircleNum(self, M) -> int:
n = len(M)
ds = DisjointSets()
for i in range(n):
ds.make_set(i)
for i in range(n):
for j in range(i + 1):
if M[i][j] == 1:
ds.union(... |
# coding=utf-8
"""helper file for path function"""
import os
def list_images(base_path, contains=None):
"""
return the set of files that are valid
Args:
base_path:
contains:
Returns:
"""
return list_files(base_path, valid_ext=(".jpg", ".jpeg", ".png", ".bmp", ".ppm"), cont... |
import random
# deck = []
def print_header():
print("BLACKJACK!")
print("Blackjack payout is 3:2")
print()
def user_input():
while True:
player_money = int(input("Starting player money: "))
if player_money < 0 or player_money > 10000:
print("Invalid amount. Must be from... |
# from multiprocessing import Pool
# import time
# COUNT = 50000000
# def countdown(n):
# while n>0:
# n -= 1
# if __name__ == '__main__':
# pool = Pool(processes=2)
# start = time.time()
# r1 = pool.apply_async(countdown, [COUNT//2])
# r2 = pool.apply_async(countdown, [COUNT//... |
#week 3 Homework kurtis Henry
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year,studentID):
super().__init__(fname, lname)
... |
# coding:utf-8
# author:tntC4stl3
'''
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find th... |
#!/usr/bin/env python3.8
"""
ROS A-Star's algorithm path planning exercise solution
Author: Roberto Zegers R.
Copyright: Copyright (c) 2020, Roberto Zegers R.
License: BSD-3-Clause
Date: Nov 30, 2020
Usage: roslaunch unit3_pp unit3_astar_solution.launch
"""
import rospy
def find_neighbors(index, width, height, costm... |
'''
Returns document as dict: documents[document] = list of words
'''
def getDocuments(texts, delimiter):
documents = {}
for text in texts:
index = 0
words = []
doc = open(text, 'r')
for word in doc.read().split(delimiter):
index += 1
word = word
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.