text stringlengths 37 1.41M |
|---|
"""Furik loves math lessons very much, so he doesn't attend them, unlike Rubik.
But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math
teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:"""
"""You are given a system of equations: a**2 ... |
import os
from src.config import (
logging,
DEFAULT_FILE_NAME
)
class City:
""" Can be destroyed, has a name and links """
def __init__(self, name):
self.name = name
self.links = {}
def get_directions(self):
""" Available links - remember these can be blown away! """
... |
import numpy as np
def hist_match(after, before):
"""
Normalisation of images based on histogram matching to the before image.
Input:
-----------
after: np.ndarray
Image to transform; the histogram is computed over the flattened
array
before: np.ndarray
... |
"""
Toy game for explaining how to work with POMDPs
Copied from: https://github.com/yandexdataschool/Practical_RL/blob/master/week7/rockpaperscissors.py
"""
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
class RockPaperScissors(gym.Env):
"""
Rock-paper-scissors game against... |
# coding=utf-8
"""
题目描述
有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,
假如兔子都不死,问每个月的兔子总数为多少?
/**
* 统计出兔子总数。
*
* @param monthCount 第几个月
* @return 兔子总数
*/
public static int getTotalCount(int monthCount)
{
return 0;
}
本题有多组数据,请使用while (cin>>)读取
输入描述:
输入int型表示month
输出描述:
输出兔子总数int型
示例1
输入
复制
9
输出
复制
34
"""
# 相当于求 1 1 ... |
# coding=utf-8
"""
题目描述
将一个字符中所有出现的数字前后加上符号“*”,其他字符保持不变
public static String MarkNum(String pInStr)
{
return null;
}
注意:输入数据可能有多行
输入描述:
输入一个字符串
输出描述:
字符中所有出现的数字前后加上符号“*”,其他字符保持不变
示例1
输入
复制
Jkdi234klowe90a3
输出
复制
Jkdi*234*klowe*90*a*3*
"""
# 将数字周围都加上* 两个数字中间肯定有两个** 然后替换掉就行了
# 正则 sub + lambda 替换,非常简单
import re
whil... |
"""
题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
示例1
输入
复制
hello world
输出
复制
5
"""
# split 分割
# -1 取最后一个
# len 求长度
while 1:
try:
print(len(input().split()[-1]))
except:
break
|
"""
题目描述
描述:
输入一个整数,将这个整数以字符串的形式逆序输出
程序不考虑负数的情况,若数字含有0,则逆序形式也含有0,如输入为100,则输出为001
输入描述:
输入一个int整数
输出描述:
将这个整数以字符串的形式逆序输出
示例1
输入
复制
1516000
输出
复制
0006151
"""
# 把输入的数字当成字符串处理
# [::-1] 倒序
while 1:
try:
print(input()[::-1])
except:
break |
def quicksort(A, i, j, calculator):
if i>=j:
return calculator
else:
q, calculator=partition(A, i, j, calculator)
calculator=quicksort(A, i, q-1, calculator)
calculator=quicksort(A, q+1, j, calculator)
return calculator
def partition(A, left, right, calculator):... |
"""
Stock Pricing Problem:
A competition model between two companies.
"""
from matplotlib import pyplot
def company_a(x, y):
a = 0.222
b = -0.0011
return a*x + b*x*y
def company_b(x, y):
c = -1.999
e = 0.010
return c*y + e*x*y
def euler(step, start, end, initial_values, diffs):
"""
... |
import math
import random
from matplotlib import pyplot
def f(x, mean=1, deviation=.25):
exponent = - float((x-mean)**2)/(2*deviation**2)
devisor = math.sqrt(2*math.pi*deviation**2)
return 1/devisor * math.e**exponent
initial_value = 1000000
days = [n for n in range(260)]
values = [random.uniform(-init... |
import sys
import exercise_2_1
def exercise(width:int = 8) -> None:
"""
Print a diamond
Params:
width -> The max width of the diamond (is even)
Example
> exercise(8)
##
####
######
########
########
######
####
##
"""
spaces:int = (width // 2) - 1
characters = 2
... |
import sqlite3
import urllib.request
from bs4 import BeautifulSoup
import re
#import ssl
# Deal with SSL certificate anomalies Python > 2.7
#scontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
scontext = None
# 1. Elegir una página web.
# 2. Extraer el texto de esa página.
# 3. Dividirlo en palabras.
# 4. Quitar las... |
def my_global_function(a,b):
"""Global Function. return a+b"""
return a + b
try:
None.some_method_none_does_not_know_about()
except Exception as ex:
ex2 = ex
print(ex2.args[0])
print(ex2.__class__)
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
msg = ex.ar... |
#just like Models, forms are classes in Django
from django import forms
#validator to validate data
from django.core import validators
#most of the time we use a form to generate some HTML
class SuggestionForm(forms.Form):
#we have three fields currently
name = forms.CharField()
email = forms.EmailField()
#so t... |
#!/usr/bin/env python3
import sys
encodingMap = {
'0': ':SeriousSloth:',
'1': ':panik:'
}
inputString = sys.stdin.read()
decodedString = ''
# empty string of decoded bits
bits = ''
while True:
# try to find both symbols in the string
# the closer one represents the next bit
nearest = None
mi... |
f=open('bank_analysis.txt',"a")
import pandas as pd
data_file = "budget_data.csv"
data_file_df = pd.read_csv(data_file)
data_file_df.head()
count = data_file_df.shape[0]
count
total = data_file_df["Profit/Losses"].sum()
total
AccountChange = data_file_df["Profit/Losses"].diff()
AccountChange
data_file_df["diff"] ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 06:38:32 2018
@author: Jake
"""
import itertools
items = [1, 2, 3, 4]
powerset = [x for length in range(len(items)+1) for x in itertools.combinations(items, length)]
from itertools import chain, combinations
def Powerset(iterable):
s =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 22 09:01:02 2017
@author: Jake
"""
class Weird(object):
def __init__(self, x, y):
self.y = y
self.x = x
def getX(self):
return x
def getY(self):
return y
class Wild(object):
def __init__(self, x, y... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 13 06:23:07 2017
@author: Jake
"""
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 2 06:58:26 2018
@author: Jake
"""
# import NumPy into Python
import numpy as np
# Create a 1000 x 20 ndarray with random integers in the half-open interval [0, 5001).
X = np.random.randint(5001, size = (1000, 20))
# print the shape of X
print('X... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 10:00:45 2018
@author: Jake
"""
import random
def stochasticNumber():
'''
Stochastically generates and returns a uniformly distributed even number between 9 and 21
'''
num = random.randint(9,21)
if num % 2 == 0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 06:39:20 2017
@author: Jake
"""
def odd(x):
'''
x: int
returns: True if x is odd, False otherwise
'''
# Your code here
return(x%2 == 1) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 07:35:21 2018
@author: Jake
"""
# prerequisite package imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
fuel_econ = pd.read_csv('fuel_econ.csv')
#print(fuel_econ.head(5))
#TODO: Task 1: Plot t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 06:04:35 2018
@author: Jake
"""
# Makes Python package NumPy available using import method
import numpy as np
# Creates matrix t (right side of the augmented matrix).
t = np.array([4, 11])
# Creates matrix vw (left side of the augmented matrix... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 06:35:16 2017
@author: Jake
"""
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all t... |
def first_function():
'''
(NoneType) -> str
Return the string 'I can write code!'.
>>> first_function()
'I can write code!'
Hint: this is not a trick question -- just a really easy one. If you are wondering what
NoneType means, it indicates that there are no arguments - no types are
being passed.
'''
retur... |
# dynamic_programming.py
# ----------
# User Instructions:
#
# Create a function compute_value which returns
# a grid of values. The value of a cell is the minimum
# number of moves required to get from the cell to the goal.
#
# If a cell is a wall or it is impossible to reach the goal from a cell,
# assign that cell... |
'''
The O(nlog(n)) time algorithm for calculating the search number of a tree
given in [1].
[1]: The Complexity of Searching a Graph. N. Megiddo et. al.
'''
import networkx as nx
def isEdge(graph):
'''
Given a graph, checks whether it is just an edge.
INPUT
graph: A NetworkX graph
OUTPUT
edg... |
'''
This file contains utility functions
'''
from typing import List
import pickle
def save_pickle(filename: str, l: List):
'''
Saves a list into a pickle file
:param filename: output file
:param l: input list
:return: None
'''
with open(filename, 'wb') as f:
pickle.dump(l, f)
de... |
""" filedb.py """
import pickle
import os
class FileDB:
""" Text file used to persist data
Args:
filename: The path to the file.
"""
def __init__(self, filename):
if os.path.isfile(filename):
self.filename = filename
else:
raise FileNotFoundError(... |
try:
name = input()
if len(name)>3:
print("Account Created")
else:
raise valueError
except:
print("Invalid Name") |
s1 = {1, 2, 3}
print(s1)
# make a copy of the set, not just a copy of the reference
s2 = s1.copy()
print("s1: {} | s2: {}".format(s1, s2))
s1.remove(2)
print("After removing 2 from s1 | s1: {} | s2: {}".format(s1, s2))
# find the 'difference' between two sets, meaning 'contents of A minus contents of B'
print("s1.di... |
# first-try.py
# Needed to get myself off Jupyter Notebook and into a proper IDE :D
#
# I'm using this Python file to practice what I'm learning in this Udemy course:
# https://www.udemy.com/course/complete-python-bootcamp/
#
# This file isn't meant to have any purpose beyond learning/experimenting with Python feature... |
import timeit
print("-".join(str(n) for n in range(100)))
# Now I time how long it takes to do the code above 10000 times
s = ''
time_in_seconds = timeit.timeit('s = "-".join(str(n) for n in range(100))', number=10000)
print("It took {} seconds to create that string 10000 times".format(time_in_seconds))
time_in_second... |
import sys
#print('<ul>')
#print('<li>')
#for param in sys.argv[1:]:
# print (param)
#print('</li>')
#print('<li>')
#for param in sys.argv[1:]:
# print (param.upper())
#print('</li>')
#print('<li>')
#for param in sys.argv[1:]:
# print (param.lower())
#print('</li>')
#print('</ul>')
str_input = " ".join(sys.a... |
"""
https://www.pythonprogramming.in/how-to-use-new-and-init-in-python.html
"""
class Shape:
def __new__(cls, sides, *args, **kwargs):
if sides == 3:
return Triangle(*args, **kwargs)
else:
return Square(*args, **kwargs)
class Triangle:
def __init__(self, base, height)... |
def add_name(names, new_name):
"""
names is a list of strings, new_name is a string.
add_name checks if the `new_name` is in the list.
If it is not in the list:
* the `new_name` is added to the list
* the list is sorted
* function returns True
if it is in the list the functi... |
list1 = [11, 11, 33, 44, 55]
list2=[13,33,31,47,44]
my_list =list1+list2
my_set = set(my_list)
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)
|
import math
base_number = float(input("Enter the base number"))
power = base_number*10
print("Power is =",power)
|
my_list = [*range(1,100)]
this_year = 2019
birthday_year = int(input("Enter the birthday year: "))
your_age = this_year - birthday_year
for age in my_list:
if age == your_age:
print(age, "This my age !!")
break
print(age, "not my age")
|
from random import randrange
user_pets = []
class Pet:
hunger_threshold = 3
hunger_decrement = 1
boredom_threshold = 3
boredom_decrement = 2
sounds = ["Hi", "Hello"]
# INITIALIZE ATTRIBUTES
def __init__(self, name, type):
self.name = name
self.type = type
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:40:51 2020
@author: Kapil
"""
print("Book Shop\n")
orders=[["34587","Learning Python,Mark Lutz",4,40.95],["98762","Programing python, Mark Lutz",5,56.80],["77226","Head first Python,Paul Barry",3,32.95],["88112","Einfuhrung in Python3, Bernd klein",3,24.99]... |
a=int(input("Enter a no"))
b=a
rev=0
while (a>0):
rem=a%10
rev=rev*10+rem
a=a//10
print(rev)
if (b==rev):
print("Pallindrome")
else:
print("Not Pallindrome")
|
import numpy as np
from paretoset.algorithms_numpy import paretoset_efficient, pareto_rank_naive
from paretoset.utils import user_has_package, validate_inputs
import pandas as pd
if user_has_package("numba"):
from paretoset.algorithms_numba import BNL
def paretoset(costs, sense=None, distinct=True, use_numba=... |
#-*-coding:utf-8-*-
def trim(s):
if s=='':
return s
while s[0]== ' ':
s= s[1:]
if s=='': #防止清空成''
return s # break
while s[-1]== ' ':
s= s[:-1]
if s=='': #防止清空成''
return s # break
return s
#测试:
if trim('hello ')!='hello':
... |
### 匿名函数
#Python中,对匿名函数提供了有限支持
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
#[1, 4, 9, 16, 25, 36, 49, 64, 81]
## 关键字lambda表示匿名函数,冒号前面的x表示函数参数
## 匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果
## 匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数:
>>> f = lambda x: x * x
>>> f
# <function <lambda> at 0x101c6ef28>... |
### 函数的参数
## Python的函数定义灵活度非常大。
## 除了正常定义的必选参数外,还可以使用默认参数、可变参数和关键字参数
# 位置函数
def power(x):
return x * x
# 要计算x4、x5…,就要把power(x)修改为power(x, n),用来计算x^n
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
## x和n,这两个参数都是位置参数,调用函数时,传入的两个值按照位置顺序*依次*赋给参数x和n
# 默认函数
# 新的power(... |
### 高级特性
# 构造一个1, 3, 5, 7, ..., 99的列表
L = []
n = 1
while n <= 99:
L.append(n)
n = n + 2
## 代码越少,开发效率越高。越简单越好。
## 切片
# 取一个list或tuple的部分元素是非常常见的操作
# 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环:
>>> r = []
>>> n = 3
>>> for i in range(n):
... r.append(L[i])
...
>>> r
['Michael', 'Sarah', 'Tracy']
# 应上面的问题,取前3个元素,用一行... |
#incremement n by 1;
#only check it against previous primes.
prime_numbers = [2,3]
not_factors = []
def prime():
#print "prime numbers up top are: "
#print prime_numbers
n = prime_numbers[-1]
n = n + 1
#print "n up top is: "
#print n
while n > 1 and n < 1000000:
for p in prime_... |
# This is intuitive but VERY slow
def lib(n):
""" Functional definition of Fibonacci numbers """
if n <= 1:
return 0
else:
return lib(n - 1) + lib(n - 2)
def fib2(x):
if x < 5:
return lib(x)
else:
return 0
|
import math
# Calculates f(x)
def f_function(x):
return math.sin(x)
# Calculates f"(x)
def f_function_2_der(x):
return -math.sin(x)
# Calculates the error for the given trapezoidal sums approximation
def calculate_error(integration_range, points):
partitions_amount = len(points) - 1
der_2_abs_re... |
class PayrollSystem:
def __init__(self):
self._employee_policies = {
1: SalaryPolicy(3000),
2: SalaryPolicy(1500),
3: CommissionPolicy(1000, 100),
4: HourlyPolicy(15),
5: HourlyPolicy(9)
}
def get_policy(self, employee_id):
pol... |
"""
Basic knapsack solvers: dynamic programming and various greedy solvers
"""
from copy import copy
def dynamic_prog(items_count, capacity, density_sorted_items, verbose_tracking):
"""
Run the dynamic programming algorithm. It is right here!
:param items_count:
:param capacity:
:param density_so... |
"""object has no dict like method."""
class Vhost(object):
def __init__(self, name, permission):
self.name = name
self.permission = permission
if __name__ == '__main__':
vhost1 = {
"name": "test2",
"permissions": "partily"
}
print "name:", vhost1["name"]
print "permissions:", vhost1["permissions"]
v... |
# Julio Ureta, CSC102
#Define a class called Car with the following attributes:
# Total Odometer Miles
# Speed in miles per hour
# Driver Name
# Sponsor
import random
class Car():
def __init__(self):
print("A Car is instantiated.")
self.total_odometer_miles = 0.0
s... |
class Stack:
def __init__(self):
self._data = []
def is_empty(self):
return not self._data
def push(self, data):
self._data.append(data)
def pop(self):
try:
return self._data.pop()
except IndexError:
raise Exception('Invalid Operation: ... |
def oddTuples(tup):
'''Take a tuple as input and return
a new tuple as output, where every OTHER
element of the input tuple is copied, starting
with the first one.'''
newTup = ()
for n in range(len(tup)):
if n % 2 == 0:
newTup += (tup[n],)
return newTup
|
# method to determine odds of pulling three balls of the same color
# from a cauldron containing three green and three red balls
def redGreenTrial(numTrials):
import random
"""
Returns the odds of pulling three consecutive balls of the same
color from a set containing three balls of each color. Balls
... |
#------------------------------------------------------------------------------------------------------------------------------------------------------
# Creator: Sarah Gillespie
# Date: August 13th, 2019
# Filename: randomWord.py
# Description: random vocab generator for GRE Questions
# Github: ht... |
'''
基本数据类型
1.Number(数字)
2.String(字符串)
3.List(列表)
4.Tuple(元组)
5.Sets(集合)
6.Dictionary(字典)
'''
#整形变量
count = 100
#浮点型变量
miles = 100.0
#字符串
name = "fayuan"
print(count)
print(miles)
print(name)
#连续多个变量赋值
a, b, c, d = 20, 5.5, True, 4 + 3j
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(isinstance(a, i... |
a1 = 2 # Varaibles cannot start with a number
b = a1 # B is undefined, it's value cannot be given to a1
x = 2
y = x + 4 # is it 6? No, the defined x was lowercase, case matters in variables, this will throw an error, change uppercase to lower.
from math import tan,pi # math should be lowercase
print(tan(pi)) # print st... |
def next_letter(c, key):
if ord(c) + key <= 90:
return chr((ord(c) + key))
return chr((ord(c) + key) - 26)
def previous_letter(c, key):
if ord(c) - key >= 65:
return chr((ord(c) - key))
return chr((ord(c) - key) + 26)
def cipher_wheel_crypt(phrase, key):
result = ""
for c i... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#Import CSV into Pandas DataFrame
df = pd.read_csv('OlympicsWinter.csv',usecols=["Year", "Sport", "Country", "Gender", "Event", "Medal"])
#Replace spaces in col names with underscore and sets all to lowercase
df.columns = df.columns.str.strip().st... |
# you can simply [::-1]
def reverser(string: str):
result = ""
for i in range(len(string)-1, -1, -1):
result += string[i]
return result |
from typing import List
def inserter(items: List, string: str) -> None:
items = items.copy()
for i in range(len(items)):
items[i] = string + str(items[i])
return items
|
from typing import Dict
def generator(n: int) -> Dict[int, int]:
result = dict()
for i in range(1, n+1):
result[i] = i ** 2
return result
print(generator(15)) |
def reverse(n):
rev = 0
while n > 0 :
rem = n % 10
rev = rev * 10 +rem
n =n//10
return rev
print(reverse(12345))
|
from math import sqrt
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def primesquare(l):
flag=0
if len(l)==1:
n=l[0]
if(sqrt(n)%1==0):
return True
else:
for i in range(0,len(l)):
if(sqrt(l[i])... |
import itertools, time
PUZZLE_INPUT = 'day_1_input.txt'
def get_puzzle_input(puzzle_file):
with open(puzzle_file) as file_input:
return [int(line.rstrip('\n')) for line in file_input]
def find_first_duplicate(changes):
freq = 0
found = set()
for change in itertools.cycle(changes):
freq += change
... |
# 创建dict字典
dict1 = {'A': '11', 'B': '22', 'C': '33'}
# dict特征1:根据key获取value
print(dict1['B'])
# dict特征2:修改value
dict1['A'] = 11
print(dict1)
# dict特征3:del删除
del dict1['C']
print(dict1)
# dict特征4:clear清空
# dict1.clear()
# print(dict1)
# dict特征5:加入新的元素
dict1['C'] = 33
print(dict1)
# 创建defaultdict
from collections im... |
# set特性1不存在重复值
s1 = {1,1,2,3,4}
# print(s1)
# Output:{1, 2, 3, 4}
# set特征2访问是无序的,不支持通过索引访问集合元素
# set特征3是可变的,支持加入不同类型的元素,同时发现加入字符串输出时在第一个,也证明了无序性
s1.add('python')
# print(s1)
# Output:{'python', 1, 2, 3, 4}
# set特征3:续-但是不能向set中加入可变容器例如列表、字典-->会报错unhashable type:‘list’
# s1.add([1,2])
# print(s1)
# Output:TypeError: u... |
__author__="albert"
__date__ ="$Mar 19, 2012 1:26:31 AM$"
# Puzzle_1: string with unique characters
def unique_char(string):
letters = []
for i in string:
if i in letters:
return "not all are unique!"
else:
letters.append(i)
return "You have a unique string!"
#print ... |
from selenium import webdriver
#Need to manually install selenium
#To open Firefox, download geckodriver: https://github.com/mozilla/geckodriver/releases
#To open Chrome, download chromedriver (please pay attention to your Chrome version number and download the same version number for chromedriver): https://sites.go... |
#kode karyawan
kode = input("Masukkan kode karyawan : ")
#nama karyawan
nama = input("Masukkan nama karyawan : ")
#golongan
gol = input("Masukkan golongan : ")
if (gol == "A") or (gol == "a"):
gaji_pokok = 10000000
potongan = 2.5
elif (gol == "B") or (gol == "b"):
gaji_pokok = 8500000
potongan ... |
#Indo
indo = float(input("Masukkan nilai Bhs Indonesia : "))
#Ipa
ipa = float(input("Masukkan nilai IPA : "))
#Mat
mat = float(input("Masukkan nilai Matematika : "))
if (indo > 59) and (ipa > 59) and (mat > 70):
print("Status Kelulusan : LULUS")
else:
print("Status Kelulusan ... |
print('----------------------------------')
print(' Harga Buah ')
print('----------------------------------')
print({'apel' : 5000, 'jeruk' : 8500,
'mangga' : 7800, 'duku' : 6500})
hargabuah = {'apel' : 5000, 'jeruk' : 8500,
'mangga' : 7800, 'duku' : 6500}
maks = max(hargabuah['... |
import random
# komputer memilih angka secara acak dari 1 s.d 100
angka = random.randint(1,100)
print('Hai, nama saya Destri, saya telah memilih sebuah bilangan bulat secara acak antara 0 s/d 100. Silakan tebak ya!!!')
teks_petunjuk = 'Tebakan Anda : '
score = 100
score_min = 0
tebakan = False
nomor_tebakan = 0
while... |
#kode karyawan
kode = input("Masukkan kode karyawan : ")
#nama karyawan
nama = input("Masukkan nama karyawan : ")
#golongan
gol = input("Masukkan golongan : ")
if (gol == "A") or (gol == "a"):
gaji_pokok = 10000000
potongan = 2.5
tunjangan = gaji_p... |
def sum(*myData):
# init values
sum = 0
i = 0
# menjumlahkan semua data dalam myData
for data in myData:
sum += data
i +=1
# hitung jumlah
jumlah = sum
print('Jumlah: ',jumlah)
def average(*myData):
# init values
sum = 0
i = 0
# menjumlahkan semua data dal... |
import numpy as np
from matplotlib import pyplot as plt
data = np.random.binomial(1, 0.25, (100000, 1000))
epsilon = [0.5, 0.25, 0.1, 0.01, 0.001]
tosses = np.arange(1, 1001)
def plot_means():
for i in range(5):
plt.plot(tosses, np.cumsum(data[i]) / tosses)
plt.xlabel("Number of coins toss... |
"""
Simple implementation of (Fisher's) Linear Discriminant Analysis.
Thanks to: https://www.python-course.eu/linear_discriminant_analysis.php
The L. D. Matrix is a transformation matrix which best separates
the instances of different classes in data projection.
"""
import sklearn.base
import numpy as np
import scipy.... |
# -*- coding: utf-8 -*-
"""
Created on Tue June 11 10:56:03 2019
@author: Paul
"""
import numpy as np
def p(prices_historical=None, demand_historical=None, information_dump=None):
"""
this pricing algorithm returns a random price for the first three time periods
and then returns a weighted moving average... |
'''
Created on Aug 30, 2018
@author: Manikandan.R
'''
print ('Running Fibonacci')
a, b = 0, 1
while a < 10:
print(a, end=',')
a, b = b, a + b
print ('Handling Strings')
alphas = "abcdefghijklmnopqrstuvwxyz"
index = len(alphas) // 2
alpha1 = alphas[: index]
alpha2 = alphas[index :]
print ('alphas: ' + alphas)
pri... |
def factorial(x):
if (x < 2):
return 1
else:
return (x * (factorial(x-1)))
|
#Program porównujący ilość pizzy pomiędzy trzema pizzami z reztauracji
#Znajdź restaurację i za pomocą wbudowanej biblioteki
#Dane nazwa_restauracji, nazwa_pizzy, 3xrozmiar_pizzy, 3xcena_pizzy
import sys
import math
wyniki = sys.argv
def printing_pizza():
pizza1 = []
pizza2 = []
pizza3 = []
pizza1.ap... |
from datetime import date,datetime
import traceback
from pathlib import Path
def convert_date_to_excel_number(datevalue):
""" Convert datetime value into numeric value
:param datevalue: python datetime value.
:type datevalue: date.
:returns: int -- Number equivalent to datetime.
>>> ... |
class A(object):
class_var = 3.14
def __init__(self):
self.instance_var = 6.28
#
#
if __name__ == '__main__':
print('\nClass variable can be accessed thru class itself or an instance. However instance variable can be only accessed thru an instance:')
print(A.class_var)
print(A().class... |
x = 1
def fun1(x):
print('id(x):{} at the top of func1'.format(id(x)))
x = 2
print('id(x):{}, id(2):{} after the assignment'.format(id(x), id(2)))
#
print('####### fun1 #######')
fun1(x)
print(x) # 1
a = []
def fun2(a):
print('id(a):{} at the top of func2'.format(id(a)))
a.append(1)
pri... |
def buy_nug_calc(num,min=0,twinty=0,nine=0,six=0):
if min==20:
twinty = twinty+1
if min==9:
nine = nine+1
if min==6:
six = six+1
if num==0:
print("="*49)
print('|\tSix = '+str(six)+' Nine = '+str(nine)+" Twinty = "+str(twinty)+"\t\t|")
# print("="*50)
return True
elif num<0:
return False
else:
r... |
"""potential_dates = [{"name": "Julia", "gender": "female", "age": 29,
"hobbies": ["jogging", "music"], "city": "Hamburg"},
{"name": "Sasha", "gender": "male", "age": 18,
"hobbies": ["rock music", "art"], "city": "Berlin"},
{"name": "Maria", ... |
x=5
x=input("Enter value of x:")
y=10
y=input("Enter value of y:")
#create a temporary varibles and swap the values
temp=x
x=y
y=temp
print("The value of x after swapping:{}"format(x))
print("The value of y before swapping:{}"format(y)) |
# Python program to convert km to mts:
num11 = float(input("Enter a number in kms = "))
num12 = num11 * 0.62
print(num12)
|
# some_input = "0 2 7 0"
some_input = "2 8 8 5 4 2 3 1 5 5 1 2 15 13 5 14"
known_states = set()
state_idx = {}
def find_max(memory):
"""
:param memory: the list
:return: the index of the first maximum value
"""
import operator
index, value = max(enumerate(memory), key=operator.itemgetter(1... |
# Days In Row!
#
# This program takes as input a start day, month, and year. Then, it calculates
# the number of days total from 0 to the start date, and subtracts that number
# from the total days from 0 to the end date. It adds "1" to this to show how
# many days in a row, and it return an integer of the days in a ro... |
__author__ = "Niketan Rane"
from collections import deque
class Queue:
def __init__(self, max_size=10**7):
self.queue = deque()
self.front = -1
def push(self, item):
self.queue.append(item)
def pop(self):
return self.queue.popleft()
def peek(self):
if self.q... |
'''Quarta aula como criar interações entre o computador e o usuário,
vendo o funcionamento das funções print() e input(), diretamente
usando Variáveis.'''
#No Python todos os comandos são considerados funções e todas as
# funções tem parenteses ().2018
print('Olá mundo')# mostra o texto dentro de aspas
print (7+4) ... |
#Exercício Python 031: Desenvolva um programa que pergunte a distância de uma
#viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens
#de até 200Km e R$0,45 parta viagens mais longas.
distancia = float(input('\033[7;30;45mDe quantos Km éa distancia da sua viajem\033[m'))
print('***'*20)
print('... |
'''Faça um programa que leia uma frase pelo teclado e mostre quantas vezes
aparece a letra "A", em que posição ela aparece a
primeira vez e em que posição ela aparece a última vez.'''
frase = str (input('escreva uma frase')).upper() .strip() #neste caso foi
# possivel usar o upper na 'str e o strip para eliminar espaç... |
'''Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e
peça para o usuário tentar descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.'''
from random import randint
from time import sleep
computador = randint(0,5) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.