text stringlengths 37 1.41M |
|---|
# coding:utf-8
'''
礼物的最大价值
'''
def maxValue(matrix, i, j, value):
row = len(matrix)
col = len(matrix[0])
while i < row-1 and j < col-1:
if matrix[i + 1][j] >= matrix[i][j + 1]:
value += matrix[i + 1][j]
i += 1
else:
value += matrix[i][j + 1]
... |
# coding:utf-8
# The factorial of number
def factorial(number):
try:
if number == 1:
return 1
elif number >= 1:
return number * factorial(number - 1)
except Exception, e:
print 'Please input a natural number:', e
number = -233
print factorial(number)
|
# coding:utf-8
'''
栈的建立
'''
class Stack(object):
def __init__(self):
self.stack = []
def is_empty(self):
return self.stack == []
def push(self, val):
self.stack.append(val)
def pop(self):
if self.stack:
return self.stack.pop()
def peek(self):
... |
# coding:utf-8
'''
2.9 斐波那契数列
(1)递归,从后向前,产生重复元素
(2)动态规划:从前向后
'''
def Fib(n):
if n < 0:
return None
fib = [0, 1]
if n <= 1:
return fib[n]
for i in range(2, n+1):
fib.append(fib[i-2]+fib[i-1])
return fib
if __name__ == '__main__':
n = 10
print Fib(n)
|
# coding:utf-8
# Reverse a list by recursive
def Reverse_list(string_list):
if len(string_list) == 1:
return string_list[0]
else:
return string_list[-1] + Reverse_list(string_list[:-1])
string_list = '1738323839289382938923892'
print Reverse_list(string_list)
|
# coding:utf-8
'''
二叉树中和为某一值的路径
输入一个二叉树和一个整数,打印二叉树中节点值得和为输入整数的所有路径,
从根节点开始往下一直到叶节点所经过的节点形成一条路径
'''
class BinaryTreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# 树:递归算法
def PathSum(self, pRoot, N):
if pRoot ... |
# coding:utf-8
from Deques import deque
# Palindrome Checker:回文检查程序,字符串关于中间对称
def checker_palindrome(ch_string):
d = deque()
for c in ch_string:
d.add_front(c)
while d.size() > 1:
if d.remove_front() != d.remove_rear():
return False
return True
return False
ch_st... |
# codinng:utf-8
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# def getval(self):
# return self.val
#
# def getnext(self):
# return self.next
#
# def setval(self, newval):
# self.val = newval
#
# def setnext(self, newnext)... |
# coding:utf-8
import turtle
my_win = turtle.Screen()
# The Tutorial of Turtle
# 1、Turtle motion
print turtle.position()
turtle.forward(25) # 沿x轴正方向移动25 turtle.fd()
print turtle.position()
turtle.forward(-75) # 沿x轴负方向移动75
print turtle.position()
print '--------------------------'
print turtle.position() # turtl... |
# coding:utf-8
'''
2.21连续加法
判断一个数是否可以使用连续数之和来表示
'''
# 计算序列之和
def seqsum(first, last):
sum = 0
for i in range(first, last + 1):
sum += i
return sum
# 打印找到的序列
def showseq(first, last):
s = []
for i in range(first, last + 1):
s.append(i)
return s
def SequenceAdd(n):
if n ... |
# coding:utf-8
# quick sort
def quickSort(num_list):
quickSortHelper(num_list, 0, len(num_list) - 1)
def quickSortHelper(num_list, first, last):
if first < last:
split_point = partition(num_list, first, last)
quickSortHelper(num_list, first, split_point - 1)
quickSortHelper(num_list... |
# coding:utf-8
'''
快速排序:一半一半排序,递归排序
'''
def partion(nums, left, right):
key = nums[left]
while left < right:
while left < right and (nums[right] >= key):
right -= 1
nums[left] = nums[right]
print nums
while left < right and (nums[left] <= key):
left += ... |
# coding:utf-8
'''
将两个栈的操作写到main中,效果会差一些
优化方案:直接定义两个不同的栈,将栈之间的操作写入到队列类的创建中,main函数中只进行队列数据的进入和输出
'''
class MyQueue(object):
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
def pop(self):
if self.stack:
return self.stack.pop()
if __nam... |
#Funkcijas atgriež 10% no a un 20% no skaitlā b
def procenti(a,b):
return a/10, b/5
print(procenti(100,100))
#1. Uzraksti funkciju var_pagulet, kas atgriež True, ja ir brīvdiena un False, ja ir darbdiena. (Dienas no 1-7)
def var_pagulet(diena):
if diena <=5:
def monkey_trouble(a_smile, b_smile):
... |
#salīdzināšana
print(2 == 2)
print(2 == "2")
print(2 * 2 != 5)
a = 50
b = 4
c = 4
print(a > b, b > c, c < a)
print(a != b, b < c, c < a)
#loģiskie operatori - and/or/not
print(True and True)
a = 5
b = 10
c = 15
print(a > 5 and b > 20)
print(a >= 5 and b >= 10)
print(a >= 5 or b > 20)
print(not a > 7)
print(a >= 5 and ... |
#!/usr/bin/env python
import csv
import re
"""
This code deals with loading data from two files and saving changes when done.
This code can accept database operation for find and insert
Examples of command
Find order EmployeeID=5, ShipCountry=Brazil
Insert customer ("ALFKI","Alfreds Futterkiste","Mari... |
import csv
import urllib
import os.path
drugs = open("data/data.csv", "r")
reader = csv.reader(drugs)
highschool = {}
college = {}
def constructDicts():
#row[129] = year, row[66] = state
#row[51] = percentage for high school-aged people
#row[52] = percentage for college-aged people
for row in ... |
def greedy_solver_1(items, capacity):
# a trivial greedy algorithm for filling the knapsack
# it takes items in-order until the knapsack is full
value = 0
weight = 0
taken = [0]*len(items)
for item in items:
if weight + item.weight <= capacity:
taken[item.index] = 1
... |
i=0
str =input("enter a string :\n")
while i<len(str):
print(str[i],end='')
i=i+2
|
"""
10. Create a class called First and two classes called Second and Third which inherit from First.
Create class called Fourth which inherits from Second and Third. Create a common method called method1 in
all the classes and provide the Method Resolution Order.
"""
import math
class First:
def method1(... |
"""
5.Write a code to implement a child class called mathnew and parent classes as sqroot, addition,subtraction, multiplication
and division. Use the super() function to inherit the parent methods.
"""
import math
class Mymath(object):
def sqroot(self,a):
c=math.sqrt(a)
print "sq... |
import urllib.request, json, csv
import datetime as datetime
import openpyxl
# Import the data from the CoinMarketCap public API
with urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/?convert=GBP") as url:
data = json.loads(url.read().decode())
# Print a list of all coins and their GBP values
for x... |
# TODO: Script definition
import socket
from time import time
def get_socket():
"""Gives the UDP socket for use. We don't create the socket in 'send_udp' because if we do that, every time we
send a package we need to create a socket."""
print('Creating UDP Socket...')
try:
return socket.soc... |
# IMPORTS
# DATA
data = []
with open("Data - Day05.txt") as file:
for line in file:
data.append(int(line))
part2_data = data.copy()
# GOAL 1
"""
An urgent interrupt arrives from the CPU:
it's trapped in a maze of jump instructions,
and it would like assistance from any programs with spare cycles to help... |
# coding = utf-8
"""
==============
Deck Class
==============
"""
from Card import Card
from Const import CARD_FORMAT
import random
class Deck:
__cards = list()
__number = __cards
def __init__(self):
for suit in ['H', 'D', 'C', 'S']:
for number in range(1, 13+1, 1):... |
# A clustering data structure implementing k-means.
# (c) 2018
from random import randint
__all__ = [ "KMeans", "fdist", "fmean" ]
def fdist(a,b):
"""A distance function for float values."""
return abs(a-b)
def fmean(s):
"""A Mean function for float values."""
assert(s)
return sum(s)/len(s)
cla... |
import errno
import os
import os.path
import shutil
import platform
class Utils:
"""
This class stores some useful functions
"""
@staticmethod
def delete_if_exist(file_path):
"""
This function deletes a file if it exists.
:param file_path: The file we want to delete.
... |
#!/usr/bin/env python
import sys
def find_steps(n):
if n < 1:
return 0
steps = 0
while True:
print n,
if n == 1:
return steps
elif n%2 == 0:
n //= 2
steps += 1
else:
n = 3*n + 1
steps += 1
def find_steps... |
#!/usr/bin/env python
def count_vowels(word):
is_vowel = lambda x: x in 'aeiou'
vowels = dict([(i,0) for i in 'aeiou'])
for letter in word:
if is_vowel(letter):
vowels[letter] += 1
print vowels,sum(vowels.values())
count_vowels('aeiou')
count_vowels('wassup')
count_vowels('hello')... |
def bubble_sort(alist):
for _ in range(len(alist)-1,0,-1):
for i in range(_):
if alist[i] > alist[i+1]:
alist[i+1],alist[i] = alist[i],alist[i+1]
return alist
alist = [10,2,3,11,23,0,1,4]
print(bubble_sort(alist))
|
class HashTable:
def __init__(self):
self.size = 11
self.slots = [None]*self.size
self.data = [None]*self.size
def hashfunction(self, key, size):
return key%size
def put(self, key, data):
hashvalue = self.hashfunction(key, len(self.slots))
if self.data[has... |
from node import node
import random
class LinkedList(object):
def __init__(self, root_node: node = None):
if type(root_node) != node and root_node != None:
raise TypeError("Root node must be node or None class")
self.root_node = root_node
if self.root_node:
self.size... |
# SelectionSort implementation in Python.
#
# Time Complexity of a Solution:
# Best: O(n^2)
# Average: O(n^2)
# Worst: O(n^2)
import sys
import random
script, number = sys.argv
def SelectionSort(aList):
for i in range(len(aList)):
minimum = i
for j in range(i + 1, len(aList)):
if (aL... |
num = 100;
def getFactorial(num):
if(num == 1):
return 1
else:
return num * getFactorial(num - 1)
total = 0
for n in list(str(getFactorial(num))):
total += int(n);
print(total);
|
#1) Import the random function and generate both a random number between 0 and 1 as well as a random number between 1 and 10.
import random
randon_number = random.random()
random_number_2 = random.randint(1, 10)
print(randon_number)
print(random_number_2)
#2) Use the datetime library together with the random number t... |
#What will the value of z be?
x = input("Enter the value for x: ") #Lets say you entered 1 as your response when you ran this program
y = input("Enter the value for y: ") #Lets say you entered 2 as your response when you ran this program
z = x + y
print("z = ", z)
|
#-- Clean merge sort
# Recursive
def merge(t, i, j, k, aux):
# merge t[i:k] in aux[i:k] supposing t[i:j] and t[j:k] are sorted
a, b = i, j # iterators
for s in range(i, k):
if a == j or (b < k and t[b] < t[a]):
aux[s] = t[b]
b += 1
else:
aux[s] = t[a]
... |
#-- Print or count all the subsets of a set
def subsets(A): # O(2^n * n)
res = [[]]
for item in A:
n = len(res)
for i in range(n):
res.append(res[i] + [item]) # O(n)
return res
A = [1, 2, 3]
subs = subsets(A)
print(subs)
print(len(subs), " = ", 2**len(A))
def recSubsets(... |
""""
list = [1, 3, 5, 7, 8, 9]
for x in list:
sentence = "list contains " + str(x)
print(sentence)
"""
'''
import range:
for i in range(11)
print(6)
'''
def chibuzor(*args): # for multiple number of argument we introduce *args to our function
number_list = args
result_list = []
for number in n... |
"""
x = ["chibuzor", "chigozie", "chinyere", "kelechi", "ifeanyi"]
response = ""
while response != "end":
response = input("enter item: ")
if response in x:
print("certainly")
else:
x.append(response)
print(x)
"""
"""
x = [1, 2, 4, 5, 7, 8]
for item in x:
sentence = "list conta... |
import time
class Neighborhood():
def __init__(self):
self.r = -1
self.c = -1
def FindRowNeighbors(self):
return [(self.r, i) for i in range(1, 10)]
def FindColNeighbors(self):
return [(i, self.c) for i in range(1, 10)]
def FindBlockNeighbors(self):
if self.r ... |
"""
n = ""
while n != 50:
n = int(input("Digite aqui um numero inteiro: "))
if n > 50:
print(" Esse número é muito alto. Tente novamente: ")
"""
"""
# 1 - Crie uma lista com 20 números quaisquer (certifique-se de que alguns números são repetidos).
Ordene a lista em ordem numérica com o método 'sort()' ... |
"""
pessoas = {
"SP": 447,
"RJ": 323,
"MG": 121
}
print(pessoas)
print(pessoas["SP"])
print(pessoas.get("MG"))
refeicoes = {
"cafe": 5,
"bolo": 10
}
print(refeicoes)
for indice in refeicoes:
print(indice)
preco = refeicoes[indice]
print(preco)
print()
def pegarrefeicoes(indices):... |
import requests
import json
import wikipedia
class WikiApi:
"""
Class for setting up API. Contains methods for loading suggestions.
"""
url = 'http://en.wikipedia.org/w/api.php'
headers = {
'Content-Type': 'application/json'
}
def process_request(self, search_data):
"""
... |
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
# In[2]:
totals = pd.read_csv('totals.csv').set_index(keys=['name'])
# In[3]:
counts = pd.read_csv('counts.csv').set_index(keys=['name'])
# In[4]:
#print(totals)
# In[5]:
#print(counts)
# In[6]:
print("City with lowest total precipitation... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def main():
game=[["#","#","#"],
["#","#","#"],
["#","#","#"]]
A=1
B=2
C=3
turn="X"
continuous=0
while continuous < 9:
c=0
print " A B C"
for row in game:
c+=1
print str(c)+'|'.join(row)
print "It's "+turn+"'s turn."
print "Select a coo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from motor import Elmotor,Bensinmotor
import cPickle as pickle
def main():
#Create Electric Engine
Motor3=Elmotor()
#Create Fuel Engine
Motor1=Bensinmotor()
#Start/stop the Engine for Motor1
reply=raw_input("Start/Stop engine: ")
Motor1.changestate(reply)
#Run Fuel... |
'''
This script takes a multicast IP address and finds the multicast mac address. Takes multicast IP, converts
to binary string, then takes the hex value of every 4 chars in that string to find the mac
'''
print "There's no error checking, please be careful and enter IP addresses correctly"
first25 = '00000001000000... |
n=int(input())
for i in range(n):
print('*'*(n-i))
# 참고코드
# n=int(input())+1
# while n:=n-1:
# print("*"*n)
# :=연산자를 통해 값 사용과 갱신을 한줄에 작성 |
# Splits lines into a left and right set.
class LeftRightSplitter:
SAFETY_MARGIN = 0.025
def __init__(self, width, logger):
self.width = width
self.logger = logger
def run(self, lines):
left_lines = []
right_lines = []
rejected_lines = []
# Sometimes a line... |
#6.S08 FINAL PROJECT
#Leaderboard.py
#GET returns the current leaderboard, formatted by teensey, also can delete and clear the current leaderboard
import _mysql
import cgi
exec(open("/var/www/html/student_code/LIBS/s08libs.py").read())
#HTML formatting
print( "Content-type:text/html\r\n\r\n")
print('<html>')
#Set ... |
from syllable3 import *
from repo import make_syllable
import json
def syllabify(word):
syllable = generate(word.rstrip())
if syllable:
syllables = []
encoding = []
for syll in syllable:
for s in syll:
syllables.append(make_syllable(s))
encoding.append(s)
return (syllables, enco... |
# 8.1) A child can take 1,2 or 3 hops in a staircase of n steps. Given n, how many possible ways the child can
# up the stairs?
cache = {}
def steps(n):
if n < 0:
return 0
if n == 1:
return n
if not cache.get(n, False):
cache[n] = steps(n - 3) + steps(n - 2) + steps(n -1)
r... |
# given a sorted array, find the range of a given number.
class Solution:
# @param A : tuple of integers
# @param B : integer
# @return a list of integers
def searchRange(self, A, B):
a_len = len(A)
if a_len < 1:
return [-1, -1]
elif a_len == 1 and A[0] == B:
... |
# 8.8) write a program that writes the permutations of a word with duplicates
def permutations(word):
if len(word) == 1:
return word
word_list = list(word)
result = []
done = []
for i in range(len(word)):
temp = word_list.pop(i)
if temp in done:
word_list.ins... |
# Write code to remove duplicates
from SinglyLikedList import SinglyLikedList
# solution with hash table
def delete_duplicates_hash(l1):
current_node = l1.head
previous_node = None
frequencies = {}
while current_node is not None:
if frequencies.get(current_node.element, 0) > 0:
... |
from random import randint
def quick_sort(arr, left, right):
if left >= right:
return
pivot_index = partition(arr, left, right) # partition the array.
quick_sort(arr, left, pivot_index - 1) # sort left side
quick_sort(arr, pivot_index, right) # sort right side
def partition(arr, left, rig... |
# Given a list of non negative integers, arrange them such that they form the largest number.
class Solution:
# @param A : tuple of integers
# @return a strings
def largestNumber(self, arr):
arr = list(arr)
a_len = len(arr)
if a_len < 1:
return ''
if a_len == 1:
... |
class Array(object):
def sum(self, size, array_string):
numbers = [int(number) for number in array_string.split(' ')]
if size != len(numbers):
raise Exception('array size is not matched')
return sum(numbers)
|
#==================================================
#==> Title: invert-binary-tree
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/19/2021
#====================================... |
#==================================================
#==> Title: 769. 最多能完成排序的块
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 2/6/2021
#==================================================
"""
https://leetcode-cn.c... |
#==================================================
#==> Title: 154. 寻找旋转排序数组中的最小值 II
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/31/2021
#==================================================
"""
https://leetc... |
#==================================================
#==> Title: Stack
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/15/2021
#==================================================
"""
Next Greater Element
in: [2,... |
#==================================================
#==> Title: single-element-in-a-sorted-array
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/11/2021
#==================================================
"""
ht... |
#==================================================
#==> Title: first-unique-character-in-a-string
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/20/2021
#==================================================
"""
... |
import sys
sys.path.append('./Data Structures and Algorithms')
from LinkedLists import *
def printLinkedList(head):
if head == None: return
printLinkedList(head.next)
print(head.val)
def reverse(head):
pre, cur = None, head
while cur != None:
next = cur.next
cur.next, pre = pre, cu... |
#==================================================
#==> Title: peak-index-in-a-mountain-array
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/10/2021
#==================================================
"""
http... |
#==================================================
#==> Title: shortest-distance-to-a-character
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 1/27/2021
#===============================... |
#==================================================
#==> Title: 59. 螺旋矩阵 II
#==> Author: Zhang zhen
#==> Email: hustmatnoble.gmail.com
#==> GitHub: https://github.com/MatNoble
#==> Date: 2/1/2021
#==================================================
"""
https://leetcode-cn.com/... |
def order_inputs(x1, y1, x2, y2):
if x1 > x2:
x1, x2 = swap_inputs(x1,x2)
if y1 > y2:
y1, y2 = swap_inputs(y1,y2)
return x1, y1, x2, y2
def swap_inputs(a,b):
return b, a
def is_input_valid(layout, x1, y1, x2, y2):
width = len(layout)
height = len(layout[0]) if width > 0 else ... |
def isprime(n):
nn = n - 1
for i in xrange(2, nn):
if n % i == 0:
return False
return True
def primes(n):
count = 0
for i in xrange(2, n):
if isprime(i):
count = count + 1
return count
N = 10 * 10000
print(primes(N))
|
import re
import collections
# 获取词表、计数
with open('/Users/zhangwanyu/data.txt') as f:
data = f.readlines()
model = collections.defaultdict(int)
vocab = set()
for line in data:
line = re.findall("[a-z]+",line.lower())
for word in line:
model[word] += 1
vocab.add(wo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#. Дано предложение. Найти наибольшее количество идущих подряд пробелов.
if __name__ == '__main__':
st = input('Введите предложение')
mx = [0]
c = 0
for i in range(len(st)):
if st[i] == ' ':
mx[c] += 1
elif st[i] != ' ' and st[... |
from .functions import _DEPRECATION_ERROR_FUNCTION_KWARGS
from . import Units
from .data.data import Data
def relative_vorticity(
u, v, wrap=None, one_sided_at_boundary=False, radius=6371229.0, cyclic=None
):
"""Calculate the relative vorticity using centred finite
differences.
The relative vorticit... |
'''There is a function mu(k,N) := the probability that k random
numbers from 1...N have a connected graph.
strategy: given N and k pick k random numbers from 1...N and determine
if the graph is connected.
the graph on subset of the naturals, S, has edge between a,b if they
are not coprime.
'''
from itertools import i... |
s = "Global variable"
def func():
#return 1
#global s
#s=50
#print(s)
mylocal = 10
print(locals())
print(globals()['s'])
func()
print(s)
def hello(name="Rafina"):
return "hello "+name
print(hello())
mynewgreet = hello
print(mynewgreet())
def hello1(name="Rafina"):
print("THE HE... |
"""
This practice shows how class attribute is created and its namespace is different from instance attribute
more details are here: https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
"""
class Test_Class(object):
class_attribute = 1
def __init__(self, instance_attribute):
... |
print("Hello estranho!")
name = input("Qaul o seu nome ? ")
print("Praazer, " + name)
|
import random
l=["s","p","si"]
print(l)
#print(l[1])
#print(l[0])
#print(l[4])
#print(l[5])
#for i in range(0,6):
#print(i)
#l[1]=10
#print(l)
#print(l[1])
#print(len(l))
'''if "hi" in l:
print("Yes")
else:
print("No")'''
'''y = input("Enter your choice: ")
print("Hii ",y)'''
c = random.choice(l)
u = input("Enter y... |
class Family:
# class attribute
visits = 0
# instance attribute
def __init__(self, name, house_name):
self.family_name = name
self.house_name = house_name
self.members = []
# instance method
def add_member(self, x):
self.members.append(x)
# instance method... |
import pprint
class invalidAgeError(Exception):
pass
f=open("empdata.txt")
employees=[]
for line in f.readlines():
line=line.rstrip()
emp={}
emp['Id']=line.split(":")[0]
emp['Name']=line.split(":")[1]
emp['Age']=line.split(":")[2]
emp['Salary']=line.split(":")[3]
try:
if... |
class Counter:
__count = 0
def getCounter(self):
self.__count += 1
print self.__count
print "-----------------------------------------------------------"
counter = Counter()
counter.getCounter()
counter.getCounter()
# print counter.__count - ERROR
print counter._Counter__count
print "--------... |
str1 = raw_input("Enter the string : ")
rev = str1[::-1]
if str1==rev:
print "%s is Palindrome" %str1
else:
print "%s is not Palindrome" %str1
|
class SayHello:
def __init__(self,arg):
print "Inside Constructor = ",self
self.greeting = "Hello " +arg +", How are you ?"
def displayGreeting(self):
return self.greeting
def convertUpper(self):
return self.greeting.upper()
print "-------------------------------------... |
unsortedList = ['Aaaa', 'bb', 'cccccccc', 'zzzzzzzzzzzz']
print "Unsorted List : " ,unsortedList
sortedList = sorted(unsortedList,key=len)
print "Sorted List : " ,sortedList
|
lst = range(50)
print "Numbers Divisible by 4 : ",filter(lambda i:i%4==0, lst)
def evenCheck(x):
return x%2==0
print "Even Numbers \t\t: ",filter(evenCheck, lst)
words = ["abc","xyz","NIL","AMN"]
#print [i for i in words if i.isupper()]
print "Only Uppercase Words : ",filter(lambda i:i.isupper(),words)
|
listOne = [123,'abc',4.56]
print listOne
print "-----------------------------------------------------------"
tupleOne = (123,'abc',4.56)
print tupleOne
print "-----------------------------------------------------------"
print listOne[2]
listTwo = ['inner','first',listOne,56]
print listTwo
print "-----------------------... |
"""def long_words(n,str1):
longWordsList=[]
words = str1.split(' ')
for i in words:
if len(i) > n:
longWordsList.append(i)
return longWordsList
print(long_words(3,"The quick brown fox jumps over the lazy dog"))
"""
longWords = lambda : [i for i in raw_input("Enter the String ").spli... |
class BookingSystem(object):
'''
This is the class for booking system logic
'''
def __init__(self, row_count, seat_count):
self._seats = {} # array of array containing seat data 0 - free, 1 - occupied
self.row_count = row_count
self.seat_count = seat_count
for row in ran... |
import sys
from time import time
def bubble_sort(lista):
ordenado = False
while not ordenado:
ordenado = True
for i in range(len(lista)-1):
if lista[i] > lista[i+1]:
lista[i], lista[i+1] = lista[i+1], lista[i]
ordenado = False
def merge_sort(array,... |
#This is an example using a csv file for inputs.
#This example was created for use as a demo at the FIA NRMT 2018.
from PyEVALIDator import fetchTable
import csv
from EVALIDatorVars import *
def main():
#read inputs for fetchTable from inputFile.csv
#fetchTable(st, yr, nm, dn, pg, r, c, of, ot, lat, lon, rad)
... |
import tkinter
# Calculator main window details
m_window = tkinter.Tk()
m_window.title('Calculator')
m_window.geometry('300x300+800+350')
# Results entry box
results = tkinter.Entry(m_window, justify='center', borderwidth=4, relief='sunken')
results.grid(row=0, column=0, sticky='nsew', ipady=4)
# Button frame
b_fram... |
# Esta funcion verifica que cada digito
# de nuestro numero se encuentre dentro
# de la base a converitr
def checkNumber(number, dictionary):
for digit in number:
if digit not in dictionary:
return False
return True |
#!/usr/bin/python3
import sys
from my_priority_queue import PriorityQueue
from math import inf
from time import time
def get_graph(n, edges):
graph = [[] for _ in range(n)]
for edge in edges:
graph[int(edge[0])].append((int(edge[1]), float(edge[2])))
return graph
def dijskstra_path(graph, start):... |
#!/usr/bin/python
import sys
swap_counter = 0
comp_counter = 0
arr_len = 0
def select(array, k):
medians = []
n = len(array)
for i in range(0, n-n%5, 5):
print("Sortowanie fragmentu tablicy {}".format(array[i:i+5]), file=sys.stderr)
insertion(array,i,i+4)
medians.append(array[i+2]... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
'''
Building a Stock Price Predictor Using Python
https://www.section.io/engineering-education/stock-price-prediction-using-python/
'''
# In[2]:
'''
What is a RNN?
When you read this text,
you understand each word based on previous words in your brain.
You would... |
add1 = int(input ())
add2 = int(input())
amal = input("vared konid amalgar\n")
if amal == "+":
print (add1 + add2)
elif amal == "-":
print (add1 - add2)
elif amal == "*":
print (add1 * add2)
else :
print ("nashenas hast")
|
n=int(input("enter anumber"))
dict= {}
i=1
while i<=n:
dict[i]=i*i
i=i+1
print(dict) |
list1=['one','two','three','four','five']
list2=[1,2,3,4,5,]
data=dict(zip(list1,list2))
print(data) |
student_data={'a':'raam','b':'raaj','c':'raani','d':'class','g':'raam','h':'class'}
dict={}
for key,value in student_data.items():
if value not in dict.values():
dict[key]=value
print(dict) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.