text stringlengths 37 1.41M |
|---|
# USAGE
# python drawing.py
# Import the necessary packages
import numpy as np
import cv2
def draw_line():
# Draw a green line from the top-left corner of our canvas
# to the bottom-right
green = (0, 255, 0)
cv2.line(canvas, (0, 0), (300, 300), green)
cv2.imshow("Canvas", canvas)
cv2.waitKey(0)
def draw_rectan... |
from Aluno import Aluno
nome = input("Nome do aluno: ")
curso = input("Nome do Curso: ")
horasSemDormir = int(input("Quantidades de horas sem dormir: "))
horasDeEstudos = int(input("Quantidades de horas de estudo: "))
dormir = int(input("Quantidades de horas sono: "))
aluno = Aluno(nome, curso, horasSemDormir)
aluno.... |
miles = float(input("Please enter the miles you drove: "))
gallons = float(input("Please enter the amount of gallons you put in the tank: "))
mpg = int(miles/gallons)
print("You got", mpg, "mpg on that tank of gas.")
|
#!/usr/bin/env python
#coding:UTF-8
def isMatch(s, p):
if len(p) == 0:
return len(s) == 0
if len(p) == 1:
return len(s) == 1 and p[0] == s[0]
if p[1] == '*':
while len(s) != 0 and (p[0] == '.' or p[0] == s[0]):
if isMatch(s, p[2:]):
return True
... |
# A List is a collection which is ordered and changeable. Allows duplicate members.
arr = ['apple', 'pear', 'strawberry', 'mango']
arr.sort()
print(len(arr))
|
#!/usr/bin/env python
import sys
import csv
data=csv.reader(sys.stdin, delimiter=',')
for info in data:
if info[12]:
value=float(info[12])
else:
value=float(0.00)
print(info[2] + '\t'+str(value)+',' + '1.00')
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Question1:
person_dict={"first_name":"Muhammad Asad","last_name":"Ahmed","age":"22","city":"Sukkur"}
for key, value in person_dict.items():
print(key+" : "+value)
print("\n Add qualification \n")
person_dict["qualification"]="Intermediate"
for key, value in person... |
naam = str(input("Naam: "))
percent = int(input("Behaalde percentage: "))
while naam != "xx" or "XX":
if (percent < 0 or percent > 100):
print("ongelevdig percent")
elif(percent >= 0 or percent <= 100):
if(percent < 60):
print("onvoldoende")
elif(percent < 70):
p... |
def main():
aantal_karakters = int(input("Hoeveel karakters wil je ingegeven? "))
teller = 0
som = 0
while teller != aantal_karakters:
karakter = input("Geef een karakter in: ")
if karakter >= 'a' and karakter <= 'z':
print(karakter, "is een kleine letter")
elif kara... |
totaal = 0
for x in range(5):
getal = int(input("Geef een getal "))
totaal += getal
print(totaal) |
def main():
fruitlist = ["appel", "banaan", "kers", "mandarijn", "mango"]
for element in fruitlist:
print(element)
element = element.upper()
print(element)
if __name__ == '__main__':
main() |
def main():
def delete_double(list):
for element in list:
if list.count(element) > 1:
list.remove(element)
else:
print(element)
numberlist = ["1", "1", "1", "1", "2", "5", "6", "8", "5", "5", "6", "8", "8", "7", "5"]
delete_double(numberlist)
... |
# -*- coding: utf-8 -*-
class Branch:
# poszczególne gałęzie - ściany piramid - mają postać:
# f(x, y) = (aX*x + bX) * (aY*y + bY)
def __init__(self, aX, bX, aY, bY):
self.aX = aX
self.bX = bX
self.aY = aY
self.bY = bY
def f(self, x, y):
return (self.aX*x + ... |
for i in range(int(input())):
n = int(input())
gest = list(input())
if "Y" in gest:
print("NOT INDIAN")
elif "N" in gest and "I" not in gest:
print("NOT SURE")
elif "I" in gest:
print("INDIAN")
|
for i in range(int(input())):
j = list(map(int, input().split()))
s = j[0]
if(j[1] + j[2] + j[3] <= s):
print(1)
elif((j[1] + j[2]) <= s or (j[2] + j[3]) <= s):
print(2)
else:
print(3)
|
t = int(input())
for i in range(t):
a, b, c = input().split()
t = 0
a = int(a)
b = int(b)
c = int(c)
t = a + b + c
if t == 180:
print("YES")
else:
print("NO")
|
for i in range(int(input())):
j = input()
s = ["2010","2015","2016","2017","2019"]
if j in s:
print("HOSTED")
else:
print("NOT HOSTED")
|
for i in range(int(input())):
j = input()
if(len(set(j)) == len(j)):
print("no")
else:
print("yes")
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
heade... |
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
if n<3:return n
index=2
for i in range(2,n):
if nums[i]!=nums[index-2]:
nums[index]=nums[i]
ind... |
"# Use of Directories It is like Map"
students = {"nakul": 20, "dhrumil": 20, "bhautik": 22}
print(students["nakul"])
"# Update the value in dictionaries #"
students["nakul"] = 21
print(students["nakul"])
"# Delete the value in dictionaries #"
del students["dhrumil"]
print(students)
"# Length of dictionaries In this it... |
def main():
#print("Inserir tamanho da matrix (m x n)")
linhas, colunas = input().split(" ")
#print(f"Inserir matriz ({linhas} x {colunas})")
matrix = [input().split("\n") for i in range(int(linhas))]
for i in range(len(matrix)):
matrix[i] = matrix[i][0].split(" ")
print(90)
rotated = rotate(matrix)
print_ma... |
f = open("ppp.txt", "r")
text = f.read().strip().split(" ")
f.close()
word = raw_input("what word are you looking for: ").strip()
def find_word_freq(w):
correct_words = [x for x in text if x == w]
return(len(correct_words))
print(find_word_freq(word))
phrase = raw_input("what word phrase are you looking fo... |
'''
Created on 27/10/2015
@author: Maxim Scheremetjew
amended 07/11/2016 by Maxim Scheremetjew
version: 1.1
'''
import argparse
import csv
import os
import urllib
import urllib2
from urllib2 import URLError
def _download_resource_by_url(url, output_file_name):
"""Kicks off a download and stores the file at the g... |
def square_digits(num):
num = str(num)
squarednum = ""
for i in range(len(num)):
squarednum += str((int(num[i]) ** 2))
squarednum = int(squarednum)
return squarednum
|
# ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet.
# ROT13 is an example of the Caesar cipher.
# Create a function that takes a string and returns the string ciphered with Rot13.
# If there are numbers or special characters included in the strin... |
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def getTuple(self):
return (self.x, self.y)
class Line():
def __init__(self, point1, point2):
self.point1 = point1
self.point2 = point2
if self.point1.x == self.point2.x:
self.m =... |
x=1
y=2
print (x+y)
print (x-y)
print (x*y)
print (x/y)
print (x**y)
print ("page 13")
print (x+2*y)
print (x-y/2)
print (2*x**3)
print ((x/2)*y)
print (x, y, sep="...")
print (x,"\n",y)
x=input ("entre el valor para x:")
x=input("")
x=float(x)
print (3*x)
t=input ("ingrese el valor del tiempo t:")
h=input ("ingrese l... |
chars = {chr(a + ord('А')): a for a in range(64)}
chars.update({' ': 64, ',': 65, '.': 66, '?': 67, '!': 68, '-': 69, '(': 70, ')': 71, '\'': 72, '"': 73, '&': 74,
':': 75, ';': 76, '*': 77, '\\': 78, '/': 79, '<': 80, '>': 81, '\n': 82})
chars.update({chr(a - 83 + ord('0')): a for a in range(83, 93)})
in... |
# File: Grid.py
# Description: This program takes in an input file of an any dimension square grid,
# and finds the largest product of 4 adjacent numbers in any direction.
# Student Name: Brionna Huynh
# Student UT EID: bph637
# Partner Name: Patricia Garcia
# Partner UT EID: pgg378
# Course ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 17:32:39 2021
@author: User
"""
def multiple(*numbers):
"""Istalgancha sonlarni qabul qilib, ularning ko'paytmasini
qaytaruvchi funksiya"""
multiples = 1
for number in numbers:
multiples *= number
return multiples
print(multiple(1,2,3,9, 10... |
'''
Created on Apr 4, 2021
@author: Q
'''
class FirstUnique(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.l_nums = list()
self.d_nums = dict()
self.start_idx = 0
for num in nums:
self.add(num)
def showFi... |
'''
Created on Nov 1, 2020
@author: Q
starting from 2 I know the steps you choose to the last ending tested floor is:
m, m-1, m-2 .... 1
this makes the total tests in worst scenario same in each range by decreasing the steps for next egg test by 1 with current egg increase test by 1
then within each step range, just ... |
'''
Created on Jan 3, 2021
@author: Q
1 loop for 3rd element and
2 points in a loop for 2 sum
'''
import sys
class Solution(object):
def threeSumClosest(self, nums0, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums0)
... |
'''
Created on Dec 26, 2020
@author: Q
'''
import random
class Solution(object):
def __init__(self, w):
"""
:type w: List[int]
"""
self.nums = [0] * len(w)
self.nums[0] = w[0]
for i in range(1, len(w)):
self.nums[i] = self.nums[i-1] + w[i]
print... |
'''
Created on Dec 20, 2020
@author: Q
double stack
one for one by one add
one for calculate the equation within the paired parenthesis
'''
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
st = list()
number = ''
for x... |
'''
Created on Sep 13, 2020
@author: Q
similar to 005
and mask the cell a[i,j] to 1 if [i,j] forms a palindromic string
'''
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
# add #
if len(s)==0: return 0
... |
'''
Created on Jan 9, 2021
@author: Q
backtracking
to speed up, it introduce a globe check to see if the node's dependency edges have all be visited,
if it has all been visited and there is no cycle (otherwise the func would have returned), there is no need to check this node in the following backtracking
'''
clas... |
'''
Created on Sep 7, 2020
@author: Q
in the main loop, the current array always includes pivot point: ascending pivot ascending
so whether mid is (l+r)//2 or sometimes to be (l+r)//2+1 is not important, because the structure keeps.
yet at the very end when there are 2 elements e.g. [5,1], we need to terminate
bec... |
CODE = 'EBG KVVV vf n fvzcyr yrggre fhofgvghgvba pvcure gung ercynprf n yrggre jvgu gur yrggre KVVV yrggref nsgre vg va gur nycunorg. EBG KVVV vf na rknzcyr bs gur Pnrfne pvcure, qrirybcrq va napvrag Ebzr. Synt vf SYNTFjmtkOWFNZdjkkNH. Vafreg na haqrefpber vzzrqvngryl nsgre SYNT.'
ALPHABET_NUM = 26
def rotate(rot, c... |
class SpellChecker:
def __init__(self):
self.words = []
def load_words(self,file_name):
self.words = open(file_name).readlines()
self.words = map(lambda x: x.strip(), self.words)
return self.words
def check_word(self,word):
return word.strip('.').lower() in self.words
def check_words(self, sen... |
# -*- coding: utf-8 -*-
# @Time : 18-10-16 上午10:47
# @Author : Mingan Luan
# @File : Pomodoro_Timer.py
"""
A Pomodoro Technique.
How it works:
1. Set a pomodoro timer (default is 25 min).
2. When the timer ends, a short break timer (default is 5 min) kicks in.
3. Go to step 1.
4. After four pomod... |
"""
Description
Given an array of integers,
find how many unique pairs in the array such that their sum is equal to a specific target number.
Please return the number of pairs.
Example
Given nums = [1,1,2,45,46,46], target = 47
return 2
1 + 46 = 47
2 + 45 = 47
"""
class Solution:
"""
* @param nums an array... |
"""
Description
Implement double sqrt(double x) and x >= 0.
Compute and return the square root of x.
Notice
You do not care about the accuracy of the result, we will help you to output results.
Example
Given n = 2 return 1.41421356
"""
from __future__ import division
def sqrt(x):
if x == 0.:
return 0.
elif x =... |
"""
Description
Your are given a binary tree in which each node contains a value.
Design an algorithm to get all paths which sum to a given value.
he path does not need to start or end at the root or a leaf,
but it must go in a straight line down.
Example
Given a binary tree:
1
/ \
2 3
/ /
4 2
for ... |
class SymbolNode:
def __init__(self, start_symbol=None, symbolic_str=''):
self.start_symbol = start_symbol
self.raw_str = raw_str
self.children = []
class SymbolTree:
def __init__(self, startSymbol):
self.root = SymbolNode(startSymbol)
def parse_node(self, ra... |
"""
Description
Given an array nums of n integers,
find two integers in nums such that the sum is
closest to a given number, target.
Return the difference between the sum of the two integers and the target.
Example
Given array nums = [-1, 2, 1, -4], and target = 4.
The minimum difference is 1. (4 - (2 + 1) = 1).
... |
'''
https://monkeysayhi.github.io/2017/08/04/%E3%80%90%E5%88%B7%E9%A2%98%E3%80%91Search-in-a-Big-Sorted-Array/
Given a big sorted array with positive integers sorted by ascending order.
The array is so big so that you can not get the length of the whole array directly,
and you can only access the kth number by Array... |
"""
Description
Partition an unsorted integer array into three parts:
The front part < low
The middle part >= low & <= high
The tail part > high
Return any of the possible solutions.
Notice
low <= high in all testcases.
Example
Given [4,3,4,1,2,3,1,2], and low = 2 and high = 3.
Change to [1,1,2,3,2,3,4,4].
xw
([1... |
"""
Description
Given an array of integers,
find how many pairs in the array such that their sum is bigger than a specific target number.
Please return the number of pairs.
Example
Given numbers = [2, 7, 11, 15], target = 24.
Return 1. (11 + 15 is the only pair)
Challenge
Do it in O(1) extra space and O(nlogn) tim... |
def adicao(operando_1, operando_2):
return operando_1 + operando_2
def subtracao(operando_1, operando_2):
return operando_1 - operando_2
def multiplicacao(operando_1, operando_2):
return operando_1 * operando_2
def divisao(dividendo, divisor):
return dividendo / divisor
def faz_nada():
pass... |
class A:
def __init__(self, name, salary):
self.name = name
self.__salary = salary
def _assign_values_method(self):
# self.name=name
return self.name
class B(A):
def __init__(self, id, name, age, salary):
super().__init__(name, salary)
self._id = id
... |
# even numbers
inputList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 342, 4, 24, 2]
outputList = [var for var in inputList if var % 2 == 0]
print outputList
# squares of 1-10 numbers
squareNumberList = [var ** 2 for var in range(1, 10)]
print squareNumberList |
"""1.Write a program that examines three variables—x, y, and z— and prints
the largest odd number among them. If none of them are odd, it should print a message to that effect."""
a, b, c = 2, 4, 6
odd_list = []
if a % 2 != 0:
odd_list.append(a)
elif b % 2 != 0:
odd_list.append(b)
elif c % 2 != 0:
odd_list.... |
# number = 34
# binary = ''
# while number != 0:
# binary = str(int(number % 2))+binary
# number = int(number) / 2
# print(binary)
# convert to single list
a = [1, [2, 3], [4, 5, [6, 7, [8, [9]]]]]
def convert_to_list(list_elem):
if type(list_elem) is not type([]):
return_list.append(list_elem)
... |
li = [1, 2, 3, 12, 11]
a = iter(li)
while True:
try:
print(a.__next__())
except StopIteration:
break
|
def isPrime(num):
count = 2
k = 0
for i in range(count, num + 1):
if num % count == 0:
k += 1
factors(num)
break
else:
continue
if k == 0:
print 'number is prime'
def factors(n):
for i in range(1, n):
if n % i == 0:
... |
# def sayHello(a):
# print('Hello')
# return a
#
#
# print(sayHello(1))
"""sum fo integers """
# def sumOfIntegers(a,b):
# return a+b
# a=0
# b=3
# c=sumOfIntegers(a,b)
# if c>0:
# print(c)
# else:
# print('negative value')
# def sum(a, b=0):
# c = a + b
# return a, b, c
#
#
# temp1, temp... |
"""3.Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered.
If no odd number was entered, it should print a message to that effect."""
li1 = input('Enter 10 numbers with space').split()
odd_list = []
if len(li1)==0:
print('Enter some values')
else:
for... |
"""1.The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder.
One way to find the GCD of two numbers is based on the observation that if r is the remainder when a is divided by b,
then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a.
Write a func... |
"""7.A palindrome is a word that is spelled the same backward and forward, l
ike "Malayalam" and "Noon" . Recursively, a word is a palindrome if the first and last letters are
the same and the middle is a palindrome. Write a function called is_palindrome that takes a string
argument and returns True if it is a palindro... |
import csv
import pandas as pd
import numpy as np
import parameters as P
def csv_dict_list(variables_file):
mydict = {}
reader = csv.reader(open(variables_file, "rb"))
for i, rows in enumerate(reader):
if i == 0: continue
k = rows[0]
v = rows[1]
try:
value = floa... |
masa=float(input("Ingresa tu masa en kilogramos"))
peso=float(input("Ingresa tu altra en metros"))
imc=masa/altura**2
print("Tu imc es: ")+str(imc))
if imc >= 25 :
print("Tienes sobrepeso")
if imc <= 19 :
print("Tienes bajo peso")
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#功能要求:
# 要求用户输入总资产,例如:2000
# 显示商品列表,让用户输入商品名称,加入购物车
# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
# 附加:可充值、某商品移除购物车
#用字典构造以购买产品,购物车
#用户输入总资产
zong_zi_chan = input("请输入你的总资产")
#将用户输入总资产转换成数字类型
zong_zi_chan1 = int(zong_zi_chan)
#打印出总资产
print("您的总资产为",zong_zi_chan1,"元")
print("\n")
#产品字典... |
dictionary = []
def displayDictionary():
if dictionary==[]:
print("*** The dictionary is empty ***")
else:
print("*** Known words ****")
for i in dictionary:
print("%-8s %-8s"%(i[0],i[1]))
def lookup(word):
if dictionary==[]:
words=input("How do i transla... |
def selection_sort(list):
for i in range( len(list) ): # Loop through the entire array
# Find the position that has the smallest number
# Start with the current position
minPos = i
for j in range(i+1, len(list) ): # Scan what's left
if len(list[j]) < len(list[mi... |
def total(R1,R2,R3):
R=1/(1/R1+1/R2+1/R3)
return R
R1=float(input("R1 is:"))
R2=float(input("R2 is:"))
R3=float(input("R3 is:"))
print(total(R1,R2,R3))
|
import random
def randomised_st_connectivity(G, n, s, t):
stepcount = 0
current_vertex = s
while (current_vertex != t) and (stepcount < 2*n**3):
a=random.randint(0,n-1)
# print(a)
if int(G[current_vertex-1][a]) != 0:
current_vertex = a+1
else:
contin... |
A = int(input("The start value:"))
B = int(input("The end value:"))
L=1
count=0
for i in range(A,B+1):
print(i,end=" ")
count+=1
if (L==count):
print()
L+=1
count=0
else:
continue
A = int(input("Line:"))
for i in range(A):
for j in range(i):
print(A,end="\t"... |
import turtle
wn = turtle.Screen()
my_turtle = turtle.Turtle()
for i in range(0,101,10):
my_turtle.forward(i)
my_turtle.left(90)
my_turtle.forward(i)
my_turtle.left(90)
wn.exitonclick()
|
# import random
#
# def main():
# smaller=int(input("Enter the smaller numbers:"))
# larger=int(input("Enter the larger number:"))
# myNumber=random.randint(smaller,larger)
# count=0
# while True:
# count +=1
# usernumber=int(input("Enter your guess:"))
# if usernumber < myNu... |
def translate(animal,language):
if animal=="cat" :
if language=="Chinese":
ww="The translate of a cat into Chinese is Māo"
elif language=="German":
ww="The translate of a cat into German is katze"
elif language=="French":
ww="The translate of a cat into Fr... |
a = 0
for i in range(10):
a = a + 1
print(a,"\n")
for j in range(10):
a = a + 1
print(a)
mylist = [1,2,3,4,5,6,7,8,9,10]
mylist[0:10:2] = ['a', 'b', 'c', 'd', 'e']
print(mylist)
mylist[9::-3] = [22, 22, 22, 22]
print(mylist)
lst=['my ', 'big ', 'fat ']
lst.append('wedding ')
lst.extend(['next','w... |
import math
def Volume(R):
V = (4*math.pi*R*R*R)/3
return V
R = float(input("sphere radius:"))
print("volume is:",Volume(R))
|
import random
def coin_toss(number):
A = random.randint(0,1)
if A==0:
X="heads"
else:
X="tails"
return X
H=0
T=0
number=int(input("number of coin tosses:"))
for i in range(number):
print(coin_toss(number))
if coin_toss(number)=="heads":
H+=1
else:
T+=1
pr... |
a=int(input("ENTER YOUR ROLL NUMBER"))
if a==1:
print ("JONES")
a=int(input("ENTER YOUR ROLL NUMBER"))
if a==1:
print ("JONES")
elif a==4:
print ("KODIDETY SOLOMON JONES")
break
elif a==4:
print ("KODIDETY SOLOMON JONES")
else:
print ("invalid entry")
|
a=input("value of A")
b=input("value of B")
if a>b:
print ("A is greater")
if a<b:
print ("B is greater")
if a==b:
print ("Both are equal")
|
'''
Michael Galarnyk
1. Define a function named to_number(str) that takes a string as a parameter, converts it to an int value, and returns that int value.
2. Define a function named add_two(n1, n2) that takes two ints as parameters, sums them, and then returns that int sum value.
3. Define a function named cube(n) th... |
import turtle
import math
def square(t,length):
"""Draws a square with the given length.
:param t: Turtle
:param length: Side length
"""
for i in range(4):
t.fd(length)
t.lt(90)
def polygon(t,length,n):
"""Draws a polygon with the given number and length.
:param t: Turtle
... |
import turtle
bob = turtle.Turtle()
def square(t,length):
"""Draws a square with the given length.
:param t: Turtle
:param length: Side length
"""
for i in range(4):
t.fd(length)
t.lt(90)
square(bob,100) |
import re
class Lexer(object):
"""dosource_codering for Lexer"""
def __init__(self, source_code):
self.source_code = source_code
def token(self):
#print('test')
# Where all the tokens dibuat oleh lexer akan di stored
tokens = []
# Menampung wordlist di test lang
source_code =self.source_cod... |
#Alex Shelton
#Project Euler Problem 3:
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
#Answer = 6857
#Get the factors in a list using % Done
# Checking if the number is prime or not: Done
# finding largest prime
import math
import time
def getFact... |
from argparse import ArgumentParser
from pathlib import Path
import shutil
import random
def main(input_dir: Path, output_dir: Path, num_move, filetype=None):
if filetype is None:
paths = list(Path(input_dir).iterdir())
else:
paths = list(Path(input_dir).glob("*" + filetype))
random.shuffl... |
from time import time
class ContextTimer:
""" Usage:
with ContextTimer() as timer:
#do stuff
print("Current time: ", timer.time)
# do more stuff
print("Current time: ", timer.time
print("Total process took : ", timer.time, " seconds")
"""
def __init__(self, na... |
"""Utility functions"""
import os
import pandas as pd
import matplotlib.pyplot as plt
def plot_selected(df, columns, start_index, end_index):
"""Plot the desired columns over index values in the given range."""
df_temp = df.ix[start_index : end_index, columns]
plot_data(df_temp, "Selected data")
def symb... |
"""Locate maximum value."""
import numpy as np
def get_max_index(a):
"""Return the index of the maximum value in given 1D array."""
return a.argmax()
def test_run():
a = np.array([9, 6, 2, 3, 12, 14, 7, 10], dtype=np.int32) # 32-bit integer array
print "Array:", a
# Find the maximum and i... |
"""Fit a polynomial to a given set of data points using optimization."""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize as spo
def error_poly(C, data): # error function
"""Compute error between given polynomial and observed data.
Parameters
----------
C: ... |
string = raw_input()
Q = int(raw_input())
for i in xrange(Q):
sub = raw_input()
if sub in string:
print "Yes"
else:
print "No"
|
T = int(raw_input())
def printArray(arr):
for item in arr:
print item,
print
def merge(arr1,arr2,N,M):
i = j = k = 0
merged = [0] * (N+M)
while( i < N and j < M):
if arr1[i] >= arr2[j]:
merged[k] = arr1[i]
i += 1
k +=1
else:
merged[k] = arr2[j]
j +=1
k +=1
if i!=N:
while(i < N):
... |
import time
import pickle
import random
from random import seed,randint
class OTGame(object):
'''Oregon Trail text game. Developed by Python Foundations Class, Hack Oregon Summer 2016'''
def __init__(self):
# self.intro()
# self.start_month = self.going()
# self.role, self.bank = self.c... |
"""Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the ... |
"""This program gets the bitcoin value from worldcoinindex.com using beautfiulsoup library
and performs profit/loss calculations with it based on user's 2 personal investments at different btc rates
using smtplib it sends different content email notificationsto user that vary depending on the high/low profit levels
us... |
import json
import datetime
# gets the json data from dict and loads into variable birthday, then passes this on to function birthday_date
def dictionary():
birthday = {}
with open('dict.json', 'r') as openfile_object:
birthday = json.load(openfile_object)
months(birthday)
def months(birthday):
dates = str(b... |
"""Make a two-player Rock-Paper-Scissors game."""
import random
words = ['rock', 'paper', 'scissors']
def function():
while True:
word = random.choice(words)
input = raw_input("Pick rock, paper, or scissors:")
print "the computer picked %s" % word
if input == 'rock' and word == 'scissors':
print "You won... |
'''
In order to win the senate, the Republicans will have to win 21 of the 36 races
this November.
What is the probability they will win 21 of these races?
Created on Sep 28, 2014
@author: adrian
'''
# QSTK Imports
# Third Party Imports
import pandas as pd
import numpy as np
import random as rn
from scipy.stat... |
def primeCheck(sentPrime):
for i in range(3,int(sentPrime**0.5)+1,2):
if sentPrime%i == 0:
return False
return True
def main():
count = 4 # Start count one step back due to location of +=
prime = 11 # Start 5th prime due to lower primes' problems with above
while count < 10002:
... |
""" def prime-factorization(n):
for i < 2 to sqrt(n)
if n%i == 0
ct < 0
while(n%i == 0)
n = n/i
ct++
Print(i, ct)
if(n! = 1)
Print(n, 1)
"""
def generate_prime_factors(argnumber):
""" Returns prime factors that compose argnumber """
if type(argnumber) != int:
rai... |
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.plot(input_values,squares,linewidth=5)
# 设置图标标题, 并给坐标轴加上标签
plt.title("Square Number",fontsize = 14)
plt.xlabel("value",fontsize = 13)
plt.ylabel("Square of value",fontsize =14)
# 设置刻度标记大小
plt.tick_params(axis = 'both',labelsize = ... |
my_list = [232,32,1,4,55,4,3,32,3,24,5,5,5,34,2,35,5365743,52,34,3,55]
#Your code go here:
for each_item in my_list:
print(each_item) |
#!/usr/bin/python3
# coding: utf-8
# 上面两句注释必须要,防止无法打印中文的
import time
import datetime
import os
word=['hot']
dic=['doh', 'got' , 'dot' , 'god' , 'tod' , 'dog' , 'lot' , 'log']
w = ['hot']
dic = ['doh', 'got', 'dot', 'god', 'tod', 'dog', 'lot', 'log']
def result(n,m,li):
length=len(li)
i=n-2
j=n-1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.