text stringlengths 37 1.41M |
|---|
#!/usr/bin/python3
"""
inserts a line of text to a file,
"""
def append_after(filename="", search_string="", new_string=""):
"""
inserts a line of text to a file,
"""
text = ""
with open(filename, encoding='utf-8') as m_file:
for x in m_file:
text += x
if search_st... |
#!/usr/bin/python3
"""
Fuction to find a pick
"""
def find_peak(list_of_integers):
""" Function find_peak """
lenght = len(list_of_integers)
if lenght == 0:
return None
else:
return findPeak(list_of_integers, lenght, 0, lenght - 1)
def findPeak(arr, lenght, low, n):
""" Auxiliar ... |
#!/usr/bin/python3
"""
connect the mysql
"""
import sys
import MySQLdb
if __name__ == "__main__":
conn = MySQLdb.connect(host="localhost", port=3306, user=sys.argv[1],
passwd=sys.argv[2], db=sys.argv[3])
cur = conn.cursor()
q = """
SELECT cities.id, cities.name, states.name... |
from scipy import stats
import numpy as np
import pandas as pd
from statsmodels.stats.power import TTestIndPower, TTestPower
import seaborn as sns
import matplotlib.pyplot as plt
def normality_test(distribution, alpha : float, printout=True):
"""Wrapper function for testing whether the distribution of values
... |
# Library 사용
# PriorityQueue
# 최소 우선
from queue import PriorityQueue
que = PriorityQueue()
que.put((3, 'Apple'))
que.put((1, 'Banana'))
que.put((2, 'Cherry'))
print(que.get()[1]) # Banana
print(que.get()[1]) # Cherry
print(que.get()[1]) # Apple
# heapq
# 최소 우선
import heapq
h = []
heapq.heappush(h, (3, "Go to hom... |
#checks if two strings are the same regardless of case
#CNA 336 , Spring 2018
#Parker,pdswift@student.rtc.edu, Ian, theholyboots@gmail.com
String_A = input(str("Say Anything: "))
String_B = input(str("Say Anything again: "))
String_A = String_A.upper()
String_B = String_B.upper()
if String_B == Strin... |
#! /usr/bin/env python
# Minecraft api reference
# https://www.stuffaboutcode.com/p/minecraft-api-reference.html
# Get the collection of code that the minecraft people
# have given us that lets us talk to minecraft, the
# "library" or "module" provides lots of functions for
# manipulating the minecraft server.
#
# Pr... |
s=input()
list = s.rsplit(' ')
sum =0
for i in list:
sum += float(i)
print(sum) |
import pygame, os
from pygame.locals import *
class Ghosts(pygame.sprite.Sprite):
"""Create and manage the 4 Ghosts"""
def __init__(self, name):
"""Constructor for ghosts"""
"""Call the constructor of Sprite class"""
pygame.sprite.Sprite.__init__(self)
image_to_load = os.path.jo... |
#!/usr/bin/env python
#coding:utf-8
age = 23
count = 0
for i in range(10):
if count < 3:
a = int(input("Plz input num: "))
if a == age:
print("恭喜你,答对了!")
break
elif a > age:
print("猜大了")
else:
print("猜小了")
else:
b = input("太笨了,还继续玩吗?(yes or not):")
if b == "yes":
count = 0
continue
... |
#!/usr/bin/env python
import random
lottery = random.randint(0, 99)
guess = eval(input("Enter your lottery pick (two digits): "))
lottery_1 = lottery // 10
lottery_2 = lottery % 10
guess_1 = guess // 10
guess_2 = guess % 10
print("The lottery number is", lottery)
if guess == lottery:
print("Exact match: you... |
'''
L2 Loss Function
L2 loss or least square error function implemented in numpy
'''
def L2(yhat, y):
"""
Arguments:
yhat -- vector of size m (predicted labels)
y -- vector of size m (true labels)
Returns:
loss -- the value of the L2 loss function defined above
"""
# find the differ... |
import numpy as np
class Activation_ReLU:
def forward(self, inputs):
self.output = np.maximum(0, inputs)
''' Notice that it is equivalent to:
output = []
for i in inputs:
if i > 0:
output.append(i)
else:
output.append(0)
... |
# Question 1
from math import sqrt, ceil
def isprime(number):
if (number == 2) or (number == 3):
return True
if (number % 2 == 0) or (number % 3 == 0) or (number == 1):
return False
for counter in range(5, ceil(sqrt(number)), 6):
if ((number % counter) == 0) or ((number % (... |
import numpy as np
import pickle
class Parameters:
"""
This class holds all weights for all layers for a specific model
Features:
- Can append for the parameters dynamically
- Can access any parameter at any layer or neuron for fine tuning
Initialization:
- Initial... |
"""
You are given a 0-indexed integer array nums and an integer x.
Find the minimum absolute difference between two elements in the array that are at least x indices apart.
In other words, find two indices i and j such that abs(i - j) >= x and abs(nums[i] - nums[j]) is minimized.
Return an integer denoting the minim... |
"""Write code that will print out the anagrams (words that use the same
letters) from a paragraph of text."""
inputParagraph = input("Enter text for checking anagrams: ")
inputSorted = sorted(inputParagraph)
print("The Anagrams is ", ''.join(inputSorted)) |
"""Create a function, is_palindrome, to determine if a supplied word is
the same if the letters are reversed."""
inputWord = input("Enter any word to check Palindrome: ")
def is_palindrome(inputWord):
reversedWord = inputWord[::-1]
if inputWord == reversedWord:
return ("The given word is Palindrome... |
word = 'Kajak'
# word = Legovogel
word = word.lower()
reversed_word = word[::-1]
if reversed_word == word:
print('PALINDROM')
else:
print('kein Palindrom')
|
'''Polycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3.
He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he
considers a positive integer n interesting if its sum of digits is divisible ... |
'''A frog is currently at the point 0 on a coordinate axis Ox. It jumps by the following algorithm: the first jump is a
units to the right, the second jump is b units to the left, the third jump is a units to the right, the fourth jump is
b units to the left, and so on.
Formally:
if the frog has jumped an even numbe... |
'''One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length ... |
'''Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has n instruments, it takes a i days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments.
Amr asked for your h... |
'''Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page ai (ai≥i).
Ivan wants to read the whole book. Each day, he reads the first page he didn't... |
def palindrome():
n = int(input("Enter the number"))
if n//10 >= (n%10):
print((n//10)*11)
else:
print(((n // 10)+1) * 11)
palindrome() |
'''During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the
children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for
standing in front of the girls in the queue and they started letting the girls move forward e... |
#its an adventure game with zombies.
#Option A, leads to scenario A with options of its own.
from random import randint
from sys import exit
class Player(object):
def __init__(self):
#player carries fatigue based on choices made, changes outcome of other choices
#or presents new choices all together. Haven'... |
sehirler = ['Adana','Ankara','Ardahan','Amasya','Edirne']
# dizi icerisinde yer alan elemanlarin ismi icerisinde 'm' harfi bulunanlarin yazdirilmasi
for sehir in sehirler:
if 'm' in sehir:
print(sehir)
else:
print(sehir, 'icerisinde \'m\' harfi gecmemektedir.') |
#ornek: disaridan girilen kelimenin uzunluk degeri 8 karakter veya daha uzun bir karakter ise onaylandi, degil ise daha uzun bir sifre giriniz.
word = input('lutfen bir kelime giriniz:')#len(input()) da olur
if len(word) >= 8:
print('sifreniz onaylandi')
print("Sifreniz:",word)
else:
print('Daha uzu... |
def setup():
size(400, 400)
set_scene()
angle = 0;
radius = 0;
center_x = 200;
center_y = 200;
def set_scene():
background(145, 112, 255)
stroke(1, 64, 3)
def draw_spiraling_circle():
global angle, radius, center_x, center_y
x = cos(angle) * radius
y = sin(angle) * radius... |
firstClick = True
xPoint = 0
yPoint = 0
def saveMousePosition():
xPoint = mouseX
yPoint = mouseY
def mouseClicked():
global firstClick
if firstClick == True:
fill(random(0, 255), random(0, 255), random(0, 255))
saveMousePosition()
firstClick = False
else:
first... |
p1Score = 0
p2Score = 0
Paddle1 = {
"x": 10,
"y": 373,
"height": 81,
"width": 17
}
Paddle2 = {
"x": 373,
"y": 373,
"height": 81,
"width": 17
}
Ball = {
"x": 200,
"y": 200,
"radius": 10,
"xVel": random(-6, 6),
"yVel": random(-3, 3)
}
def movingPaddle1 () :
fill(18, 6, 18)
... |
area = 0
radius = 0
areaCanv = 0
def drawCircle ():
global radius, area, areaCanv
background(113, 76, 191)
textSize(50)
text("Area of a Circle", 26, 47)
ellipse(200, 200, abs(200 - mouseX), abs(200 - mouseX))
def calculateCircleArea ():
global radius, area, areaCanv
radius = abs(200 - mouseX)
... |
start = millis()
score = 0
counter = 0
def displayGame():
background(0, 252, 0)
textSize(16)
text("Click and hold when the number is a multiple of 3", 50, 50)
textSize(20)
text("Score: " + score, 165, 350)
textSize(90)
text(counter, 185, 200)
def countUp():
counter = round((millis() - ... |
def setup():
size(400, 400)
display_instructions()
def display_instructions():
fill(46, 46, 46)
text("click the screen and press a key to start", 92, 200)
prev_key = ""
def display_keycode():
vowels = {'a', 'e', 'i', 'o', 'u'}
if key in vowels:
background(108, 221, 187)
... |
area = 0
radius = 0
def drawCircle():
background(113, 76, 191)
textSize(50)
text("Area of a Circle", 26, 47)
ellipse(200, 200, abs(200 - mouseX), abs(200 - mouseX))
def calculateCircleArea():
radius = abs(200 - mouseX)
area = 3.14 * radius * radius
def printOutCalculations():
textSize(15)... |
def setup():
size(400, 400)
class ball:
def __init__(self):
self.x = 200
self.y = 200
self.z = 1
self.size = 50
self.xspeed = 2
self.yspeed = 4
self.zspeed = 0.5
myBall = ball()
def drawScene():
background(0)
stroke(255)
fill(0)
rect(40... |
def eratosthenes(limit):
# Create an array containing numbers from 1 to limit
primes = []
for i in range(2, limit):
primes.append(i)
# Loop through the numbers removing composites of the found primes
for y in primes:
for i in primes:
if i % y == 0:
if i !... |
from intcode_computer.program import Program
from intcode_computer.computer import Computer
if __name__ == '__main__':
# Read input
with open('inputs/input_day02.in') as file:
source_code = file.readline()
# Part 1: Restore and run program
program = Program(source_code)
program.resto... |
'''
############################################################################
AUTHOR: MAHNOOR ANJUM
DATE CREATED: 8/31/2018
DATE MODIFIED: -
DESCRIPTION: The following code implements the basic one way message
exchange for time synchronization.
The simplest approach of pairwise synchroniza... |
# from simple_date import SimpleDate
class Person:
def __init__(self,name,birthday,height,weight):
self.name = name
self.birthday = birthday
self.weight = weight
self.height = height
# implement an __eq__ method here
def __eq__(self,other):
if not isinstance(o... |
# 设计一个函数,对于身份证这个字符串
# 取出对应的性别:'男'、'女'
# 取出对应的生日:'20010723'
def sex(x: str) -> str:
"""取出身份证倒数第二位。判断性别"""
z = int(x[-2])
if z % 2 == 0:
return "性别为女"
else:
return "性别为男"
def bir(x: str) -> str:
"""从身份证中取出生日"""
a = x[6:10] +"年"
b = x[10:12] +"月"
c = x[12:14] + "日"
retu... |
inStr,outStr="",""
ch=""
count,i=0,0
inStr=input("문자열을 입력하세요:")
count=len(inStr)
for i in range(0,count):
ch=inStr[i]
if(ord(ch)>=ord("A") and ord(ch)<=ord("Z")):
newCh=ch.lower()
elif( ord(ch)>=ord("a") and ord(ch)<=ord("z")):
newCh=ch.upper()
else:
newCh=ch
outStr+=newCh
pr... |
mixlist=['apple',5,'banana','grape',3,8,6,'melon']
i=0
while i<=7:
if type(mixlist[i])==str:
print(mixlist[i])
print("type은 문자다")
i+=1
else:
print(mixlist[i])
print("type은 숫자다")
i+=1
|
ss=input("문자열 입력==>")
print("출력 문자열==>",end='')
for i in range(0,len(ss)):
if ss[i]!='o':
print(ss[i],end='')
else:
print('$',end='')
|
total2=int(input("전기용량:"))
if (total2<28*0.3):
print("휘발유로 주행해야한다.")
else :
print("전기로 주행해도됩니다")
|
t=int(input("에어컨 온도을 입력하세요:"))
if t<23:
print("적정온도가 아니니,온도를 높여야한다")
else:
print("적정온도입니다.")
|
sem=int(input("이수학기를 입력하시오:"))
sco=int(input("이수학점를 입력하시오:"))
if (sem==8) and (sco>=150):
print("정상졸업자입니다.")
elif (sco>=150):
print("조기졸업자입니다.")
else:
print("졸업대상자가 아닙니다.")
|
def plus(num1,num2):
return num1+num2
def minus(num1,num2):
return num1-num2
def multiply(num1,num2):
return num1*num2
def divide(num1,num2):
if num2!=0:
return num1/num2
else:
print("0으로 나누면 안되요ㅠㅠ")
return -1
|
import matplotlib.pyplot as plt
import numpy as np
#Generate a random number, you can refer your data values also
data = np.random.rand(4,2)
rows = list('1234') #rows categories
columns = list('MF') #column categories
fig,ax=plt.subplots()
#Advance color controls
ax.pcolor(data,cmap=plt.cm.Reds,edgecolors='k')
ax.set_x... |
x=float(input())
if x<20:
x=x*1.45
else:
x=x*1.3
print(x) |
# -*- coding: utf-8 -*-
from fractions import Fraction
from itertools import cycle
from codepage import toChr, toOrd, codepage
def dup(stack):
stack.append(stack[-1])
def pop(stack):
stack.pop()
def swap(stack):
b = stack.pop()
a = stack.pop()
stack.append(b)
stack.append(a)
def clear_stack(stack):
s... |
#hangman project - first unit.
# wtite the name of the game and draw the images for the wrong guesses.
# limit your gusses by using randint function
#the name of the game:
HANGMAN_ASCII_ART = print(""" _ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \\
| |... |
#write a message for the player to guess a letter
guess_a_word=input("Please enter a word:" )
#print the letter
print(string_of_char_word)
|
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
def encrypt(key, msg):
c = strxor(key, msg)
print
... |
import pandas as pd
####get data
df = pd.read_csv("desicion_tree.csv")
#print(df)
#####set the data like inputs[drop the output line] & target[only output] output which we need
inputs = df.drop('salary_more_then_100k',axis='columns')
target = df['salary_more_then_100k']
##print(inputs)
##print(ta... |
#Try out the Python stack functions
#TODO create a new empty stack
stack =[]
#TODO push items onto the stack
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
#TODO print the stack contents
print(stack)
#TODO pop an item from the stack
stack.pop()
print(stack) |
import random
def random_select(L,K,L1):
for i in range(K):
L1.append(random.choice(L))
L=['a','a','r','a','b','c','f','a','p','d','h','t','j','e']
L1=[]
random_select(L,3,L1)
print(L1) |
def insert(data,L,k,L1):
for i in range(len(L)):
if i!=k-1:
L1.append(L[i])
else:
L1.append(data)
L1.append(L[i])
L=['a','a','r','a','b','c','f','a','p','d','h','t','j','e']
L1=[]
data='alpha'
insert(data,L,3,L1)
print(L1) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: ... |
def reverse(x):
"""
:type x: int
:rtype: int
"""
maxN = (2**31 - 1)
num = int(str(abs(x))[::-1])
if num > maxN:
return 0
return num if x > 0 else -num
print(reverse(123))
print(reverse(-123))
print(reverse(120))
print(reverse(0))
print(reverse(1534236469)) |
def addBinary(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
rmnd = 0
a = max(a, b)
b = (len(max(a, b)) - len(min(a, b)))*"0" + min(a, b)
res = ""
for pos in range(len(a)):
num = int(a[::-1][pos]) + int(b[::-1][pos]) + rmnd
if num > 0:
res += "... |
number=int(input("ป้อนขนาดของคุณ = "))
for row in range(number):
for column in range(number):
print("x",end="")
print("") |
#users = ['admin', 'fred', 'lori', 'ryan', 'tyler']
users = []
for user in users:
if user in 'admin':
print(f"Hello {user.title()}, would you like to see a status report?")
elif user in users:
print(f"Hello {user.title()}, thank you for logging in again.")
if not users:
print("We need t... |
bicycles = [ 'trek', 'cannondale', 'redline', 'specialized']
# The first item in a list starts with [0]
print(bicycles[1])
print(bicycles[3])
# [-1] will always select the last item in a list
print(bicycles[-1])
message = f"My first bicyle was a {bicycles[0].title()}."
print(message) |
alien_color = 'green'
#alien_color = 'red'
#When the color is red there will not be any output message.
if alien_color is 'green':
print("You just earned 5 points")
#alien_color = 'green'
alien_color = 'yellow'
#alien_color = 'red'
if alien_color is 'green':
print("You just earned 5 points")
elif alien_color i... |
"""EZ"""
def main(money, rate, year):
"""ez"""
for _ in range(year):
money = money*(1+rate/100)
print("%.2f"%money)
main(int(input()), float(input()), int(input()))
|
"""pair"""
def main(wood1, wood2, wood3):
"""triagle"""
if wood2 >= wood1:
wood1, wood2 = wood2, wood1
if wood3 >= wood1:
wood1, wood3 = wood3, wood1
print("Yes" if abs(((wood1**2)+(wood2**2)+(wood3**2)-wood1**2)-(wood1**2)) <= 0.01 else "No")
main(float(input()), float(input()), float(i... |
"""psit"""
def main(day):
"""love psit"""
if day%400 == 0 or (day%4 == 0 and day%100 != 0):
print("Yes")
else:
print("No")
main(int(input()))
|
"""despacito"""
def main(text1, boxa=1, boxb=0, boxc=0):
"""sheep hide"""
for i in text1:
if i == "A":
boxa, boxb, boxc = boxb, boxa, boxc
if i == "B":
boxa, boxb, boxc = boxa, boxc, boxb
if i == "C":
boxa, boxb, boxc = boxc, boxb, boxa
print("1"*(... |
"""psit"""
def main(number, temp=0):
"""fc inw nut"""
num_max, num_min = max(number[0], number[1]), min(number[0], number[1])
while num_min > 0:
temp = num_min
num_min = num_max%num_min
num_max = temp
print(num_max)
main((int(input()), int(input())))
|
"""psit week3"""
def main(num):
"""i love psit"""
for j in range(1, num+1):
for i in range(1+j, num+1+j):
print(i, end=" ")
print()
main(int(input()))
|
"""EZ"""
def main(number):
"""test"""
ans_list = ["1", "2"]
for _ in range(3, number+1):
ans_list += [ans_list[-1]+ans_list[-2]]
print(ans_list[number-1])
main(int(input()))
|
"""despacito"""
def main(text1):
"""sheep hide"""
if text1[0].lower() in "qwertyuioplkjhgfdsazxcvbnm":
print("Hello %s."%text1)
else:
print("สวัสดี", text1)
main(input())
|
"""EZ"""
import json
def diff(list1, list2):
"""555"""
union = list1+list2
for i in set(list1).intersection(set(list2)):
if list1.count(i) != list2.count(i):
for _ in range(min(list1.count(i), list2.count(i))*2):
union.remove(i)
else:
while i in union:... |
"""EZ"""
def main(string):
"""EZ"""
for i in range(len(string)):
print(string[:i+1])
main(input())
|
"""psit"""
def gdc(number, temp=0):
"""fc inw nut"""
num_max, num_min = max(number[0], number[1]), min(number[0], number[1])
while num_min > 0:
temp = num_min
num_min = num_max%num_min
num_max = temp
return num_max
def main():
"""ez"""
number_list = sorted([int(input()) f... |
"""EZ"""
def test_pack():
"""EZ"""
for _ in range(int(input())):
book_worm(int(input()), int(input()))
def book_worm(times, values):
"""EZ"""
book_time = sorted([int(input()) for _ in range(values)])
if book_time:
while times >= book_time[0]:
if book_time:
... |
"""psit"""
def main(group1, group2):
"""fibo"""
group = list({input() for i in range(group1)}.intersection({input() for i in range(group2)}))
if group:
return print(*sorted(group)[::-1], sep="\n")
return print("Nope")
main(int(input()), int(input()))
|
"""psit"""
def blackjack(hand):
"""evil doctor"""
ans = 0
count = 0
for _ in range(hand):
card = input()
if card == "J" or card == "Q" or card == "K":
ans += 10
elif card == "A":
ans += 1
count += 1
else:
ans += int(card)
... |
#4. Faça um Programa que peça as 4 notas bimestrais e mostre a média.
print("================================================================")
print("Bem-vindo!!")
print("Digite as notas dos bimestres!!")
print("================================================================")
print("Se der erro não é um número!!")
p... |
import pyttsx3 # python text to speech version 3 its convert text form speech.
import speech_recognition as lis # as use for renaming or surname.
lisn = lis.Recognizer() # Creat a object of lis
speaker = pyttsx3.init() # creat a object of pyttsx3
print('Talk with me!')
speaker.say('Talk with me!') #.say() --> u... |
# Carga de los datos
import pandas as pd # https://pandas.pydata.org/docs/
import os # https://docs.python.org/3/library/os.html
import csv # https://docs.python.org/3/library/csv.html
import urllib3 # https://urllib3.readthedocs.io/en/latest/user-guide.html
main_path = 'D:/curso_python/datasets'
file_name = 'titanic/... |
from Board import Board
from HumanPlayer import HumanPlayer
class Game:
def __init__(self, player1, player2):
self.players= [player1, player2]
self.current_board = Board()
def start_loop(self):
current_state = [False, None]
current_player = 0
self.print_state()
... |
#CamJam EduKit 3 - Robotics
#worksheet 4 - Driving and Turning
import RPi.GPIO as GPIO # import the GPIO library
import time # import the time library
# set the GPIO modes
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# set variable for the GPIO motor pins
pinMotorAForwards = 9
pinMotorABackwards = 10
pinMotorBForw... |
n = int(input("Dati un numar. \t \t"))
for i in range(1, 11):
print(n, " x ", i, " = ", n * i) |
"""A tag-based chatbot framework."""
import re
from collections import Counter
class ChatBot:
"""A tag-based chatbot framework.
This class is not meant to be instantiated. Instead, it provides helper
functions that subclasses could use to create a tag-based chatbot. There
are two main components to a... |
"""
Chart definitions.
"""
GRAPH_COLORS = ('#FF0000', '#0000FF', '#00FF00', '#FF9900',
'#CC00CC', '#00CCCC', '#99CC00', '#990000', '#000066')
class Chart(object):
"""A chart definition.
A chart could have multiple graphs.
A graph displays points stored under a key.
"""
precision = 2
na... |
# Assignment 3 - IN4110 - H2020 - UiO
# Exercise 3.1
# Author: Fábio Rodrigues Pereira - fabior@uio.no
import sys, os
from pathlib import Path
def _counter(fn):
"""
Function to count the number of lines, words and characters in a file.
Paramters
_____________________
fn: string
Name... |
"""
David Pratt
for SIAM Fall 2019
========================= PROJECT EULER #07 ============================
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?
========================================================================... |
from random import randint
from os import system
#กำหนดตัวที่เก็บความถี่ Array = 0
def init(CT):
for r in range(5):
CT.append([])
for c in range(5):
CT[r].append([])
CT[r][c]=0
#กำหนด Array ที่รับข้อมูล โดยเริ่มต้นที่รับอายุ 1-3
def EnterData(TData):
for r ... |
from datetime import datetime
now = datetime.now()
import random
import database
import validation
from getpass import getpass
print(now)
def init():
print("Weclome to RP Bank")
haveAccount = int(input("Do you have a bank account with us: 1 (yes) 2 (no) \n"))
if(haveAccount == 1):
... |
import os
from parse import parse
def get_fe_info():
PATH = "info/fe_info.txt"
if os.path.exists(PATH): #file exists
f = open(PATH, "r")
line = f.readlines()[0]
info = parse("{} {}", line)
if info and check_ip(info[0]) and check_port(int(info[1])): #was able to parse file and ... |
def sep():
print("-" * 160)
print("")
print("-" * 160)
# union - combination of two or more sets, each item only once (no dupes/repeats)
# difference - everything in one set but not another
# symmetric difference - everything that is unique to all sets, no shared items
# intersection - a new set containing... |
def sep():
print("-" * 160)
print("")
print("-" * 160)
# old way of creating a set required the use of the set function
my_set = set([1, 2, 3])
print(my_set)
# in Python3 you can use curly braces alone to create a set if the set is not empty
new_set = {1, 2, 3} # note that while it uses curly braces, it i... |
# I need you to add a method name praise. The method should return a positive
# message about the student which includes the name attribute. As an example,
# it could say "You're doing a great job, Jacinta!" or
# "I really like your hair today, Michael!".
# Feel free to change the name attribute to your own name, too!
... |
"""
Alright, my list is messy! Help me clean it up!
First, start by moving the 1 from index 3 to index 0.
Try to do this in a single step by using both .pop() and .insert().
It's OK if it takes you more than one step, though!
"""
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
messy_list.insert(0, messy_list.pop(3))
m... |
#!/usr/bin/env python3
# Functions are great ways to clean up your
# code and use code pieces multiple times without
# need to rewrite or copy paste.
# to create a function
def printHello():
print("Hello!")
# now you can call this function to put it to use.
print("Welcome to my app. I'm now going to say hello... |
#!/usr/bin/env python3
class Dog:
def __init__(self, breed, name, age):
self.breed = breed
self.name = name
self.age = age
my_dog = Dog(breed="Lab", name="Aida", age=7)
print(f"My dog {my_dog.name} is a {my_dog.breed}, born {my_dog.age} years ago.")
|
#!/usr/bin/env python3
class Dog:
category = "animal"
def __init__(self, breed, name, age):
self.breed = breed
self.name = name
self.age = age
# this is a method. A method is just like a function
# but it's defined inside a class and can be called from
# the outside. You... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.