text stringlengths 37 1.41M |
|---|
Class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
self.parent = None
def findnext(node,root):
if root and node:
if node.right:
mostleft = node.right
while mostleft... |
score=int(input("점수 :"))
deg={10:"A",9:"A",8:"B",7:"C",6:"D",5:"F",4:"F",3:"F",2:"F",1:"F",0:"F"}
print(score,":",deg[score//10])
|
# --------------
#Importing header files
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv(path)
plt.hist(data['Rating'].dropna(),bins=10)
plt.xlabel('Rating of the Apps')
plt.ylabel('Frequency')
plt.title('Rating is more the five')
plt.show()
data = data[data['Rating']<=5]
... |
import random
def check_answer(guess, number, counter):
if guess > number:
print("Too high")
return counter - 1
elif guess < number:
print("Too low")
return counter - 1
else:
print('You have guessed the number. You are WINNER')
def guess_game():
number = rando... |
import hangman_art
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
de... |
import numpy as np
## by yourself .Finish your own NN framework
## Just an example.You can alter sample code anywhere.
class _Layer(object):
def __init__(self):
pass
def forward(self, *input):
r"""Define the forward propagation of this layer.
Should be overridden by all subclasses.... |
#!/usr/bin/env python
# coding: utf-8
# # Coding a Two-Layer, Feed-forward Neural Network
# This file illustrates the training of a two-layer neural network, using sigmoid activation functions.
#
# This is meant to be a simpele implementation of how gradient descent and back-propagation work, and this code has not be... |
K = int(input())
t1=0
t2=1
for x in range(0,K):
nextterm = t1+t2
t1=t2
t2=nextterm
print(t1,sep=' ',end=' ')
|
def solution(n, arr1, arr2):
answer = []
for k in range(n):
arr = arr1[k] | arr2[k]
tmp = ""
for i in range(n):
if arr | (1<<i) == arr:
tmp += "#"
else:
tmp += " "
answer.append(tmp[::-1])
return answer |
import sys
read = sys.stdin.readline
# 아래의 Node, Trie class는
# [https://alpyrithm.tistory.com/74]
# 알파이님의 블로그를 토대로 작성했습니다.
class Node(object):
# trie 자료구조를 위한 node
def __init__(self, key, data=None):
self.key = key
self.data = data
# dictionary 자료구조 사용
self.children = {}
cla... |
class Node(object):
def __init__(self, key, data=None):
self.key = key
self.data = data
self.children = {}
class Trie(object):
def __init__(self):
self.head = Node(None)
def insert(self, string):
curr_node = self.head
for char in string:
if ch... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 07:31:47 2018
@author: makoto
"""
print('Please thing of a secret number between 0 and 100!')
low = 0
high = 100
guess = (low + high)//2
print('Is your secret number ' + str(guess) + '?', end='')
ans = input("Enter 'h' to indicate the guess is to... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 13:58:18 2018
@author: makoto
"""
x = float(input('Enter a decimal number between 0 and 1: '))
p = 0
while ((2**p)*x)%1 != 0:
print('Remainder = ' + str((2**p)*x - int((2**p)*x)))
print('Remainder% = ' + str(((2**p)*x)%1))
p += 1
num... |
import random
import tkinter as tk
from tkinter import ttk
from sorting_algorithms.bubble_sort import bubble_sort
from sorting_algorithms.quick_sort import quick_sort
from sorting_algorithms.merge_sort import merge_sort
from sorting_algorithms.selection_sort import selection_sort
from sorting_algorithms.heap_sort impo... |
def solution(s):
answer = ''
flag = False
for char in s:
if char.isalpha() and not flag:
answer += char.upper()
flag = True
elif char == ' ':
flag = False
answer += char
else:
answer += char.lower()
flag = True
... |
numbers = input().split()
if sorted(numbers, reverse=True) == numbers:
print("descending")
elif sorted(numbers) == numbers:
print("ascending")
else:
print("mixed")
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Swap the value not the node
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
node = head
while node and node.next:
no... |
string = input()
dic = {"c=": 0, "c-": 0, "dz=": 0, "d-": 0, "lj": 0, "nj": 0, "s=": 0, "z=": 0}
count = 0
for word in dic:
dic[word] = string.count(word)
dic["z="] -= dic["dz="]
croatian_count = 0
for word in dic:
croatian_count += (len(word) * dic[word])
count += sum(dic.values())
count += (len(strin... |
word = list(input().upper())
words = sorted(word)
if len(words) == 1:
print(words[0])
exit(0)
words_dict = {}
for c in words:
if c in words_dict:
words_dict[c] = words_dict[c] + 1
else:
words_dict[c] = 1
sorted_tuple = sorted(words_dict.items(), key= lambda x:x[1], reverse=True)
i... |
import sys
case = int(input())
for i in range(case):
nums = list(map(int, sys.stdin.readline().rstrip().split()))
average = (sum(nums[1:])/nums[0])
total = list(filter(lambda x: x > average, nums[1:]))
print("{:.3f}%".format(len(total) / nums[0] * 100))
|
def solution(n):
cases = ["4", "1", "2"]
answer = ''
while n:
answer = cases[n % 3] + answer
n = n // 3 - (n % 3 == 0)
return answer |
#!/usr/bin/python3
import math as m
class complex_number:
def __init__(self, r, i):
self.r = r
self.i = i
def out(self):
if self.i < 0:
return "{}{}i".format(self.r, self.i)
else:
return "{}+{}i".format(self.r, self.i)
def abs(self... |
#!/usr/bin/python3
name, surname, date = input("Enter name, surname and date:").split() #separated by spaces
#name, surname, date = input("Enter name: "), input ("Enter surname: "), input("Enter date: ") #separated by line breaks
print("Name: {}\nSurname: {}\nBirth Date: {}".format(name,surname,date)) |
input_file=open('standalone.txt', 'r')
ans=["a","an","the","-"]
sen=0
score=0
a=1
for c in input_file:
s=list(map(str, c.split()))
for e in range (len(s)):
if s[e]=="a" or s[e]=="the" or s[e]=="an":
correct=s[e]
s[e]="..."
print(" ".join(s))
print("A: a")
... |
#Берет из файла standalone.txt предложение, находит там глагол
#В файле questions-verbs.txt формирует запись следующего вида:
#Q: Петя ... погулять.
#А: Пошел
#B: Пошла
#C: Пошли
#D: Пошло
#Без символа комментария в начале строки. Тут глагол заменяется многоточием и предлагаются варианты ответа.
s=list(map(str, input()... |
""" Kill Kenny.
A really simple pygame game that demonstrates:
opening a pygame window
setting the background colour
displaying a sprite from an image
using random coordinates
checking for mouse clicks
checking is mouse click is in the rectangle of the sprite
updating the sprite im... |
import pygame
" CONSTANTS "
# Dimensions
WIDTH, HEIGHT = 400, 400
# Iterations per pixel
ITERATIONS = 100
# Colors
BLACK = (0, 0, 0)
def main():
"""
Main function of the program
"""
# Initialize pygame
pygame.init()
# Setup window
window = pygame.display.set_mode((WIDTH, HEIGHT))
# ... |
#EJER4
import os
#declaracion de variables
base_menor,base_mayor,altura,area,figura =0.0,0.0,0.0,0.0,""
verificador= False
#input
figura="trapecio"
base_menor=float(os.sys.argv[1])
base_mayor=float(os.sys.argv[2])
altura=float(os.sys.argv[3])
#processing
area=((base_mayor*base_menor*altura)/2)
verificador=(area>=100)
#... |
import os
#declarar las variables
cliente,vendedor,kg_papas,precio_kg="","",0.0,0.0
total_pagar=False
#input
cliente=os.sys.argv[1]
vendedor=os.sys.argv[2]
kg_papas=int(os.sys.argv[3])
precio_kg=float(os.sys.argv[4])
#processing
consumo_total=kg_papas*precio_kg
igv=consumo_total*0.18
total_pagar=consumo_total+igv
#... |
import os
#declarar las variables
velocidad_1,velocidad_2,distancia=0.0,0.0,0.0
tiempo_encuentro=False
#input
velocidad_1=int(os.sys.argv[1])
velocidad_2=int(os.sys.argv[2])
distancia=int(os.sys.argv[3])
#processing
tiempo_encuentro=(distancia)/(velocidad_1+velocidad_2)
tiempo_exacto=(tiempo_encuentro==10)
#output
p... |
#EJER9
import os
#declaracion de variables
area_lateral2,area_base2,area_total2,figura =0.0,0.0,0.0,""
verificador= False
#input
figura="prisma"
area_lateral2=float(os.sys.argv[1])
area_base2=float(os.sys.argv[2])
#processing
area_total2=(area_lateral2+(2*area_base2))
verificador=(area_total2>=200)
#output
print("#####... |
#EJER9
import os
#declaracion de variables
area_lateral2,area_base2,area_total2,figura =0.0,0.0,0.0,""
verificador= False
#input
figura="prisma"
area_lateral2=float(os.sys.argv[1])
area_base2=float(os.sys.argv[2])
#processing
area_total2=(area_lateral2+(2*area_base2))
verificador=(area_total2>=200)
#output
print("#####... |
#!/usr/bin/env python3
"""
Project Euler Problem 24
========================
A permutation is an ordered arrangement of objects. For example, 3124 is
one possible permutation of the digits 1, 2, 3 and 4. If all of the
permutations are listed numerically or alphabetically, we call it
lexicographic order. The lexicogra... |
#!/usr/bin/env python3
"""
Project Euler Problem 18
========================
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
... |
#!/usr/bin/env python3
"""
Project Euler Problem 67
========================
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
... |
#!/bin/python3
#
#
#
#
#
#
#
#
#
#
# 11
# 12
# 13
# 14
# 15
# 16
# 17
# 18
# 19
# 20
up_limit = 20
factors = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
not_found = True
def check_value(num):
for i in factors:
if num % i != 0:
return False
return True
def small_multiple(up_limit):
inc = 19 * 20... |
#!/bin/python3
import itertools
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
i... |
#!/usr/bin/env python3
"""
Project Euler Problem 42
========================
The n-th term of the sequence of triangle numbers is given by, t[n] =
1/2n(n+1); so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding... |
#!/usr/bin/env python3
def calc_sum(num):
s = 0
for x in range(4):
s += (num * num - x*(num - 1))
return s
def main():
diag_sum = 1
for i in range(3, 1001+1, 2):
diag_sum += calc_sum(i)
print(diag_sum)
if __name__ == "__main__":
main() |
from pygame import *
from math import *
from random import *
from Fonts import *
def pencil(tool, screen, canvas, mpos, mb, mx, my, ox, oy, color, thickness): #pencil tool
if tool == "Pencil":
screen.set_clip(canvas)
draw.line(screen, color, (ox, oy), (mx, my), thickness)
def marker(tool... |
import sys
import collections
import multiprocessing
import time
from datetime import datetime, date
FIND_SCIENCE_MSG = "Find a scientist name = %s, age = %d"
def process_item(item):
time.sleep(1)
born = 2017 - item.born
print(FIND_SCIENCE_MSG % (item.name, born))
return {
'name': item.nam... |
def main():
for i in range(5):
inputStr = input().split(" ")
j = 0
while j < len(inputStr):
if len(inputStr[j]) > 1 and findPunctuation(inputStr[j]):
punctuation = inputStr[j][len(inputStr[j]) - 1]
inputStr[j] = inputStr[j][:len(inputStr[j]) - 1]
... |
# -*- coding: utf-8 -*-
"""
Base class for Topologies
You can use this class to create your own topology. Note that every Topology
should implement a way to compute the (1) best particle, the (2) next
position, and the (3) next velocity given the Swarm's attributes at a given
timestep. Not implementing these methods ... |
'''
Дан список целых чисел. Подсчитать сколько четных чисел в списке
'''
x = 5
a = list(range(x))
n = 0
for i in range(x):
if a[i] % 2 == 0:
n += 1
print(a)
print(n) |
N = int(input('Введите количество гостей '))
if N > 50:
print('ресторан')
elif 20 <= N <= 50:
print('кафе')
else:
print('дома') |
from pymongo import MongoClient
import pandas as pd
import pickle
def connect_to_mongo(database_name,collection_name):
# Initial client to connect to mongo
client = MongoClient()
# Access/Initiate Database
database = client[database_name]
# Access/Initiate Table
collection = database[collect... |
import pandas as pd
import numpy as np
def fraud_column(df):
'''
Add column called fraud based on acct_type column.
Input: initial dataframe without labeled fraud
Returns: dataframe with label of fraud (1) or not fraud (0)
'''
df['fraud'] = df.apply(label_fraud, axis=1)
df_final = df.dro... |
from selenium import webdriver
from time import sleep
from pw import pw
import smtplib
# import os
# ask new instagram password from the user
new_pw = input("Enter new password : ")
confirm_pw = input("Enter same password to confirm : ")
class InstaBot :
def __init__(self, username, pw):
"""
... |
import sys
def solve_bot_trust(input_array):
position_dict = {'O': 1, 'B': 1}
time_since_last_push = {'O': 0, 'B': 0}
time = 0
for i in input_array[1:]:
if i == 'O':
pushing_bot = 'O'
moving_bot = 'B'
elif i == 'B':
pushing_bot = 'B'
... |
from os import system, name
import time
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
clear()
num=input("Please enter your decimal here:")
bin=0
divisionControl=int(num)
total= []
if(int(num)<0):
print("This is not a positive number.\n")
#C... |
#!/usr/bin/python
'''a very simple idiom for a state machine'''
from random import random
from time import sleep
# Each of the state functions below performs some action and then implements
# logic to choose next state. Each state function returns the next state.
def state0():
print "state0"
# delay and de... |
import textwrap
# My solution without textwrap (works fine)
# def wrap(string, max_width):
# lines = []
# total_length = 0
# for i in range(len(string) // max_width):
# lines.append(string[i * max_width : (i + 1) * max_width])
# total_length += max_width
# if total_length != max_width:
... |
def pow(base, exp):
if exp > 0:
return base * pow(base, exp - 1)
elif exp == 0:
return 1
base = int(input("Enter the base number: "))
exp = int(input("Enter the power of the number: "))
print(base, "^", exp, " = ", pow(base,exp), sep = '') |
#This is a platform independet script(you can run on any operating system)
import os
path=input("Enter your path: ")
if os.path.exists(path):
print("Given path : {path} is a valid path")
if os.path.isfile(path):
print("it is a file path")
else:
print("it is a directory path")
else:... |
# Paul Cruz
# CS5001
# HW 2
# Problem 1
# piglatin.py
# PURPOSE
# Translates a word to pig latin. The word must contain only letters. If the
# word starts with a vowel, the suffix "ay" will be added to the end.
# Otherwise, the consonant cluster at the start of the word is moved to the end
# then the suffix "ay" is ad... |
def main():
print("cuál es la factura total de hoy, por favor?")
money = float(input())
tip = money * 00.18
count = money + tip
print("18% propiena es $",round(tip), "lo que lleva tu total a",round(count))
main()
main() |
import pygame
class DotMachine:
def getValue(self):
'''
Get the current numerical value of the dots on the board
'''
pass
def explodeLeft(self):
'''
Update dot counts by collapsing lower place values to higher if appropriate
'''
gl... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 6 00:25:54 2021
@author: DELL Erali Abdinazarov
"""
print("Assalomu alaykum")
dasturlash = input("Qaysi dasturlash tilini o'rganasiz?\n>>>")
if dasturlash == "Python":
print("Sizga Omad!")
else:
print("Qaysi dasturlash tilini o'rganishigizdan qat'i nazar sizga ... |
# This program simulates the rolling of a user-specific number of dice with a user-specified number of sides.
# Each die has an independently randomly produced number between 1 and the number of sides the user specifies they
# want on their dice. User can repeat as many times as they want. Once the user chooses to quit... |
from turtle import *
raphael = Turtle()
screen = Screen()
raphael.color("red")
raphael.pensize(5)
raphael.speed(2)
raphael.shape("turtle")
#DRAWING INSTRUCTIONS
def drawTriangle():
for x in range(3):
raphael.forward(100)
raphael.left(120)
drawTriangle()
mainloop() |
import tkinter
import sqlite3
def convert(out_breed, enter_rank):
""" Find the rank in Sqlite3 dogs89.db table Dog_Licc and return the breed. """
num = enter_rank.get()
num_tup=(num,)
con = sqlite3.connect('dogs89.db')
cur = con.cursor()
cur.execute('''SELECT Breed FROM Dog_Licc WHERE Rank = ?'... |
import math
import unittest
from circle import Circle
class TestCircle(unittest.TestCase):
def test_init(self):
c=Circle(2)
self.assertEqual(c.r,2)
def test_girth(self):
c=Circle(2)
exp=2*math.pi*2
self.assertEqual(c.girth(),exp)
def test_area(self):
... |
#这次作业因为有很多不明白的地方,所以参考了一些网上的代码,若有问题请批评指正。
from socket import *
from time import ctime
bufferSize=1024
def recvMsg(host,port):
address=(host,port)
serverSocket=socket(AF_INET,SOCK_STREAM)
serverSocket.bind(address)
serverSocket.listen(5)
while True:
print('waiting for connection...')... |
dict={}
def add_dict(dictionary,en,ch):
dictionary[en]=ch
dictionary[ch]=en
print("添加成功")
for i in range(10):
en=input("增添的英文单词:")
ch=input("对应的中文单词:")
add_dict(dict,en,ch);
def find(dictionary,string):
if string in dictionary:
print("该单词的意思是:%s"%dictionary[string]... |
#>6 list type
bicycles=['trek','cannondale']
print (bicycles)
print(bicycles[0])
#>7 list-change/add/delate
bicycles[0]='change'
bicycles.append("motorcycle")
bicycles.insert(0,"ducati")
del bicycles[0]
pop_bicycle=bicycles.pop()
pop_bicycle=bicycles.pop(0)
bicycles.remove('cannondale')
#>8 list-sort()
cars=['bmw','aud... |
class Player(object):
def __init__(self, name):
self.name = name
self.hand = []
def addCard(self, card):
self.hand.append(card)
def showHand(self):
print "{}'s hand: ".format(self.name)
for card in self.hand:
print card
|
import random
playing = input("Do you want to start this awesome game? Type Yes or No. ")
if playing.lower() != "yes":
print("Okay, You can run the game again anytime you want to play!")
quit()
print("Okay then, Let's start this game!!")
print()
top_of_range = input("Type a number: ")
if top... |
import pygame
import queue
def BreadthFirstSearch(window, grid, rows, width, startX, startY, startTime, endX, endY):
q = queue.Queue()
startingNode = grid[startX][startY]
q.put(startingNode)
while not q.empty():
state = q.get()
#Check if its the goal node
if(state.isEnd()):
... |
def read_income(pathName = "c:\dat203.1x\mod4", fileName = "Adult Census Income Binary Classification dataset.csv"):
## Load the data
import pandas as pd
import os
## Read the .csv file
filePath = os.path.join(pathName, fileName)
return pd.read_csv(filePath)
## Plot categorical variables as ... |
import string
import os
from os.path import join
from pathlib import *
import re
def dos_2_unix(filename):
file_contents = open(filename, "r").read()
f = open(filename, "w", newline="\n")
f.write(file_contents)
f.close()
def find_files(top_dir, pattern, recursive=True):
# type (st... |
"""
Return the First Element in a List
Create a function that takes a list containing only numbers and return the first element.
Examples
get_first_value([1, 2, 3]) ➞ 1
get_first_value([80, 5, 100]) ➞ 80
get_first_value([-500, 0, 50]) ➞ -500
Notes
The first element in a list always has an index of 0.
"""
from edabit... |
"""
Power Calculator
Create a function that takes voltage and current and returns the calculated power.
Examples
circuit_power(230, 10) ➞ 2300
circuit_power(110, 3) ➞ 330
circuit_power(480, 20) ➞ 9600
Notes
Requires basic calculation of electrical circuits (see Resources for info).
"""
from edabit.Test import Test
d... |
"""
Correct the Mistakes
Fix the code in the code tab to pass this challenge (only syntax errors). Look at the examples below to get an idea of what the function should do.
Examples
squared(5) ➞ 25
squared(9) ➞ 81
squared(100) ➞ 10000
Notes
READ EVERY WORD CAREFULLY, CHARACTER BY CHARACTER!
Don't overthink this chal... |
"""
Fix the Expression
Fix the code in the Code tab so the function returns true if and only if x is equal to 7. Try to debug code and pass all the tests.
Examples
is_seven(4) ➞ False
is_seven(9) ➞ False
is_seven(7) ➞ True
Notes
The bug can be hard to find, so look closely!
"""
from edabit.Test import Test
def is_se... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 21:47:45 2019
@author: gwihy
"""
import random
class Dice :
face_no = 7
def shoot(self) :
return random.randint(1, 7)
ju = Dice()
ju.shoot()
import random
class Dice :
def __init__(self, val) :... |
from util import runall
from importlib import import_module
def exercise4():
while True:
response = input("Enter a pizza topping or quit: ")
if response.lower() == "quit":
break
else:
print(f"{response.capitalize()} has been added to your pizza.")
def exercise5():... |
x = float(input("Enter num for X; "))
y = float(input("Enter num for Y; "))
z = float(input("Enter num for Z; "))
j = (x+y+z)/3
print("Среднее арифметическое: ", j)
k = int(j/2);
print("J/2: ", k)
if (k > 3):
print("Successful!!!") |
class Person:
name = "Ivan"
age = 10
def set(self, name, age):
self.name = name
self.age = age
class Student(Person):
course = 1
Igor = Student()
Igor.set('Igor', 19)
Igor.course = 2
print('Name:',Igor.name,'Age:', Igor.age, 'Course:', Igor.course)
Vlad = Person()
Vlad.set ('Vlad', 2... |
# wu chi de python code
def revSentence(sentence):
s = sentence.split()
s.reverse()
print "reversed sentence is:"
for i in range(len(s)):
print s[i], |
#此题并非自己想出
#关键点 1 创建新节点 2 确保两个长度不同 3跳出循环后还要做一步判断
class Solution(object):
def addTwoNumbers(self, l1, l2):
l3 = ListNode(0)
current = l3
carry = 0
while l1 or l2: # 1,1 | None,1 | 1,None
# Pad 0 if None
if l1 is None:
l1v = 0
else:
... |
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
#思路一遍历一遍所有节点的值,放到数组里然后排序然后赋值给新的链表
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
nodelist = []
for i in range(len(lists)):
currentnode = lists[i]
while currentnode:... |
#利用了heapq的结构
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
dict = {}
for i in nums:
dict[i] = dict.get(i,0)+1
pq = list()
for key,value in dict.items():
... |
def divide(x, y):
return x / y
num1 = int(input("Enter miles driven: "))
num2 = int(input("Enter gallons of gas used: "))
print(num1,"/",num2,"=", divide(num1,num2)) |
# 设置当前线程的全局变量
# 场合:当前线程下,各函数的实参重复较多的情况下
import threading
# 创建全局ThreadLocal对象:
local_student = threading.local() # <class:dict>
def process_student():
# 获取当前线程关联的student:
name = local_student.name
print('Hello, %s (in %s)' % (name, threading.current_thread().name))
def process_thread(name):
# 绑定Thr... |
class Employee:
"""
This class is to represent an Employee
"""
def __init__(self, name, salary):
self.name = name
self.salary = salary
def print(self):
print(self.name, self.salary)
def netsalary(self):
return self.salary
class Manager(Employee):
def __ini... |
from math import sqrt
def FindPrimes(limit):
isPrime = {}
isPrime[1] = False
for i in xrange(2, limit + 1):
isPrime[i] = True
checkLimit = int(sqrt(limit)) + 1
for i in xrange(2, checkLimit):
if isPrime[i]:
for factor in xrange(2, limit + 1):
j = i *... |
import sys
def next_palindrome(number):
number = str(number)
number_len = len(number)
number_len_half = number_len // 2
left, middle, right = number[:number_len_half], (number[number_len_half:-number_len_half] or ''), number[-number_len_half:]
if len(left) == 0 and len(middle) == 0:
right = str(int... |
# def mirror(n, l):
# if l%2 == 0:
# left = n[:l/2]
# array = [left, left[::-1]]
# return "".join(array)
# else:
# left = n[:l/2]
# array = [left, n[l/2], left[::-1]]
# return "".join(array)
# def increment(n):
# numberString = mirror(n, len(n))
# p = int(numberString)
# if p > int(n):
# return p
#... |
import random
#todo
#1 zie beschrijving
def main():
word = getWord()
UserChoose(word)
#zet de woorden in een list en kiest een random woord
def getWord():
try:
bestand = open("test.txt")
wordFile = bestand.read()
word = []
# Alle woorden in het bestand hebben een spati... |
def find_number(y):
missing = []
if not isinstance(y, list):
raise TypeError('invalid input')
else:
for i in range(1, 10):
if i not in y:
missing.append(i)
return missing
print(find_number([1, 2, 3, 5, 6, 7, 9]))
|
from ler_entrada import ler_grafo_input, ler_grafo_arquivo
def is_euleriano(grafo):
"""
:param grafo:
:param grafo:
:return:
"""
return not has_vertices_grau_impar(grafo)
def has_vertices_grau_impar(grafo):
"""
:param grafo:
:return: Algum dos vértices do grafo possui grau ímpar?... |
mehmonlar = ['Jonibek','Temurbek','Javlonbek','O`tkirbek']
print(mehmonlar)
for k in mehmonlar:
print("Salom",k)
print("Xayr",k)
print(f"Hurmatli {k} sizni ertaga 9:00 da Nikoh oqshomiga taklish qilamiz")
print("Hurmat bilan Jonibek" )
sonlar = list(range(0,10))
for son in sonlar:
print(f"{son} ning kv... |
def oraliq(min,max,qadam):
sonlar = []
while min<max:
sonlar.append(min)
min+=qadam
return sonlar
print(oraliq(1,101,2)) |
from sys import exit
from random import randint
def game_room(key, points):
print("You are in the game room")
print("There's only one game here.")
print("In the corner is a prize store")
print("(Play) the game, go to prize (store) or (leave)")
action = input("> ")
if "play" in action:
... |
people = 20
cats = 30
dogs = 15
# de if-functie test of er een waarde is voordat het de code binnen de
# functie uitvoert
# deze waardes zijn of gewoon een waarde, of True
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < ... |
from sys import exit
class Scene (object):
def enter(self):
pass
# de class Engine, een instance werd aangemaakt toen a_game deze callde
# Engine erfde daarbij de eigenschappen/ attributes van Map, inclusief de
# variabele
# de Engine class has-a __init__ en play methods
class Engine(object):
def __... |
one = 1
zero = 0
if one != 1:
print("one")
else:
if one != 1:
print("one")
else:
if one != 1:
print("one")
else:
if one != 0:
print("happy face")
else:
print("zero")
if zero != 0:
print("yah")
else:
print... |
# geeft aan dat het aantal auto's 100 is.
cars = 100
# geeft aan hoeveel plaats er in een auto is.
space_in_a_car = 4
# geeft de variabele 'drivers' een cijfer
drivers = 30
# geeft aan in een variabele hoeveel passagiers er zijn.
passengers = 90
# deze variabele bestaat uit een combinatie (in een aftreksom) hoeveel aut... |
# een function met de naam (aangegeven door def) met als naam cheese_and_crackers
# binnen de function zijn er twee arguments, cheese_count en boxes_of_crackers
# deze nemen een waarde aan die later worden meegegeven wanneer de function
# wordt gecalled/geuset/gerund
# de function hierbeneden print in de eerste twee st... |
import pandas as pd
import sqlite3
import matplotlib.pyplot as plot
import matplotlib.mlab as mlab
import matplotlib.dates as dates
conn = sqlite3.connect("database.sqlite")
'''
Select all rows which loan status is charged off from orginal data table
and consist of a new data table named charged_off_loan
'''
charged_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.