text stringlengths 37 1.41M |
|---|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
length = 1
linked_list = head
while linked_list.next is not None:
length += 1
... |
def printFibno(n):
if(n==0):
fib = []
elif(n==1):
fib = [1]
elif(n==2):
fib = [1,1]
elif(n>2):
fib = [1,1]
i = 1
while(i< n-1):
fib.append(fib[i]+fib[i-1])
i = i +1
return fib
print(printFibno(int(input("Enter Number"))))
#another code Fibonacci Numbers
def printFibona... |
def fuel(mass: int):
return mass // 3 - 2
def theRocketEq(mass: int):
neededFuel = fuel(mass)
totalFuel = neededFuel
while neededFuel > 0:
neededFuel = fuel(neededFuel)
if neededFuel < 0:
break
totalFuel += neededFuel
return totalFuel
print(theRocketEq(100756)... |
def get_freq(str):
freq = {}
for char in str:
freq[char] = freq.get(char, 0)+1
return freq
def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
... |
import re
class Word:
def __init__(self, file_path):
self.file_path = file_path
def find_regex_match(self, pattern, path=None):
"""""
input data from the file
"""
if path is None:
path = self.file_path
with open( path, 'r' ) as file:
... |
credit = int(input("Enter the value of credits: "))
if credit >= 7500:
print("Tera Leader")
elif credit >= 6000 and credit < 7500:
print("Gega Leader")
elif credit >= 4500 and credit < 6000:
print("Mega Leader")
elif credit < 4500:
print("Rising star")
|
for x in range(int(raw_input())):
word = raw_input()
if len(word) > 10:
print(word[0] + str(len(word)-2) + word[len(word)-1])
else:
print(word) |
class Group():
def __init__(self, persons):
self.persons = persons
def lil_pop(self):
self.persons -= 1
return 1
def pop(self):
if self.persons > 1:
self.persons -= 2
return 2
elif self.persons == 0:
return 0
else:
... |
def validateSI(input):
outInvalid = {
"tinNumber": input,
"validStructure": False,
"validSyntax": False,
}
if not input.isnumeric():
outInvalid["message"] = "TIN must be numeric"
return outInvalid
elif not (int(input) < 1000000 or int(input) > 9999999):
... |
import re
def validateAT(input):
tin = input
input = re.sub('[^A-Za-z0-9 ]+', '', tin)
outInvalid = {
"tinNumber": tin,
"validStructure": False,
"validSyntax": False,
}
if len(input) != 9:
outInvalid["message"] = "Invalid Length"
return outInvalid
elif ... |
# Guess the number game
import random
guessesTaken = 0
print('Hello, what is your name?') # ask user their name
userName = input()
number = random.randint(1, 10)
print(userName + ', I am thinking of a number between 1 and 10.')
# create loop for user to guess up to six times on number
while guessesTaken < 6:
... |
import unittest
from typing import List
def min_rectangle(sizes: List[List[int]]) -> int:
max_w, max_h = 0, 0
for w, h in sizes:
if w < h:
w, h = h, w
max_w, max_h = max(max_w, w), max(max_h, h)
return max_w * max_h
class Test(unittest.TestCase):
def test(self):
s... |
import unittest
class Solution:
def reverseStr(self, s: str, k: int) -> str:
if len(s) < k:
return s[::-1]
return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k)
class Test(unittest.TestCase):
def test_reverseStr(self):
solution = Solution()
self.assertEq... |
import unittest
def find_prime(n):
a = set([i for i in range(3, n+1, 2)])
for i in range(3, n+1, 2):
if i in a:
a -= set([i for i in range(i*2, n+1, i)])
return len(a) + 1
class Test(unittest.TestCase):
def test(self):
self.assertEqual(find_prime(10), 4)
self.asse... |
"""
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and ... |
import unittest
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start, end = 0, len(nums) - 1
while start <= end:
mid = (start + end) // 2
if nums[mid] < target:
start = mid + 1
else:
... |
import unittest
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = sum(nums[0:3])
d = abs(target - res)
for i in range(len(nums) - 2):
j, k = i + 1, len(nums) - 1
while j < k:
... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
list_size = len(arr)
positive_counter = 0
zero_counter = 0
negative_counter = 0
for number in arr:
if(number > 0):
positive_counter = positive_co... |
import unittest
from typing import List
def target_number(numbers: List[int], target: int) -> int:
answer = 0
queue = [[numbers[0], 0], [-1 * numbers[0], 0]]
n = len(numbers)
while queue:
temp, idx = queue.pop()
idx += 1
if idx < n:
queue.append([temp + numbers[idx]... |
import unittest
from collections import defaultdict
class TimeMap:
def __init__(self):
self.dict = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.dict[key].append([timestamp, value])
def get(self, key: str, timestamp: int) -> str:
arr = self.d... |
import unittest
def valid_parenthesis(s: str) -> bool:
stack = []
for c in s:
if c == "(":
stack.append(c)
else:
try:
stack.pop()
except IndexError:
return False
if stack:
return False
return True
class Test(... |
import collections
import unittest
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagrams = collections.defaultdict(list)
for word in strs:
anagrams[''.join(sorted(word))].append(word)
return list(anagrams.values())
class... |
from .ast import BExpr, ParanExpr, NumExpr
from .lexer import *
class ParseException(Exception):
""" An Exception while parsing """
pass
class ParseError(ParseException):
""" An error that occurs during parsing """
def __init__(self, message):
self.message = message
def message(self):
... |
number = int(input("Enter a number: "))
if number == 5:
print("it's 5!")
elif number < 5:
print("so low!")
elif number > 5 and number < 20:
print("pretty decent.")
else:
print("whoa slow down! so high, take care!")
'''
flag = input("Enter 'True' or 'False': ")
flag = bool(flag)
# if the condition e... |
# As an exercise, write a function that takes a string as an argument and displays the letters backward, one per line.
word = input("Please enter a word: ")
x = 0
while x < len(word):
i = 1
print(word[len(word) - i])
i = i + 1
x = x + 1
'''
users = {'mary': 22, 'caroline': 26, 'harry': 20}
#... |
'''
If a runner runs 10 miles in 30 minutes and 30 seconds,
What is his/her average speed in kilometers per hour? (Tip: 1 mile = 1.6 km)
'''
distance_ran_miles = 10
time_taken_seconds = (30 * 60) + 30
time_taken_hours = (time_taken_seconds/60)/60
speed_in_miles = distance_ran_miles/time_taken_hours
print(speed_in_mil... |
'''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it ou... |
users = {'mary': 22, 'caroline': 26, 'harry': 22}
print(users['mary']) # using the key to return the value of key 'mary'
users['harry'] = 20 # changing the original value of 'harry'
print(users['harry'])
for user, age in users.items():
print(user, age)
for user, age in users.items():
age = age + 10
pri... |
import random
randomlist = []
randomlist2 = []
for i in range(0,20):
n = random.randint(1,20)
m= random.randint(1,20)
randomlist.append(n)
randomlist2.append(m)
print(randomlist)
print(randomlist2)
p= random.randint(1,40)
# list_1 = [1,2,3,4,5,6,7,8]
# list_2 = [9,2,5,59,56,6,8,1]
list_1 =randomlis... |
# importing required libraries gui based
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
# create a Window class
class Window(QMainWindow):
# constructor
def __init__(self):
super().__init__()
# setting title... |
# Number
# string
# list
# dict
# tuple
# set
a=2345
b=374.3
print(type (a),a)
print(type (b),b)
name="this is a car can't for flying"
print(type(name),name)
c= 'This is a single qoutes "string" '
d=" double we can use \n for new line "
e="""This
is also
multiline for paragraph writing
"""
f="she is asking me i \... |
"""Tests for samplesheet.py"""
from fluffy import samplesheet
def test_get_separator_space():
"""Test to get a separator"""
# GIVEN a line with spaces
line = "one two three"
# WHEN getting the separator
sep = samplesheet.get_separator(line)
# THEN assert space is returned
assert sep == " ... |
def my_sum(*val):
result = 0
for x in val:
result = result + x
return result
print(my_sum(1, 4, 5))
|
"""
Closest Pair of Points XY Plane
- closest_pair_2d: Divide and Conquer in xy plane
- bf_closest_pair_2d: Brute force in xy plane
"""
import math
import random
from .utils import min_of_pairs
class Point(object):
"""
Point class of 2d: x and y
"""
def __init__(self, x, y, *args):
s... |
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("tic tac toe game")
root.iconbitmap("D:/tkinter/tic tac toe/game.ico")
root.geometry("1350x750")
root.config(background="skyblue")
#frame for showing title of game
frame1 = Frame(root,bg="cadet blue",width=1350,height=100,pady=2,rel... |
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("binding events")
root.iconbitmap("icons/superman.ico")
root.geometry("400x400")
def clicked(event):
Label(root,text="button clicked"+" "+str(event.x)+" "+str(event.y)+" "+event.char+" ",font=("arial",20)).pack()
button... |
from tkinter import *
root = Tk()
e = Entry(root,width=50)
e.insert(0,"enter here")
e.pack()
def clicked():
hello="hello"+" "+e.get()
mylabel=Label(root,text=hello,fg="blue")
mylabel.pack()
button=Button(root,text="click here",command=clicked)
button.pack()
root.mainloop() |
from random import randint
import random
answer_list = []
global list1
global rando
list1 = ['ntr_np','ntr_tem','ntr_jlk','prabhas','mahesh_sri',
'mahesh_ban','mahesh_maha']
names = {"ntr_np":'nanakuprematho',"ntr_tem":'temper',"ntr_jlk":'jailavakusa',
"prabhas":'saaho',"mahesh_s... |
side=float(input())
area=side**2
perimeter=4*side
print("Area of square",area)
print("Perimeter of square",perimeter)
|
def max3(arr):
arr = sorted(arr, reverse=True)
return arr[:3]
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
max_number= max3(numbers_list)
for num in max_number:
print(num) |
"""Module to fetch weather information"""
import requests as rq
def lookup_weather(city, day, month, year, api_key):
"""Get weather information for a place at a given date, using the
World Weather Online API. This API is limited to 500 calls / user / day.
Parameters
----------
city : string
d... |
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
im = np.array(Image.open('empire.jpg'))
plt.imshow(im)
x = [100,100,400,400]
y = [200,500,200,500]
plt.plot(x, y, 'r*')
plt.plot(x[:2], y[:2])
plt.axis('off')
plt.title('Plotting: "empire.jpg"')
plt.savefig('plot2img_axis-off.jpg')
plt.show()
|
# Task 1
# The greatest number
# Write a Python program to get the largest number from a list of random numbers with the length of 10
# Constraints: use only while loop and random module to generate numbers
import random as rd
our_num = list()
n = 0
while n < 20:
numbers = rd.randint(0, 1000)
n = n+1
our_n... |
__all__ = ['Heart']
class Heart(object):
def __init__(self, size):
self.size = size
def get_distance(self, point):
x, y, z = point
x /= self.size * 0.43
y /= self.size * 0.43
z /= self.size * 0.43
res = 320 * ((-x**2 * z**3 - 9*y**2 * z**3/80) +
... |
print('{{')
for y in range(14):
print('\t{ ', end='')
for x in range(18):
print(hex(0x4100 + x + y * 18) + ', ', end='')
print(' },')
print('},{')
for y in range(14):
print('\t{ ', end='')
for x in range(18):
print(hex(0x6200 + x + y * 18) + ', ', end='')
print(' },')
print('}};')
|
#根据GFF3文件统计外显子大小和数量以及内含子大小
#1.每个基因的外显子起始与结束的位置,保存为1.txt,注意需要打开1.txt编辑删除第一行的空行
output_file = open("1.txt", "w")
with open('test.gff3', 'r') as f:
for line in f:
line = line.rstrip("\n") # 删除行尾的换行符
array = line.split("\t")
sub_array = array[8].split(";")
name = sub_array[1].... |
"""
给定一棵二叉树,返回其节点值的后序遍历。
例如:
给定二叉树 [1,null,2,3],
1
\
2
/
3
返回 [3,2,1]。
注意: 递归方法很简单,你可以使用迭代方法来解决吗?
"""
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root... |
'''
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
'''
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
if len(self.stack2) == 0:
self.stack2.append(node)
elif node < self.stac... |
'''
请实现一个函数按照之字形打印二叉树,
即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def printTree(self, root):
if root == None:
return
result, nodes = [... |
"""
time: O(log(m+n)
"""
class Solution:
def median_of_two_sorted_array(self, num1, num2):
size1 = len(num1)
size2 = len(num2)
if (size1 + size2) % 2 == 0:
return (self.find_k_th(num1, size1, num2, size2, (size1 + size2) // 2 + 1) + self.find_k_th(num1, size1,
... |
'''
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
if root is None or root.va... |
'''
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
'''
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def FindPath(self, root,target):
if root == None:
return
if root.left ... |
'''
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,
重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution1:
def deleteDuplication(self, pHead):
if not pHead:
return pHead
res = []
... |
'''
输入一个链表,反转链表后,输出链表的所有元素。
'''
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if pHead == None or pHead.next == None:
return pHead
last = None
while pHead:
... |
def power1(base, exponent):
if exponent == 0:
return 1
if exponent == 1:
return base
result = power1(base, exponent >>1)
result *= result
if exponent & 1 ==1:
result *= base
return result
print(power1(2,16))
|
'''
把只包含因子2、3和5的数称作丑数(Ugly Number)。
例如6、8都是丑数,但14不是,因为它包含因子7。
习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
'''
"""
解题思路:
丑数是另一个丑数乘以2 3 5 的结果
因此我们可以每个丑数分别乘以2 3 5
对于乘以2而言,一定存在某个丑数,排在它前面的每个丑数都小于当前已有丑数,在它之后每个丑数乘以2得到的结果都会太大
我们只需要记录这个值
对于3 5 类似
"""
class Solution:
def GetUglyNumber_Solution(self, index):
if index <= 0:
... |
'''
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。
HF作为牛客的资深元老,自然也准备了一些小游戏。
其中,有个游戏是这样的:
首先,让小朋友们围成一个大圈。
然后,他随机指定一个数m,让编号为0的小朋友开始报数。
每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,
从他的下一个小朋友开始,继续0...m-1报数....
这样下去....
直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。
请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从... |
'''
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),
返回结果为复制后复杂链表的head。
(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
'''
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
... |
'''
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。
要求不能创建任何新的结点,只能调整树中结点指针的指向。
'''
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def convert(self,root):
if root == None:
return root
if not ro... |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
@staticmethod
def level_order(root):
if root is None:
return []
cur = [root]
next = []
result = []
while cur:
f... |
'''
一只青蛙一次可以跳上1级台阶,也可以跳上2级。
求该青蛙跳上一个n级的台阶总共有多少种跳法。
'''
# -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
# write code here
if number < 2:
return number
a, b, c = 1, 0, 0
for i in range(1, number + 1):
c = a + b
b = a
... |
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def reverseList(self, node):
if node ==None or node.next == None:
return node
last = None
while node:
temp = node.next
node.next = last
... |
'''
一个栈依次压入1、2、3、4、5,那么从栈顶到栈底分别为5、4、3、2、1。
将这个栈转置后,从栈顶到栈底为1、2、3、4、5,也就是实现栈中元素的逆序,
但是只能用递归函数实现,不能使用其他数据结构。
'''
'''
解决思路
首先实现一个递归函数 a,其功能是返回并移除栈底元素。
之后再实现一个递归函数 b,其功能是不断用递归的临时变量去接住 a 函数返回的栈底元素,
这样,最后一个栈底元素就是原来栈的栈顶元素,
之后一层一层的将递归中的临时变量压入栈中,这样就实现了逆序。
'''
class Solution:
def getAndRemoveLastElement(self,... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteNode(self, pHead, pNode):
if not pHead or not pNode:
return
if pNode == pHead:
pHead = pHead.next
elif pNode.next != None:
pNode.val = pNo... |
"""
给一个只包含 '(' 和 ')' 的字符串,找出最长的有效(正确关闭)括号子串的长度。
对于 "(()",最长有效括号子串为 "()" ,它的长度是 2。
另一个例子 ")()())",最长有效括号子串为 "()()",它的长度是 4。
"""
"""
解题思路:
定义个start变量来记录合法括号串的起始位置,
我们遍历字符串,如果遇到左括号,则将当前下标压入栈,
如果遇到右括号,
如果当前栈为空,则将下一个坐标位置记录到start,
如果栈不为空,则将栈顶元素取出,
此时若栈为空,则更新结果和i - start + 1中的较大值,否
则更新结果和i - 栈顶元素中的较... |
class Solution:
"""
@param numbers: Give an array numbers of n integer
@return: Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
if len(numbers) < 3:
return []
numbers.sort()
res = ... |
'''
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,
那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};
针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个:
{[2,3,4],2,6,2,5,1},
{2,[3,4,2],6,2,5,1},
{2,3,[4,2,6],2,5,1},
{2,3,4,[2,6,2],5,1},
{2,3,4,2,[6,2,5],1},
{2,3,4,2,6,[2,5,1]}。
'''
class Solution:
def maxInWindows(self, nu... |
'''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
'''
def getMoreHalfNumber(num):
hash = dict()
length = len(num)
for n in num:
hash[n] = hash[n] + 1 if hash.get(n) else 1
if hash[n] > length/2:
return n
a = [1,2,3,2... |
def DisplayMenu():
print("DisplayMenu")
def ReadFile():
print("ReadFile")
NoOfAttempt = 0
while NoOfAttempt<3:
DisplayMenu()
choice = int(input("Make your choice:"))
if choice == 1:
ReadFile()
elif choice == 2:
print("Add customer code")
elif choice == 3:
pr... |
fileHandler = open('records.txt','r') # to open pre-existing text file
id= input("enter the id you want to search") # string datatype
rec=fileHandler.readline() # reads the firsdt record of file
found=False # boolean variable
while(len(rec)>0):
list=rec.split('#') # split the record and shift in ... |
# -*- coding: utf-8 -*-
# Two friends Anna and Brian, are deciding how to split the bill at a dinner.
# Each will only pay for the items they consume. Brian gets the check and
# calculates Anna's portion. You must determine if his calculation is correct.
#
# For example, assume the bill has the following prices: bill ... |
# -*- coding: utf-8 -*-
# [collections.Counter()](https://docs.python.org/2/library/collections.html#collections.Counter)
#
# A counter is a container that stores elements as dictionary keys, and their
# counts are stored as dictionary values.
#
# Sample Code
#
# >>> from collections import Counter
# >>>
# >>> myList ... |
# -*- coding: utf-8 -*-
# You are given the first name and last name of a person on two different lines.
# Your task is to read them and print the following:
#
# Hello firstname lastname! You just delved into python.
#
# Input Format
#
# The first line contains the first name, and the second line contains the last
#... |
# -*- coding: utf-8 -*-
# Read an integer 'N'.
#
# Without using any string methods, try to print the following:
#
# 123...N
#
# Note that "..." represents the values in between.
#
# Input Format
#
# The first line contains an integer 'N'.
#
# Output Format
#
# Output the answer as explained in the task.
#
# Sample In... |
def replicate_iter(times, data):
if ((not isinstance(times, int)) or (not isinstance(data, (int, float, long, complex, str)))):
raise ValueError("Invalid argument")
if(times <= 0):
return []
else:
result = []
for i in range(1, times+1):
result.append(data)
return result
def replicate_recur(times, data)... |
import sys
import numpy as np
import matplotlib.pyplot as plt
def get_params(filename):
print("Getting parameters. Opening file...")
file = open(filename)
file_str = file.read()
file.close()
'''
Params presumed to be
pow_i pow_f np
a dtype
Where the pows are the powers of 10 at which to start and ... |
from Graph import Node
from heapq import heappush,heappop,heapify
#Note: This algoritm uses either Dijkstra or A*
#it all depends if the start node has a defined goal
#which can be used to calculate the heuristic cost
def graphSearch(start,goals):
d=[]
heapify(d)
#start.cost=0
f=[start]
heapify(f)... |
# imports
from requests import get
from bs4 import BeautifulSoup
import os
import pandas as pd
def get_blog_posts():
filename = './codeup_blog_posts.csv'
# check for presence of the file or make a new request
if os.path.exists(filename):
return pd.read_csv(filename)
else:
return make_n... |
'''
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order.
Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example... |
class Pattern_Two:
'''Pattern two
1 1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1
1 1 1 1
1 1 1
1 1
1
'''
def __init__(self, strings='1', steps=10):
self.steps = steps
if isinstance(strings, str):
self.strings = strings
els... |
class Pattern_Eight:
'''Pattern eight
P
P r
P r o
P r o g
P r o g r
P r o g r a
P r o g r a m
P r o g r a m m
P r o g r a m m i
P r o g r a m m i n
P r o g r a m m i n g
P r o g r a m m i n
P r o g r a m m i
... |
import collections
class Count_Letter:
def __init__(self, strings):
self.strings = strings
def method_one(self):
'''Using for loop'''
dic = {}
for string in self.strings:
if string in dic:
dic[string] += 1 # If a character exists... |
import cv2
class Open_CV:
'''Capture image from your camera'''
def __init__(self, image_name):
self.image_name = image_name
self.download_link = 'pip install opencv-python'
def capture(self):
'''Capturing Image'''
try:
cam = cv2.VideoCapture(0) ... |
import requests
def is_internet():
'''Check if you are connected to internet'''
try:
requests.get("http://www.google.com")
return True
except requests.ConnectionError:
return False
if is_internet():
print('Internet Access')
else:
print('No Internet')
... |
from tkinter import *
from tkinter.font import Font
class ShortCut:
def __init__(self, master):
self.master = master
self.font = Font(size=8)
def show_shortcut(self, button, text, rely=None):
'''Show text aside of the button when the cursor enters to the button'''
self.label ... |
import random
class setup:
'''This class is responsible for:
1. Showing board each time when user as well as bot enters their turn
2. Asking user if he / she wants to go first'''
def __init__(self):
self.board = [str(i) for i in range(1, 10)]
def display_board(... |
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
import math
def primes(n):
sums, sieve = [], [True] * n
for p in range(2, n):
if sieve[p]:
sums.append(p)
for i in range(p * p, ... |
from datetime import *
import sqlite3
# This is our connection to the database
conn = sqlite3.connect('activities.db')
# This is the cursor. Using it we can add, delete or update information in the database
c = conn.cursor()
def create_table():
"""
This function creates a table with some columns that will be... |
import pyperclip
plaintext = 'MKOCKBMSZROB.'
key = 10
mode = 'decrypt'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
plaintext = plaintext.upper()
for symbol in plaintext:
if symbol in letters:
num = letters.find(symbol)
if mode == 'encrypt':
num = num + key
elif mode == 'decrypt':
... |
"""Main cryptographic functions of the platform.
These are the fucntion that encrypt and decrypt all the content from the
backend side of the platform.
"""
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
"""Declare m... |
from HW1.data_gen import DataSet
import numpy as np
import HW1.percept_learning as pla
def generate_target(data_set):
"""A method used to set the target vector for the linear regression.
Target vector i is set to -1 if point i dot f is negative (or zero) otherwise set to +1.
Params: DataSet
Return: ... |
class base():
def func(self,X1):
X = X1
print(X)
def __str__(self):
txt = "This is your object"
return txt
class child(base):
#def func(self,Z):
# print("in child class")
def func1(self):
print("inside child")
#super().func(20)
self.func(50) # via inheritance
#Bx = base()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
def display(Xrow, ImageName):
'''Display a digit by first reshaping it from the row-vector into the image. '''
plt.imshow(np.reshape(Xrow, (28, 28)))
plt.gray()
plt.savefig(str(ImageName) + "... |
from database import fetch_entries, add_entry, create_table
menu = """Please select one of the following options:
1. Add new entry for today
2. View entries
3. Exit
Your Input: """
Welcome = """Welcome to the programming diary"""
def prompt_new_entry():
date = input("Enter a date:")
content = input("Enter ... |
class Node:
def __init__(self, data):
self.next = None
self.data = data
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def getMiddleNode(self):
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
... |
import random
import simplegui
n=0
g=0
def f_r1():
global g,n
n=random.randint(0,100)
g=7
print "new game initialized: range from 0 to 100"
print "number of guesses are :"+str(g)
def check(t):
global g,n
g=g-1
if ((g+1)>0):
print "guess : "+t
print "numbe... |
# x = 20
# y = 30
# +,-,*,/,%, **,//
# print(x + y)
# print(2**4)
# print(19//5)
# x = 10
# =,+=,-=,*=
# x = 10
#
# x += 20
#
# print(x)
# and,or,not
#
# userName = 'admin'
# password = 'admin002'
#
# if userName=='admin' and password=='admin002':
# print('Welcome')
# else:
# print('')
# ==,>,<,>=,<=
... |
# Polynomial regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
dataset = pd.read_csv('data.csv')
X = dataset.iloc[:, 1:2].values # ma... |
import math
def hypotenuse(a , b ):
#c = (a**2 + b**2)**(1/2)
try:
return math.sqrt(a**2 + b**2)
except TypeError:
return None
d = hypotenuse
print(d(2,3)) #print 2 numbers
print(d("2","3"))
print(d(2,"3"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.