text stringlengths 37 1.41M |
|---|
"""Module for making player choices for game simulations."""
from __future__ import annotations
import logging
import cashflowsim.player as cfs_player
import cashflowsim.strategy as cfs_strategy
import cashflowsim.assets as cfs_assets
import cashflowsim.loans as cfs_loans
log: logging.Logger = logging.getLogger(__nam... |
"""Functions related to rolling a die."""
import random
def roll_die(strategy="Manual", no_of_dice=1, verbose=False):
"""Roll a die."""
if strategy == "Manual":
verbose = True
if no_of_dice == 1:
input("Hit 'Enter' to roll die ")
else:
input("Hit 'Enter' to roll... |
def string_reverser(our_string):
"""
Reverse the input string
Args:
our_string(string): String to be reversed
Returns:
string: The reversed string
"""
# TODO: Write your solution here
string = "" # O(1)
for i in range(len(our_string)): # O(n)
string += our_strin... |
# sıralama
def bubbleSort(array):
for j in range(len(array)):
for i in range(len(array)-1):
if array[i+1] < array[i]:
temp = array[i]
array[i] = array[i+1]
array[i+1] = temp
result = []
for i in range(len(array)):
result.append(a... |
from collections import defaultdict
class Pmf(defaultdict):
def __init__(self, prob_dict):
defaultdict.__init__(self, int, prob_dict)
if not self.is_a_probability():
print "ERROR, NOT A PROBABILITY"
def is_a_probability(self, tol = 0.001):
total_p = reduce(lambda x, v: x ... |
MIN_LENGTH = 1
MAX_LENGTH = 140
def is_valid_tweet(tweet):
""" (str) -> bool
Return True if and only if tweet is no less than 1 and no more
than 140 characters long.
>>> is_valid_tweet('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in th... |
from game_view import *
from generic_game_state import *
import random
import math
import time
class Player:
""" """
def __init__(self):
""" (Player) -> NoneType
Initialize a blank player to be overwritten once a game has been
started, unless the game
>>> p = Player()... |
MIN_LENGTH = 1
MAX_LENGTH = 140
def is_valid_tweet(tweet):
""" (str) -> bool
Return True if and only if tweet is no less than 1 and no more
than 140 characters long.
>>> is_valid_tweet('To me programming is more than an important ' \
+ 'practical art. It is also a gigantic undertaking in th... |
def check_password(passwd):
""" (str) -> bool
A strong password has a length greater than or equal to 6, contains at
least one lowercase letter, at least one uppercase letter, and at least
one digit. Return True iff passwd is considered strong.
>>> check_password('I<3csc108')
True
"""
... |
def swap_name(name_list):
""" (list of str) -> NoneType
name_list contains a single person's name. Modify name_list so that the first name and last name are swapped.
>>> name = ['John', 'Smith']
>>> swap_name(name)
>>> name
['Smith', 'John']
>>> name = ['John', 'A... |
def count_uppercase(s):
""" (str) -> int
Return the number of uppercase letters in s.
>>> count_uppercase('Computer Science')
"""
num_upper = 0
for ch in s:
if ch.isupper():
num_upper = num_upper + 1
return num_upper
|
def only_evens(lst):
""" (list of list of int) -> list of list of int
Return a list of the lists in lst that contain only even integers.
>>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
[[4, 0, 6], [2]]
"""
even_lists = []
for sublist in lst:
result =... |
def format_name(last, first):
""" (str, str) -> str
Print first and last name given.
>>> format_name('steingrimsson', 'axel')
'steingrimsson, axel'
"""
return last + ', ' + first
def to_listing(last, first, phone):
""" (str, str, str) -> str
return a string contains a listing
... |
def build_placements(shoes):
""" (list of str) -> dict of {str: list of int}
>>> build_placements(['Saucony', 'Asics', 'Asics', 'NB', 'Saucony', 'Nike', 'Asics', 'Adidas', 'Saucony', 'Asics'])
{'Saucony': [1, 5, 9], 'NB': [4], 'Adidas': [8], 'Asics': [2, 3, 7, 10], 'Nike': [6]}
"""
r... |
def reverse_lookup_dictionary(phone_num, phone_to_name):
""" (str, dict of {str: str}) -> str
This function receives a phone number phone_num, and a dictionary
phone_to_name in which each key is a phone number and each value
is the name associated with that phone number.
Return the name associate... |
#! /usr/bin/python3
# 程序的入口
# 每一次启动名片管理系统都通过main这个文件启动
import card_tool
while True: # 进行一个无限循环,由用户决定什么时候退出循环
# 显示功能菜单
card_tool.show_menu()
# 用户输入
action_str = input("请选择希望执行的操作: ")
print("您选择的操作是【%s】"%action_str)
# 1,2,3针对名片的操作
if action_str in ["1", "2", "3"]:
# 输入为1进行新增名片的操作... |
#ЗАДАЧА Begin17◦
#a = int(input("ведите координату первой точки:"))
#b = int(input("ведите координату второй точки:"))
#c = int(input("ведите координату третьей точки:"))
#x = abs(c - a)
#y = abs(c - b)
#z = x + y
#print("длинна отрезка ac:" + str(x) + "длинна отрезка bc:" + str(y) + "сумма отрезков равна :" + str(z) )... |
# functions
def print_separator():
print('--------')
print('here')
# intructions
print("Hello World")
# variables
name = 'Wes'
age = 31
total = 99.78
found = False
print(name)
print(age)
print(total)
print(age + 13)
print_separator()
# if statements
user_age = 79
if(user_age ... |
#El enunciado es confuso en cuanto a lo que pasarìa si introduzco 30, por lo que usarè if X else X if X -- Sin usar if elif
num = int(input("Ingrese un numero: "))
if num % 2 == 0:
print("Es Multiplo de 2")
else:
print("No es multiplo de 2")
if num % 3 == 0:
print("Es Multiplo de 3")
else:
print("No es... |
def calcularValorPalabra(cadena):
total = 0
for letra in cadena:
if letra in diccionario[1]:
total = total + 1
elif letra in diccionario[2]:
total = total + 2
elif letra in diccionario[3]:
total = total + 3
elif letra in diccionario[4]:
... |
r=float(input("enter a value of radius:"))
a = 3.14*r*r
print(a) |
"""Demonstrate `for`."""
from typing import List
def test_for_string() -> None:
"""Iterate over a string."""
alpha = "ababa"
num_of_as = 0
for letter in alpha:
if letter == "a":
num_of_as += 1
assert num_of_as == 3
def test_for_list() -> None:
"""Iterate over a list.""... |
"""Demonstrate default arguments and keyword arguments."""
from typing import List, Optional, Union, Tuple
import pytest
def test_default_args() -> None:
"""Default arguments."""
def default_args(value: Union[int, str], multiplier: int = 2) -> Union[int, str]:
"""If `multiplier` is not provided, th... |
"""Manual string formatting."""
from typing import List
def test_rjust() -> None:
"""Right-justifying a string."""
squares: List[str] = [
str(x).rjust(2) + " " + str(x * x).rjust(3) for x in range(1, 5)
]
assert squares[0] == " 1 1"
assert squares[1] == " 2 4"
assert squares[2] ==... |
"""Looping Techniques."""
import math
from typing import Dict, List, Tuple
def test_dict_items() -> None:
"""Looping through a dictionary using `items()`."""
knights_dict: Dict[str, str] = {"gallahad": "pure", "robin": "brave"}
knights: List[str] = [
name.title() + " the " + value.title() for na... |
"""Output formatting using `reprlib`."""
import reprlib
def test_reprlib_string() -> None:
"""Limit the number of characters in a string representation."""
test_str = "thequickbrownfoxjumpsoverthelazydog"
assert (reprlib_str := reprlib.repr(test_str)) == "'thequickbrow...verthelazydog'"
assert len(r... |
from pynput.keyboard import Key, Listener
from threading import Thread
class KeyboardListener:
def on_enter(self,fn):
'''
fn will be called each time the enter key is pressed.
'''
#start a thread to listen to the enter key event.
#This is to prevent this method from blocki... |
def rotate(text, key):
chars = "abcdefghijklmnopqrstuvwxyz"
newchars = chars[key:] + chars[:key]
trans = str.maketrans(chars + chars.upper(), newchars + newchars.upper())
return text.translate(trans)
|
import random
import time
def binarysearch(no,arr,left,right):
if left<=right:
mid = (left+right)/2
if no >arr[mid] and no<arr[mid+1]:
return mid+1
elif no<arr[mid]:
return binarysearch(no,arr,left,mid-1)
elif no>arr[mid]:
return binarysearch(no,... |
#------code by @Hrishikesh Waikar@ -----#
def decimaltobinary(no):
#returns the binary representation of the decimal no in the form of a list
b=[] #b will hold the binary no as it forms
print('in decimal to binary , no'+str(no))
while no!=0:
remainder = no%2
#print remainder
b.... |
import streamlit as st
from api_call import api_call
import pandas as pd
import numpy as np
import plotly.express as px
def run():
st.header("Check the emotion in the Text.")
selected_model = st.selectbox(
"Algorithm you would like to use?", ("Logistic Regression", "Naive Bayes")
)
input_te... |
print ("hello")
print ("saya sedang belajar python")
a = 8
b = 6
print ("variable a=",a)
print ("variable b=",b)
print ("hasil penjumblahan a+b=",a+b)
a=input ("masukan nilai a:")
b=input ("masukan nilai b:")
print ("variable a=",a)
print ("variable b=",b)
print ("hasil penggabungan {1}&{0}=%d".format(a,b) %(a+b))
#... |
import math
dp = "%.2f"
def quadratic():
a = float(input("Please enter coefficient a: "))
b = float(input("Please enter coefficient b: "))
c = float(input("Please enter coefficient c: "))
root = math.sqrt((b * b) - 4 * a * c)
x1 = (-b + root) / (2 * a)
x2 = (-b - root) / (2 * a)
print()
print("The sol... |
# team = 'New England Patriots'
# # letter = team[-2]
# # # print(letter)
# # index = 0
# # while index < len(team):
# # letter = team[index]
# # print(letter)
# # index = index + 1
# # prefixes = 'JKLMNOPQ'
# # suffix = 'ack'
# # for letter in prefixes:
# # if letter == 'O' or letter == 'Q':
# # ... |
# age = 10
# if age >= 18:
# print('Your age is', age)
# print('adult')
# else:
# print('no')
# BMI Categories:
# Underweight = <18.5
# Normal weight = 18.5–24.9
# Overweight = 25–29.9
# Obesity = BMI of 30 or greater
# weight = input('Please enter your weight: ')
# height = input('Please enter your hei... |
class P:
def __init__(self, first, last):
self.fn = first
self.ln = last
def name(self):
return self.fn + ' ' + self.ln
class Employee(P):
def __init__(self, first, last, staffnum):
# super().__init__(first, last)
P.__init__(self, first, last)
sel... |
"""
to create a class attribute, which we call "counter" in our example
to increment this attribute by 1 every time a new instance will be create
to decrement the attribute by 1 every time an instance will be destroyed
"""
class Count:
"""
Create a class in which it will be used to count the number of instan... |
"""
Syntax: property(fget, fset, fdel, doc)
Parameters:
fget() – used to get the value of attribute
fset() – used to set the value of atrribute
fdel() – used to delete the attribute value
doc() – string that contains the documentation (docstring) for the attribute
Return: Returns a property attribute from the given g... |
# demonstration of the difference of zip() method within p2 and p3
dishes = ["pizza", "sauerkraut", "paella", "hamburger"]
countries = ["Italy", "Germany", "Spain", "USA"]
country_specialities_zip = zip(dishes,countries)
print(list(country_specialities_zip))
#country_specialities_list = list(country_specialities_zip)
... |
"""
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
"""
class MyDecorator:
def __init__(self, f... |
# Example of exception in python
# In short, the exception block in python is consist of a try except pair corresponding to language like Java in which it uses try catch block
while True:
try:
n = input("Please enter an integer\n")
n = int(n)
break
except ValueError:
print("No v... |
# lambda
sum = lambda x, y: x+y
print(sum(1,1))
# map
# map(func, seq) - Apply each of the elements of seq on func
seq = [1,2,3,4,3,3,3,3,3,3,]
f = list(map(lambda x: (float(9)/5)*x + 32, seq)) # convert celsius to fahrenheit
print(f)
# map can also be applied on more than one list object
a = [1,1,1,]
b = [2,2,2,]
... |
"""
* Class methods are not bound to the instances.
* Class methods are bound to the a class.
"""
class Robot:
__counter = 0
def __init__(self):
type(self).__counter += 1
# Class methods are bound to the class itself
@classmethod
def robot_instances(cls):
return cls, Robot.... |
from math import sqrt
#for a in range(1,1000):
# for b in range(a+1,1000):
# c = (a**2 + b**2)**0.5
# if a + b + c == 1000:
# print(a, b, c, a*b*c)
for a in range(1,500):
for b in range(a+1, 500):
c = (a**2 + b**2)**0.5
if a + b + c == 1000:
print(a,b,c, a*b*c) |
# -*- coding: utf-8 -*-
import sqlite3
def read_words(database_name):
words = []
conn = sqlite3.connect(database_name)
sql = (
'SELECT word, usage from words '
'LEFT JOIN LOOKUPS ON words.id = LOOKUPS.word_key WHERE words.lang="en" GROUP BY word;'
)
for row in conn.execute(sql):
... |
def solution(A , K):
# write your code in Python 3.6
# 利用array相加做出rotation,A[-1]代表array的最後一個,依此類推。
# more detail please check it out at https://openhome.cc/Gossip/CodeData/PythonTutorial/NumericString.html .
if len(A) == 0:
return A
K = K % len(A)
return A[-K:] + A[:-K]
# testcase 1... |
import tensorflow as tf
import numpy as np
import utils
def lstm(nlstm=128, layer_norm=False):
"""
Builds LSTM (Long-Short Term Memory) network to be used in a policy.
Note that the resulting function returns not only the output of the LSTM
(i.e. hidden state of lstm for each step in the sequence), bu... |
def main():
while True:
print("Welcome to a sloppy script that calculates interest for you based on parameters you give!")
c = getC()
t = getT()
r = getR()
comp = getComp()
mode = getMode()
if mode == False:
output = calculate(c , t , r , comp)
... |
"""
==================
Rasterization Demo
==================
Rasterization is a method where an image described in a vector graphics
format is being converted into a raster image (pixels).
Individual artists can be rasterized for saving to a vector backend
such as PDF, SVG, or PS as embedded images. This can be usef... |
nameList = []
print "Enter 5 names (press the Enter key after each name):"
for i in range(5):
name = raw_input()
nameList.append(name)
print "The names are:", nameList
print "Replace one name. Which one? (1-5):",
replace = int(raw_input())
new = raw_input("New name: ")
nameList[replace - 1] = new
print "The nam... |
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> friends = []
>>> friends.append('David')
>>> friends.append('Mary')
>>>
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> print letters[0]
a
>>> print letters[3]
d
>>> print... |
length = float(raw_input ('length of the room in feet: '))
width = float(raw_input ('width of the room in feet: '))
cost_per_yard = float(raw_input ('cost per square yard: '))
area_feet = length * width
area_yards = area_feet / 9.0
total_cost = area_yards * cost_per_yard
print 'The area is', area_feet, 'square feet.'
p... |
user_dictionary = {}
while 1:
command = raw_input("'a' to add word, 'l' to lookup a word, 'q' to quit ")
if command == "a":
word = raw_input("Type the word: ")
definition = raw_input("Type the definition: ")
user_dictionary[word] = definition
print "Word added!"
elif comman... |
__author__ = 'pallavipriya'
def mergeSort( arr, start, end ):
if end-start<=0:
return None
mid = (start+end)/2
mergeSort(arr, start, mid)
mergeSort(arr, mid+1, end)
merge(arr, start, mid, end)
def merge( arr, start, mid, end ):
tarr = []
i, j = start, mid+1
while i<=mid and j<=... |
__author__ = 'pallavipriya'
class linkedList():
def __init__(self,value=None,next=None):
self.value = value
self.next = next
def getValue(self):
return self.value
def getNext(self):
return self.next
def setNext(self,next):
self.next = next
def setValue(s... |
__author__ = 'pallavipriya'
def reverse(arr):
length = len(arr)
for itr in range(int(length/2)):
(arr[itr],arr[length-1-itr]) = (arr[length-1-itr],arr[itr])
arr = [1,4,2,8,5]
reverse(arr)
print (arr) |
__author__ = 'pallavipriya'
"""How to check if two Strings are anagrams of each other? """
def anagrams(istring,bstring):
astr = sorted((istring.lower()))
bstr = sorted(bstring.lower())
if len(astr) != len(bstr):
return ("string are not anagram of each other")
else:
for i,j in zip(a... |
__author__ = 'pallavipriya'
def binarySearchRecursion(value,L):
if len(L) <1:
print ("Not found")
else:
mid = len(L) / 2
if value < L[mid]:
binarySearchRecursion(value,L[:mid])
elif value > L[mid]:
binarySearchRecursion(value,L[mid+1:])
elif value... |
#!/bin/python
import sys
def staircase(n):
spaces = n-1
while( spaces >= 0 ):
print ' ' * spaces + '#' * (n-spaces)
spaces -= 1
if __name__ == "__main__":
n = int(raw_input().strip())
staircase(n) |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../to... |
from abc import ABC, abstractmethod
class Formula(ABC):
"""
Return the result of computing the formula.
:param Dict[str, float] Network state: key: species name, value: concentration
:returns float of result
"""
@abstractmethod
def compute(self, state):
pass
"""
Change va... |
'''
This file implements the collaborative filtering mechanism.
The feature upweights the relevant movies of the previous user that is most similar to the current user
and downweights the irrelevant movies of the previous user that is most similar to the current user
'''
import numpy as np
import math
'''
Find the euc... |
#
# Given a list of numbers, L, find a number, x, that
# minimizes the sum of the absolute value of the difference
# between each element in L and x: SUM_{i=0}^{n-1} |L[i] - x|
#
# Your code should run in Theta(n) time
#
import random as rand
from math import ceil
# Write partition to return a new array with
# all v... |
#
# Given a list of numbers, L, find a number, x, that
# minimizes the sum of the square of the difference
# between each element in L and x: SUM_{i=0}^{n-1} (L[i] - x)^2
#
# Your code should run in Theta(n) time
#
def minimize_square(L):
# f(x) = sum(to n) (L[i] - x)**2
# g(x) = x**2, h(x) = L[i] - x
# g... |
# Implement Dijkstra's algorithm using a heap instead of linear scan to find smallest distance from source node
# given these functions
def parent(i):
return (i - 1) / 2
def left_child(i):
return 2 * i + 1
def right_child(i):
return 2 * i + 2
def is_leaf(L, i):
return (left_child(i) >= len(L)) a... |
import smtplib
import tkinter as tk
from tkinter import BOTH, END, LEFT
root = tk.Tk()
canvas = tk.Canvas(root, height=700, width=700, bg="#263D42")
canvas.pack()
frame = tk.Frame(root, bg="White")
frame.place(relwidth = 0.8, relheight =0.8, relx = 0.1, rely = 0.1)
whom = ""
body = ""
subject = ""
def emailSend():
... |
#!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
import cryptocompare
def getCoinsList() :
liste = []
listOfCoins = cryptocompare.get_coin_list(format=True)
for coin in listOfCoins:
liste.append(coin)
print(liste)
def getCoinPrice(coin):
if (cryptocompare.get_price(coin)):
price = ... |
import sys
print("Olá " + input("Digite seu nome:\n"))
while True :
resposta = input("Fala comigo bebê \n")
print(input(resposta +'?\n'))
|
main_dict={}
def insert_item(item):
if item in main_dict:
main_dict[item] += 1
else:
main_dict[item] = 1
#Driver code
insert_item('Key1')
insert_item('Key2')
insert_item('Key2')
insert_item('Key3')
insert_item('Key1')
print(main_dict)
print (len(main_dict))
|
class Book:
'''Has the following properties:
-id
-title
-description
-author
'''
def __init__(self, id, title, description, author):
self._id = id
self._title = title
self._description = description
self._author = author
def __repr__(self... |
from math import sqrt
def is_prime(n):
"""this function checks if a number is prime or not.
If it is prime, it will show True and False otherwise"""
if n == 2:
return True
if n < 2 or n % 2 == 0:
return False
for i in range(3, int(sqrt(n)) + 1, 2):
if n % i == 0:
... |
import sys
import controler
from copy import deepcopy
def read_command():
"""This function splits up the command"""
cmd = input("Command: ")
if cmd.find(" ") == -1:
command = cmd
params=""
else:
command = cmd[0:cmd.find(" ")]
params = cmd[cmd.find(" "):]
params... |
list1 = [1,2,3,4,5]
list2 = [1,2,3,4,5]
list3 = [1,2,3,4,5]
list4 = [1,2,3,4,5]
def proc(mylist):
global list1
list1 = mylist
#mylist = list1
print list1
#print mylist
list1 = list1 + [6,7]
mylist = mylist + [6,7]
def proc2(mylist):
mylist.append(6)
mylist.append(7)
def proc3(mylist):
my... |
# player_name = "Manuel"
# player_attack = 10
# player_heal = 16
# health = 100
#player = ["Manuel",10,16,100]
from random import randint
game_running = True
game_results = []
# print(player['name'])
# print(monster['health'])
def cal_monster_attack(attack_min,attack_max):
return randint(attack_min,attack_max)
... |
M,N=map(int,input().split())
"""
def mymethod(N):
primes={2:True,3:True}
for i in range(2,int(sqrt(N))+1):
if primes.get(i,True)==False:
continue
#while i*j<N:
for t in range(i*i,N+1,i):
#if i*j not in primes:
primes[t]=False
#j+... |
def maxChar(word):
maxChar = ''
for char in word:
if maxChar < char:
maxChar = char
return maxChar
word = input('Gebe ein wort ein: ')
char = maxChar(word)
print(char) |
def reverse(normalString):
reveseString = ''
for c in normalString:
reveseString = c + reveseString
return reveseString
normalString = input('Geben sie ein wort ein: ')
print(reverse(normalString))
|
#python3.8
import json, requests, sys, time, math
APPID = '<--------------------->'
print("API key stored")
print()
"""
#compute location from command line arguments
if len(sys.argv) < 2:
print('Usage: getOpenWeather.py city_name, 2-letter_country_code')
sys.exit()
"""
#location = ' '.join(sys.argv[1:])
city = i... |
import time
class Board(object):
def __init__(self, cells):
self.cells = cells
def next_step(self):
next_state = set([])
interesting_cells = set([])
for cell in self.cells:
interesting_cells.add(cell)
interesting_cells |= self.neighbours(cell)
... |
import time
import pandas as pd
import pants
# function to read the excel with the distance matrix
def parse_input(path):
distances = pd.read_excel(path, index_col=0)
return distances
dists = parse_input('Lab10DistancesMatrix.xlsx')
# function to get the distance between two points
def getDist(a, b):
... |
def bin_search(arr, ele):
start, end = 0, len(arr)
while start <= end:
# print(arr[start:end])
mid = (start + end) // 2
if arr[mid] == ele:
return mid + 1
else:
if arr[mid] < ele:
start = mid + 1
elif arr[mid] > ele:
... |
def rotation_generator(arr, x):
print('rotated array : ', arr[x:] + arr[:x])
return arr[x:] + arr[:x]
def rotation_point_finder(arr):
low, high = 0, len(arr) - 1
while low <= high:
print(arr[low:high])
if arr[low] <= arr[high]:
return low
mid = (low + high) // 2
... |
import math as m
class Heap:
def __init__(self):
self.data=[]
def addNode(self,value):
self.data.append(value)
index=len(self.data)-1
while index!=0:
if self.data[index] < self.data[m.floor((index-1)//2)]:
self.data[index] , self.data[m.floor((index-1)... |
# gesture control python program for controlling certain functions in windows pc
# Code by Harsh Namdev
# add pyautogui library for programmatically controlling the mouse and keyboard.
import pyautogui
import time
def action_func(incoming_data):
# print the incoming data
print('handy', incoming_data)
... |
# Dijkstra's algorithm in python
def dijkstra(graph,start,end):
D={}# Final distances dict
P={}# Predecessor dict
# Fill the dicts with default values
for node in graph.keys():
D[node] = -1 # Vertices are unreachable
P[node] = "" # Vertices have no predecessors
D[start] = 0 # The start vertex needs no more
u... |
# !/usr/bin/env python
# -*- coding=utf-8 -*-
# Summary: HASH表(处理冲突的方法:开放寻址法h(k,i)=(h'(k)+i))mod m );查找的时间为O(1)
# Author: HuiHui
# Date: 2019-04-01
# Reference: 网易公开课-算法导论
# https://www.cnblogs.com/dairuiquan/p/10509416.html
#################################
#创建与内建类型list相似的数组,其初始元素均为None
class A... |
# !/usr/bin/env python
# -*- coding=utf-8 -*-
# Summary: Dijkstra算法(解决带权重的有向图单源最短路径问题;要求权重非负无环;思路:贪心策略,不断将能最短到达的节点u加入集合S,并松弛从u出发的边)(时间O(n2))
# Author: HuiHui
# Date: 2019-09-20
# Reference:
#################################
# graph:邻接矩阵存储带权有向图(利用字典构造二维散列表,values为权重);s:源点(节点名)
# cost:存储源点到各点的最短路径估计(散列表);path... |
#!/usr/bin/python3
"""Save all info to a JSON file"""
import json
import requests
def save_all_to_json():
"""
Save info to a JSON file. That info? Still employee record.
"""
users_and_tasks = {}
users_json = requests.get('https://jsonplaceholder.typicode.com/users')\
.json()
todos_j... |
# Função para ler uma String passada pelo usuário
def digite_mensagem(mensagem):
return input(mensagem)
# Função para ler um número de ponto flutuante
def digite_numero(numero):
return float(input(numero)) |
import csv
with open("data.csv", newline='') as f :
reader = csv.reader(f)
file_data = list(reader)
print(file_data)
data = file_data[0]
print(data)
def mean(data):
n = len(data)
total = 0
for i in data:
total += int(i)
mean = total/n
return mean
squared_list = ... |
def string_length(i):
if type(i) == int:
return "A number has no length"
elif type(i) == float:
return "This is a float, it has no length either"
else:
return len(i)
#i = input("Enter a string to see its length: ")
print(string_length(10.0))
|
class Position(object):
row_dict = {
1: 'A',
2: 'B',
3: 'C',
4: 'D',
5: 'E',
6: 'F',
7: 'G',
8: 'H'
}
def __init__(self, x, y):
if x < 0:
raise ValueError("Figure's row value must be greater than 0")
if x > 7:
... |
import numpy as np
import pandas as pd
dfPaises = pd.read_csv('paises.csv', delimiter=';')
# print(dfPaises['Region'])
oceania = dfPaises[dfPaises['Region'].str.contains("OCEANIA")]
# Exercicio 1
print("--- Paises da OCEANIA ---")
print(oceania['Country'])
print("--- Nº de Paises da OCEANIA ---")
print(oceania['Cou... |
"""
NP2 - C210
Código referente a Questão 1
"""
# Usado para plotar o gráfico no PyCharm
import matplotlib.pyplot as plt
import numpy as np
from skfuzzy import control as ctrl
# Antecedentes
nivelTanque = ctrl.Antecedent(np.arange(0,101,1), "nivel do tanque")
erroLeitura = ctrl.Antecedent(np.arange(0,101,1), ... |
'''
author: Camilo Hernández
This script takes an image file and converts it into pixelart based on the given initial parameters
file_name # this should point to the name of the image file (without the file extension)
file_format # this should be the type of file
new_file_appendix # this should be what is added to th... |
x = int(input())
if x % 2 == 0:
print ('even')
else:
print ('odd') |
#Sum of Digits of a Number
# 112 -> 1+1+2=4
number = int(input("Input a Number : "))
sum=0
temp = number
for i in range(len(str(number))):
rem = number %10
sum += rem**3
number = number//10
if (temp == sum):
print("Number is Armstrong")
else:
print("Number is Not Armstrong")
#check wether numbe... |
#Exception Handling
#Error
#-syntactical error
#-run time error
#-exception -> exception Handling
a = int(input("Enter number 1 :"))
b = int(input("Enter number 2 :"))
try:
#list1 = [1,2,3,4]
#print(list1[100])
p = a+b
print("sum=",p)
q = a-b
print("sub=",q)
r = a*b
print("mul=",r)
... |
list1 = [5,6,0,3,9,1]
for i in range(len(list1)):
for j in range(0,len(list1)-i-1):
if list1[j] > list1[j+1]:
list1[j],list1[j+1] = list1[j+1],list1[j]
print(list1)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Size(object):
"""Class Size
"""
# Attributes:
def __init__(self, width=0, height=0):
r"""
@Arguments:
- `args`:
- `kwargs`:
@Construct
Size()
Size(width=100, height=100)
"""
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.