text stringlengths 37 1.41M |
|---|
# #Program to add 2 numbers
# number1 = raw_input("Enter 1st number : ");
# number2 = raw_input("Enter 2nd number : ");
#
# sum = int(number1) + int(number2)
#
# print("The Sum of {0} and {1} is {2}".format(number1,number2,sum))
#PYTHON 2.7 :
#raw_input takes input as it is while input() takes string input and eval() ... |
def insertion_sort(A):
for j in range(len(A)):
key = A[j]
i = j - 1
while i > -1 and A[i] > key:
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
return A
A = insertion_sort([2, 4, 1, 6, 5])
print("Sorted array is:")
print('\t'.join(map(str, A)))
|
# 循环语句
# my_list=[1,2,3,4,5,6,7,8,9,10]
# print(my_list[0])
# print(my_list[1])
my_list=['jack','tom','xiao li']
print(my_list[0])
print(my_list[1])
for name in my_list:
print(name)
for number in range(10,24,2):
print(number+1)
for letter in 'ocean':
print('each letter is:'+letter)
print(type(letter))
|
# import random
# for i in range(5):
# value1=random.randrange(1,5)
# print('value1:'+str(value1))
# for i in range(5):
# value2=random.randint(1,5)
# print('value2:'+str(value2))
# from random import randint,randrange
# for i in range(5):
# value1=randrange(1,5)
# print(value1)
#
# from rand... |
#object oriented
class Student():
def eat(self): #有class,def叫mathed,方法,属性
print('student can eat')
def study(self):
print('student can study')
Student().eat()
Student().study()
ocean=Student()
ocean.eat()
ocean.study()
print('----------------------------------------------------------------'... |
mylist=(1,2,3,4)
myDictionary={'key':'value','key2':'value'}
myPhones={'Iphone x':1000,'Sumsang s9':900}
print(myPhones)
#access dic keys
Iphone_Price=myPhones['Iphone x']
print('Iphone Price:'+str(Iphone_Price))
#不能直接用+,因为Iphone_Price是数字类型
#change key values
myPhones['Iphone x']=500
#不能写成Iphone_Price=500
print(myPho... |
# -*- coding:utf-8 -*-
from sys import argv
script, input_file = argv
#定义了三个函数,第一个输出显示文件内容,第二个位置回到文档最开始的字节,第三个输出显示文档的一行
#readline 执行完一次后位置会留在当前,再次执行时输出下一行
def print_all(f):
print f.read()
#seek()回到文件最开始的地方
def rewind(f):
f.seek(0)
#在print语句后加’ ,‘ 使打印完后不自动换行
def print_a_line(line_count, f):
print line_cou... |
# for logical operaotor
n1= 5
if(n1>2 and n1<7):
print("n1 is greater than 2 and smaller than 7....")
if(n1>4 or n1>6):
print("n1 is grater than 4 and also Greater than 6...")
if( n1 is not 2 ):
print("n1 is not equal 2 ") |
#ultiplication table and concept of f
num = int(input("Enter a number whose you want ltiplication Table of: "))
for i in range(11):
# print( str(i) + " * " + str(num) + " = " + str(i*num))
#here we can also use
print(f"{i} * {num} = {i * num}") #2nd way of printing |
def creating_New(string, rmword):
newstr = string.replace(rmword, "")
return newstr.strip() #for removing the blank space.
str1 = " Shubham this is Sentence "
n = creating_New(str1, "Shubham")
print("The new String is: ~~~",n)
|
rang = [1,2,3]
for i in rang:
print i;
print "loop is over"
for i in range(1,6):
print i;
|
name = input("Write Name: ")
if len(name) < 3:
print("Name must e at least 3 characters")
elif len(name) > 50:
print("Name must be a miximum of 50 characters")
else:
print("Names is correct") |
from pathlib import Path
# path = Path("emails")
# print(path.exists()) # check if this path exists
# print(path.mkdir()) # makes directory
# print(path.rmdir()) # delete directory
path = Path()
# print(path.glob("*.py")) # search for directories "*.*" for all files "*.py" all... |
import unittest
from activities import eat, nap
class ActivityTests(unittest.TestCase):
def test_eat_healthy(self):
"""Testing for healthy food eat function"""
self.assertEqual(eat("brocolli", is_healthy=True),
"I'm eating brocolli, because my body is a temple.")
def... |
palindromes = set()
for i in range(1,1000):
for j in range(1,1000):
number = str(i*j)
if len(number) % 2 == 0:
# even
first_half = number[:len(number)/2]
second_half = number[len(number)/2:]
else:
first_half = number[:len(number)/2]
second_half = number[len(number)/2+1:]
... |
def lenthOfLastWord(s):
if s == '':
return 0
else:
last_string = s.split(" ")
length = len(last_string)
if length == 1:
return len(last_string[length-1])
else:
new_list = [x for x in last_string if x]
new_list_length = len(new_list)
... |
def smallerNumbersThanCurrent(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count = 0
result = []
length = len(nums)
if length == 1:
return nums
if length >= 2:
for i in range(0, length):
for j in ra... |
def toLowerCase(str):
"""
:type str: str
:rtype: str
"""
str = str.lower()
return str
print(toLowerCase("ROSHAN")) |
# Task 1a
print "Hello, World!"
# Task 1b
name = raw_input("What is your name? ")
print "Hello, " + name + "!"
# Task 2
def is_leap_year(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
# Pro... |
def hanoi(n):
_hanoi_helper(n, 'A', 'C')
def _hanoi_helper(n, A, C):
if n == 0:
return
_hanoi_helper(n-1, A, C)
print A, "to B"
_hanoi_helper(n-1, C, A)
print "B to", C
_hanoi_helper(n-1, A, C)
|
# Python 3 program to find modular
# inverse of a under modulo m
# A naive method to find modulor
# multiplicative inverse of 'a'
# under modulo 'm'
def modInverse(a, m):
m0 = m
y = 0
x = 1
if (m == 1):
return 0
while (a > 1):
# q is quotient ... |
def has_consecutive(number):
i = 1
while i < len(number):
if number[i] == number[i - 1]:
return True
i += 1
return False
def has_2_consecutive(number):
i = 0
while i < len(number) - 1:
num_consecutive = 0
while i + num_consecutive < len(number) and numbe... |
import sys
def find_keys(maze):
keys = {}
for row in range(len(maze)):
for col in range(len(maze[row])):
tile = maze[row][col]
if tile == "@" or (tile.isalpha() and tile.islower()):
keys[tile] = (row, col)
return keys
def get_key_vector(keys):
all_keys... |
"""
Program that computes the readability using the Coleman-Liau index.
"""
"""
TODO
Count the number of letters, words & sentences.
* Count letters: only chars a to z.
* Count words: sequence of chars separated by spaces.
* Count sentences: separated by period,, exclamation point or question mark.
"""
import cs50
i... |
from tkinter import *#Imports every library from tkinter
from PIL import Image #Importing pillow module
from PIL import ImageTk #Importing pillow module
import tkinter #Importing tkinter module
import random #Importing random module
root = tkinter.Tk() #Tkinter.TK()
root.title("Rock, Paper, Scissors by AstronGaming")... |
#!/bin/python3
'''
Author: shamo0
An English text needs to be encrypted using the following encryption scheme.
First, the spaces are removed from the text. Let 'L' be the length of this text.
Then, characters are written into a grid, whose rows and columns have the following constraints:
floor(sqrt(L)) <= row <= colu... |
#!/bin/python3
'''
A deterministic environment is one where the next state is completely determined
by the current state of the environment and the task executed by the agent. If there
is any randomness involved in determining the next state, the environment is stochastic.
The game Bot Clean took place in a determin... |
def sum_of_two_numbers(number1,number2):
number1.reverse()
number2.reverse()
number = list()
carry = 0
max_length = len(number2)
for x in range(max(len(number1),len(number2))):
temp = number1[x]+number2[x]+carry
if(temp > 9):
carry = temp // 10
number.appe... |
# ENPM661, Spring 2020, Project 2
# Shelly Bagchi & Omololu Makinde
import math
import numpy as np
import cv2
class Node:
def __init__(self, node_no, map, parent, act, cost):
self.map = map
self.parent = parent
self.act = act
self.node_no = node_no
self.cost = cost
def co... |
"""Module permettant d'implementer des figures geometriques"""
from turtle import *
#Fonction pour tracer un rectangle
#Entree: longueur,largeur,couleur
#Sortie: rectangle
#Methode: boucle for
#Connu: les angles droit
def rectangle(longueur,largeur,couleur):
fillcolor(couleur)
begin_fill()
for i in rang... |
# Read the names and marks of at least 3 students
# Rank the top three students with highest marks
# Give cash rewards. $500 for first rank, $300 for second rank, $100 for third rank. Value cannot be modified
# Appreciate students who secured 950 marks and above
import operator
def readStudentDetails():
print()
... |
# Name : Arif Khan
# Judge: Dimik Oj
# University: Primeasia University
# problem: প্রোগ্রামিং সমস্যা 10 - [৫২ সমস্যা বই] রান রেট - ১
# Difficulty: Easy
# Time Complexity: 0.2712 সেকেন্ড
# ... |
def gcd(a, b):
assert int(a) == a and int(b) == b, 'The number must be integer only'
if a < 0:
a = -1*a
if b < 0:
b = -1*b
if b == 0:
return a
else:
return gcd(b, a%b)
print(gcd(48,18)) |
# Name : Arif Khan
# Judge: Dimik Oj
# University: Primeasia University
# problem: প্রোগ্রামিং সমস্যা 29 - [৫২ সমস্যা বই] চিহ্ন পরিচয়
# Difficulty: Easy
# Time Complexity: 0.3788 সেকেন্ড
# ... |
import queue
q = Queue()
n = int(input())
for i in range(n):
m = int(input())
q.put(m)
print("Queue size : ", q.qsize())
print("Queue first element : ",q.get())
print("Check Queue is full or not : ", q.full())
print("Queue is empty or not : ", q.empty())
while not q.empty():
print(q.get(),end=' ')
... |
# Name : Arif Khan
# Judge: SPOJ
# University: Primeasia University
# problem: CLSLDR - Class Leader
# Difficulty: Easy
# Problem Link: https://www.spoj.com/problems/CLSLDR/
#
# this solution ... |
# Name : Arif Khan
# Judge: HACKERRANK
# University: Primeasia University
# problem: Day 4: Class vs. Instance
# Difficulty: Easy
# Problem Link: https://www.hackerrank.com/challenges/30-class-v... |
# Name : Arif Khan
# Judge: HACKERRANK
# University: Primeasia University
# problem: Day 8: Dictionaries and Maps
# Difficulty: Easy
# Problem Link: https://www.hackerrank.com/challenges/30-dict... |
# Name : Arif Khan
# Judge: Dimik Oj
# University: Primeasia University
# problem: প্রোগ্রামিং সমস্যা 72 - ত্রিভুজ (ISCPC 2018 Preliminary)
# Difficulty: Easy
# Time Complexity: 0.5223 সেকেন্ড
#... |
# Name : Arif Khan
# Judge: Dimik Oj
# University: Primeasia University
# problem: প্রোগ্রামিং সমস্যা 42 - [৫২ সমস্যা বই] ধারার যোগফল - ৩
# Difficulty: Easy
# Time Complexity: 0.5878 সেকেন্ড
# ... |
if __name__ == '__main__':
tc = int(input())
for i in range(1,tc+1):
k = int(input())
print("Case ",end='')
print(i,end='')
print(':',end=' ')
for j in range(1,(k//2)+1):
if not k%j:
print(j,end=' ')
print(k) |
# Name : Arif Khan
# Judge: HACKERRANK
# University: Primeasia University
# problem: Day 5: Loops
# Difficulty: Easy
# Problem Link: https://www.hackerrank.com/challenges/30-loops/problem
#
imp... |
# 3科目の試験得点を管理するリストを1つ作成
test_score = []
# 国語の試験得点をキーボートから入力
japanese_score = int(input("国語の試験得点"))
# 国語の試験得点を手順1で作成したリストに追加
test_score.append(japanese_score)
# 数学の試験得点をキーボードから入力
math_score = int(input("数学の試験得点"))
# 数学の得点を手順1で作成したリストに追加
test_score.append(math_score)
# 英語の試験得点をキーボードから入力
english_score = int(input("数学... |
#
# Programming Assignment 2, CS640
#
# A Gomoku (Gobang) Game
#
# Adapted from CS111
# By Yiwen Gu
#
# The script provides a Gomoku Board class and a Player class
#
#
import random
class Board:
""" a data type for a Connect Five board with arbitrary dimensions
"""
def __init__(self, height=10, width=1... |
'''
题目:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
'''
def max(i,j):
if i>j:
return i
else:
return j
def biggest_subarray(dp,lenth,intial_list):
# lenth为母序列长度,intial_list为序列长度
dp[0] = intial_list[0... |
#Best for Regression and Classfication
#IMPORT LIBRARIES
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#IMPORT DATASET
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
#SPLIT DATA - TRAINING AND TEST
from sklearn.model_selection import train_t... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing Dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
#SPLITTING DATA UP
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test... |
import random
import matplotlib.pyplot as plt
def walkendgraph(startingposition=0,rightweight=1,leftweight = 1,nomovement = 1):
probablities = [1] * rightweight + [0] * nomovement + [-1] *leftweight
x=startingposition
res= {}
for i in range(-10,11,1):
res[i]=0
for i in rang... |
"""
Code Challenge
Name:
Webscrapping ICC Cricket Page
Filename:
icccricket.py
Problem Statement:
Write a Python code to Scrap data from ICC Ranking's
page and get the ranking table for ODI's (Men).
Create a DataFrame using pandas to store the information.
Hint:
https://www.icc-cr... |
# ‘hello world’
print("hello world")
print("Hallo, world")
print('First Line', end=' ')
print('Second Line', end='\n\n\n')
print('Third Line', end='!')
print('Third Line', end='\t')
print('Third Line')
print('#########')
print('#', end='\t')
print('#')
print('#', end='\t')
print('#')
print('#', end='\t')
print('#')... |
class Person():
def __init__(self, name, age, sex, lessons, education, purpose):
self.name = name
self.age = age
self.sex = sex
self.education = education
self.purpose = purpose
self.lessons = lessons
def __str__(self):
return f" {self.name.capitalize()}... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def append(self, newData):
if self.next is not None:
self.next.append(newData)
else:
self.next = Node(newData)
def print(self):
if self.next is None:
print(se... |
def change_list(name, age):
mylist = [1,2,3]
print("Name is ", name)
print("Age is", age)
return
change_list("Nitesh",1)
change_list(1,"Nitesh")
change_list(age=1,name="Nitesh")
|
"""
A utility to find search terms within a specfied line window.
"""
from __future__ import print_function
import os
import sys
import re
import fnmatch
import click
DEFAULT_WINDOW_SIZE = 8
NO_BORDER, EXTEND_TO_BORDER, TRUNCATE_AT_BORDER = range(3)
# matches a blank line (default border)
BLANK_LINE_TERM = r'^\s*$'... |
# Problem link - https://www.hackerrank.com/challenges/ctci-merge-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
def merge(li, low, mid, high):
i = low
j = mid + 1
inversionCount = 0
ansList = []
while i <= mid and j <= high:
if li[i]... |
def phoneCall(min1, min2_10, min11, s):
res = 0
if s >= min1:
res += 1
s -= min1
for x in range(0,9):
if s >= min2_10:
res += 1
s -= min2_10
else:
break
if res == 10:
for x in range(0,s):
if s >= min11:
... |
# We want to turn the given integer into a number that has only one non-zero
# digit using a tail rounding approach. This means that at each step we take the
# last non 0 digit of the number and round it to 0 or to 10. If it's less than 5
# we round it to 0 if it's larger than or equal to 5 we round it to 10 (rounding... |
def allLongestStrings(inputArray):
mayor = 0
final_array = []
# Busco el item mayor
for x in inputArray:
if len(x) > mayor:
mayor = len(x)
else:
continue
# Armo el array con los mayores
for y in inputArray:
if len(y) == mayor:
final_arr... |
# You have k apple boxes full of apples. Each square box of size m contains m × m apples.
# You just noticed two interesting properties about the boxes:
#
# The smallest box is size 1, the next one is size 2,..., all the way up to size k.
# Boxes that have an odd size contain only yellow apples. Boxes that have an even... |
# Given integers n, l and r, find the number of ways to represent n as a sum of two
# integers A and B such that l ≤ A ≤ B ≤ r.
#
# Example
#
# For n = 6, l = 2, and r = 4, the output should be
# countSumOfTwoRepresentations2(n, l, r) = 2.
#
# There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: 6 = 2 + 4... |
# quick sort
def quick_sort(num_array):
# базовый случай
if len(num_array) < 2:
return num_array
# рекурсивный случай
else:
pvt = num_array[0] # опорный элемент
less = [i for i in num_array[1:] if a <= pvt] # подмассив элементов, меньших опорного
greater = [i for i in... |
# /*
# ============================================================================
# Loads the plane displacement data at given coordinates, generates corresponding
# velocity and acceleration data, in order to print the hercules file.
# Version: Sep 10, 2015
# =======================================================... |
from tkinter import *
def bt_click():
print("bt_click")
lb["text"] = "It Woks!"
janela = Tk()
bt = Button(janela, width=10, text="OK", command=bt_click)
bt.place(x=100,y=100)
lb = Label(janela, text="Fala galera!")
lb.place(x=10,y=10)
janela.geometry("500x200+200+200")
janela.mainloop() |
Numpy checkboard pattern
import numpy as np
x = np.ones((3,3))
print("Checkboard pattern: ")
x = np.zeros((8,8),dtype = int)
x[1::2,::2] = 1
x[::2,1::2] = 1
print(x) |
#Program to implement pow(x,n)
class sol:
def pow(self,x,n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
retur... |
#To return sum of all divisors of a number:
try:
l = []
num = int(input("Enter the number: "))
for i in range(1,num+1):
if num%i ==0:
l.append(i)
print(l)
except:
print("Enter a valid integer!")
|
#To find factorial of a number
try:
number = int(input("Enter the number= "))
factorial = 1
if number < 0:
print("Factorial does not exist for negative numbers!")
elif number == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, number+1):
fac... |
#Gravitational force
try:
m1 = float(input("Enter the first mass: "))
m2 = float(input("Enter the second mass: "))
r = float(input("Enter the distance between the centres of the masses: "))
G = 6.673*(10**-11)
Formula = (G*m1*m2)/(r**2)
print("Hence, the gravitational force is: ",float(... |
#Read a list of words and return the length of the longest one
print(max(['a','cat','sat','goat'],
key = lambda s: (len(s), s)))
|
#To separate even and odd numbers in a separate list:
nums = range(1, 100)
list_even = [n for n in nums if n%2 == 0]
list_odd = [n for n in nums if n%2 == 1]
print("Odd numbers: "+ str(list_odd))
print("Even numbers: " +str(list_even)) |
#Rolling the dice
import random
try:
min = 1
max = 6
roll_again = "Yes"
while roll_again == "Yes" or roll_again == "y":
print("Rolling the dices...")
print("The values are...")
print(random.randint(min,max))
print(random.randint(min, max))
roll_... |
#Sort the list of tuples in increasing order by the last element in each tuple
tuple1 = [(1,2),(3,4),(5,6),(7,8)]
h = sorted(tuple1, key=lambda x: x[-1])
print(h)
|
# Concanate 2 dict into 1
dict_1 = {'A':1,'B':2}
dict_2 = {'C':3}
concatenating = dict_1.update(dict_2)
print(dict_1)
|
import random
import sqlite3
connection = sqlite3.connect('card.db')
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS card (
id INTEGER PRIMARY KEY,
number TEXT,
pin TEXT,
balance INTEGER DEFAULT 0);
""")
def luhn(number):
original_number = list(str(number))
d... |
#!/usr/local/bin/python
# Program for displaing information about POSIX compliant OSes.
# Define the clear function, which clears the screen.
def clear():
import os
os.system('cls' if os.name == 'nt' else 'clear')
# Define the print_menu function, which displays the menu.
def print_menu():
print " ... |
"""This file is provided as a starting template for writing your own unit
tests to run and debug your minimax and alphabeta agents locally. The test
cases used by the project assistant are not public.
"""
import unittest
import isolation
import game_agent
import logging
import logging.config
logging.config.fileConf... |
# Write your code here :-)
from microbit import *
# define our function
def weather_conditions(temp, condition):
# temperature
# temp = 84.4
# conditions
# condition = "dry"
# scroll the current conditions
# TODO
display.scroll(temp)
display.scroll(condition)
def c_to_f(ctemp):
fte... |
# Hyun-Joon Yang
# ITP 115, Fall 2018
# Assignment 10
# yanghyun@usc.edu
class Animal(object):
# constructor for animal object
# input: int representing hunger, happiness, energy, age; str representing name, species
# return: none
def __init__(self, hungerArg, happinessArg, healthArg, energyAr... |
# import MenuItem python file for use
from MenuItem import MenuItem
# create Menu class that does not inherit from another class
class Menu(object):
# class variable
MENU_ITEM_TYPES = ["Drink", "Appetizer", "Entree", "Dessert"]
# define constructor with necessary inputs
# input: string repr... |
# Hyun-Joon Yang
# ITP 115, Fall 2018
# Assignment 12
# yanghyun@usc.edu
from Human import Human
from Vampire import Vampire
def printHumans(humanlist):
for number in range(len(humanlist)):
print(number, humanlist[number])
def performFeeding(humanList, vamp):
userInput = input("Please ch... |
'''
Problem
An RNA string is a string formed from the alphabet containing 'A', 'C', 'G', and 'U'.
Given a DNA string t corresponding to a coding strand, its transcribed RNA string u is formed by replacing all occurrences of 'T' in t with 'U' in u
Given: A DNA string t having length at most 1000 nt.
Return: The tr... |
"""
模拟登录
如果账号的密码错误3次,提示锁定账户,效果如下:
请输入账号:qtx
请输入密码:1234
登录失败
你还剩余 2 次机会
请输入账号:Qtx
请输入密码:1234
登录失败
你还剩余 1 次机会
请输入账号:Qtx
请输入密码:123456
登录成功
"""
count = 3
right_account = "Pqz"
right_pwd = "123456"
while count > 0:
account = inpu... |
#! /usr/local/bin/python3
# count_change is another example of tree recursion
def count_change(amount):
return cc(amount, 5)
def cc(amount, kinds_of_coins):
if amount == 0:
return 1
elif amount < 0 or kinds_of_coins == 0:
return 0
else:
return cc(amount, kinds_of_coins-1) + cc(... |
#! /usr/local/bin/python3
from random import randint
def isEven(integer):
return integer%2 == 0
# return reminder of base^exp after dividing by m
# i.e (2**5)%5 = 2
def expmod(base, exp, m):
if exp == 0:
return 1
elif isEven(exp):
return (expmod(base, exp/2, m) ** 2)%m
else:
r... |
from legacy.hex_board import Board
top_header = ' _ '
# header = '_'
level_1 = '/{}\\_'
level_2 = '\\_/{}'
level_2_end = '\\_'
def print_board(the_board):
#
# draw header
#
lines = []
header = ''
for i in range(the_board.size):
header += top_header
print(header)
offset = ... |
import random
print('H A N G M A N')
print('Guess the word: ')
word_list = ['python', 'java', 'kotlin', 'javascript']
words = random.choice(word_list)
word = input()
if words == "python":
print("Guess the word pyt---:")
elif words == "java":
print("Guess the word jav-")
elif words == "javascript":
print("Gu... |
"""
1. Euclid's Algorithm
Part 1.
Function gcd takes in two numbers, calculates and returns their GCD
"""
import math
def gcd(x,y):
a = x
b = y
r = None
r_prev = None
while(r != 0):
q = math.floor(a/b)
r_prev = r
r = a - (q*b)
print(str(a) + " = " + str(q) + "*" + str(b) + " + " + str(r))
a = b
b ... |
def main():
M = int(input())
bot = list(map(int, input().strip().split()))
for i in range(0, M):
col = input().strip().find('p')
if col != -1:
princess = [i, col]
break
diff = [p - b for p, b in zip(princess, bot)]
if diff[1] == 0:
print('UP' if diff... |
# Boolean values: True, False
a = 3
b = 5
print('a = 3 b = 5')
print(f'a == b: {a == b}') # prints False
print(f'a != b: {a != b}') # prints True
print(f'a > b: {a > b}') # prints False
print(f'a < b: {a < b}') # prints True
print(f'type (True): {type(True)}') # prints 'bool'
print(f'type (False): {type(False)}') # p... |
global playerTurn, one, two, three, four, five, six, seven, eight, nine
playerTurn = "x"
win_condition = 0
drawCondition = False
#Board Spaces
one = "1"
two = "2"
three = "3"
four = "4"
five = "5"
six = "6"
seven = "7"
eight = "8"
nine = "9"
turn = 1
def drawBoard(one, two, three, four, five, six, ... |
'''
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
'''
class Solution:
def helper(self , nu... |
'''
给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。
'.' 匹配任意单个字符。
'*' 匹配零个或多个前面的元素。
匹配应该覆盖整个字符串 (s) ,而不是部分字符串。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "a*"
输出: true
解释: '*' 代表可匹配零个或多个前面的元素, 即可以匹配 'a' 。因此, 重... |
'''
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(... |
'''
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
'''
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
if not nums:
return []
res = []
n = len(nums)
... |
class backtest:
cash = 0
positions = {}
buy_commission = 0.00013
sell_commission = 0.00135
def __init__(self, init_fund=10000):
self._init_fund = init_fund
self.cash = init_fund
self.positions = {}
return
def buy(self, symbol, price, amount):
cost = (pri... |
# -*- coding: utf-8 -*-
grade={}
homepage=input('欢迎登陆学生BMI指数信息管理系统!按任意键继续\n')
while True:
print('~~\n欢迎你来到主菜单\n~~')
menu=('1.录入','2.查询','3.修改','4.删除','5.预览','6.退出')
for feature in menu:
print(feature)
number=('1','2','3','4','5','6')
order=input('请输入你想要操作的序号:\n')
if order in number:
... |
from board import Board
class Board(object):
def __init__(self, board, size, parent=None):
self.board = board
self.size = size
self.parent = parent
self.num_pieces = pow(self.size, 2)
goal = list(range(1, self.num_pieces))
goal.append(0)
self.goal = goal
... |
#!/usr/bin/python
"""
Logistic regression classification of preprocessed GoT data, with columns "season" and "text"
Steps:
- Read preprocessed data
- Get X (chunked sentences) and y (season labels)
- Split into train and test data using 80/20 split
- Use count vectoriser to extract features from X
- Train a... |
class Student():
def __init__(self, name,golar:int, will_array):
self.student_name = name
self.golar = golar
self.will = will_array
self.last = None
pass
def copyone(self,student):
self.student_name = student.student_name
self.golar = student.golar
... |
""" Playing around with the Look and Say sequence: https://en.wikipedia.org/wiki/Look-and-say_sequence """
import matplotlib.pylab as plt
def next_string(current_string):
""" we iterate along the current string and append the numbers to another string until we encounter a different one, at that point we append th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.