blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
a7c3457276ecc11d0cff0a1821cfab073e544811 | mansipurohit11/100-Days-Python | /GuessTheGame.py | 865 | 3.984375 | 4 | import random
from art import logo
print(logo)
print("Welcome to gussing game!\nI'm thinking of a number between 1 to 100.")
type = input("Choose a difficulty. Type 'easy' or 'hard': ")
answer = random.randint(1, 100)
if type == "easy":
chances = 10
elif type == "hard":
chances = 5
else:
print("Sorry wrong input try again")
game_over = True
while game_over:
print(f"You have {chances} attemps remaining to guess the number")
choice = int(input("Make a guess: "))
if choice == answer:
print(f"You got it! The answer was {answer}.")
break
elif chances == 1:
print("You run out of guesses, you loss.")
break
else:
if choice > answer:
print("Too high")
elif choice < answer:
print("Too low")
chances -= 1
continue |
94de3a8fce5a89456e90984a65b204e87101f565 | saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174- | /Introduction to Programming Exercises/ex31.py | 476 | 4.0625 | 4 | '''
Exercise 31: Sum of the Digits in an Integer
Develop a program that reads a four-digit integer from the user and displays the sum
of the digits in the number. For example, if the user enters 3141 then your program
should display 3+1+4+1=9.
'''
num = int(input('Enter your four digit number: '))
num_list = list(map(int, str(num)))
summation = sum(num_list)
print('{} + {} + {} + {} = {}'. format(num_list[0], num_list[1], num_list[2], num_list[3], summation)) |
c717bbca497cbbd86acaea0a27900b713f5a626f | thylaco1eo/practice | /datastructre/graph.py | 1,168 | 3.78125 | 4 | def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath:
return newpath
def find_all(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
def shortest_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph.:
return None
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_shortest_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest |
f1f022b40c04c440eb34cbb69099e30398a09b80 | omadara/Educational-Software | /Educational Software/extra/example exercise.py | 872 | 4.03125 | 4 | # exercise description goes here
# use question marks(?) if needed to help user complete the exercise
def func(words):
count = 0
for word in words:
if ????????? and ?????????:
????????
return count # dont forget to return a value to use on testing
# only the code above this line gets shown to the user
# TEST CODE START
# use this function for testing, user will see the testing output
# or u can import it with "from testing import test"
prefixPrinted = False
def test(args, got, expected):
global prefixPrinted
if not prefixPrinted:
print("=== Testing your code ===")
prefixPrinted = True
status = "CORRECT" if got == expected else "FAILED"
print(f"{status} input: {args} got: {got} expected: {expected}")
# example tests
test(123, func(123), 1)
test(1234, func(1234), 42)
test(9999, func(9999), 10)
|
e517f10d472716263b3fb4601ddb6d42a26ec8a2 | quixoteji/Leetcode | /solutions/508.most-frequent-subtree-sum.py | 926 | 3.546875 | 4 | #
# @lc app=leetcode id=508 lang=python3
#
# [508] Most Frequent Subtree Sum
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
return self.sol1(root)
# Solution 1 : dfs
def sol1(self, root) :
if not root : return []
ans = []
self.subtrees(ans, root)
counter = collections.Counter(ans)
ans = collections.defaultdict(list)
for val in counter : ans[counter[val]].append(val)
print(ans)
return ans[max(ans.keys())]
def subtrees(self, ans, root) :
if not root : return 0
val = self.subtrees(ans, root.left) + self.subtrees(ans, root.right) + root.val
ans.append(val)
return val
# @lc code=end
|
7cddbc18ea9642f622e095d103391a8f1b57cbf1 | amaldare93/myCode | /Structures.py | 5,635 | 4 | 4 | class node(object):
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
class linked_list(object):
def __init__(self, head=None, tail=None):
self.head = head
self.tail = tail
def appendFront(self, thing):
# create node for data
if type(thing) != type(node()):
thing = node(thing)
# if list is empty
if not self.head:
self.head = thing
self.tail = thing
else:
thing.next = self.head
self.head.prev = thing
self.head = thing
def appendBack(self, thing):
# create node for data
if type(thing) != type(node()):
thing = node(thing)
# if list is empty
if not self.head:
self.head = thing
self.tail = thing
else:
self.tail.next = thing
thing.prev = self.tail
self.tail = thing
def insertAfter(self, node, newThing):
# create node for data
if type(thing) != type(node()):
thing = node(thing)
# if adding to end
if node == self.tail:
node.next = newThing
newThing.prev = node
self.tail = newThing
else:
newThing.next = node.next
newThing.prev = node
node.next.prev = newThing
node.next = newThing
def delete(self, thing):
# if list is empty
if self.head == None:
return
# if thing data, find node
if type(thing) != type(node()):
thing = self.search(thing)
# if thing is only node in list
if self.head == self.tail == thing:
self.head = None
self.tail = None
del thing
return
# if thing is head
if thing == self.head:
self.head = thing.next
self.head.prev = None
del thing
return
# if thing is tail
if thing == self.tail:
self.tail = thing.prev
self.tail.next = None
del thing
return
# else
thing.prev.next = thing.next
thing.next.prev = thing.prev
del thing
return
def printList(self):
current = self.head
buff = []
while(current != None):
buff.append(current.data)
current = current.next
print(buff)
def search(self, data):
current = self.head
while(current != None):
if(current.data == data):
return current
else:
current = current.next
return False
def size(self):
if self.head == None:
return 0
current = self.head
count = 0
while(current != None):
count += 1
current = current.next
return count
class stack(object):
def __init__(self):
self.top = None
def push(self, data):
temp = node(data)
temp.next = self.top
self.top = temp
def pop(self):
if self.top != None:
temp = self.top
self.top = self.top.next
return temp.data
return None
def peek(self):
return self.top.data if self.top != None else None
def isEmpty(self):
return self.top == None
class queue(object):
def __init__(self):
self.head = None
self.tail = None
self.size = 0
class node(object):
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
def isEmpty(self):
return self.size == 0
def size(self):
return self.size
def enqueue(self, data):
n = self.node( data )
self.size += 1
if self.size != 1:
n.next = self.tail
self.tail.prev = n
self.tail = n
else:
self.head = n
self.tail = n
def dequeue(self):
if self.size > 1:
self.size -= 1
result = self.head.data
self.head = self.head.prev
del self.head.next
self.head.next = None
return result
elif self.size == 1:
self.size -= 1
result = self.head.data
del self.head
return result
else:
return None
def peek(self):
return self.head.data if self.size != 0 else None
class binTree(object):
def __init__(self):
self.root = None
class node(object):
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def __lt__(self, rh):
return self.data < rh.data
def __gt__(self, rh):
return self.data > rh.data
def height(self, node=1):
# initial call
if node == 1:
return self.height(self.root)
# recursion
elif node != None:
return max(self.height(node.left), self.height(node.right)) + 1
# base case
elif node == None:
return 0
def printIn(self, node=1):
# initial call
if node == 1:
node = self.root
# recursion
if node != None:
self.printIn(node.left)
print(node.data)
self.printIn(node.right)
def contains(self, data):
current = self.root
while current != None:
if data == current.data:
return True
elif data < current.data:
current = current.left
else: # data > current.data
current = current.right
return False
class binSearchTree(binTree):
def insert(self, data):
# create new node with data
n = self.node(data)
# search for sorted position
if self.root != None:
current = self.root
while current != None:
if n < current:
if current.left != None:
current = current.left
else:
current.left = n
return
elif n > current:
if current.right != None:
current = current.right
else:
current.right = n
return
else:
# ignore duplicates
return
else:
self.root = n
def remove(self, data):
current = self.root
while current != None:
if data == current.data:
#delete node
pass
elif data < current.data:
current = current.left
else: # data > current.data
current = current.right
return False
|
4d681ad4ff51a47d4b0e8983405772065c68006d | ToruTamahashi/practice_python | /ファイル操作/seek.py | 375 | 3.609375 | 4 | with open('text.txt', 'r') as f:
# test.txtのなかで今何文字目を見ているかを表示
print(f.tell())
# 現在の位置の文字を読み込んで次の位置に移動
print(f.read(1))
# 5文字目に移動
f.seek(5)
print(f.read(1))
# 戻ることもできる
f.seek(1)
print(f.read(1))
f.seek(10)
print(f.read(1)) |
125f823ae1dc2b59a23238113b0c12f8f3fbbac7 | Chestnut-lol/MIT-6.006 | /ps6/rubik/solver.py | 2,407 | 3.703125 | 4 | import rubik
def shortest_path(start, end):
"""
Using 2-way BFS, finds the shortest path from start_position to
end_position. Returns a list of moves.
You can use the rubik.quarter_twists move set.
Each move can be applied using rubik.perm_apply
"""
if start == end:
return []
# keep track of states that have been expanded from the start
parent = {start:None} # child_node: (parent_node, perm)
# where perm_apply(parent_node) = child_node
# keep track of states that have been expanded from the end
child = {end:None} # parent_node: (child_node, perm)
# where perm_appry(parent_node) = child_node
level = 1
frontier = [start]
backtier = [end]
found = None
while level <= 7:
# expand from end
next = []
for current_state in backtier:
for twist in rubik.quarter_twists:
state = rubik.perm_apply(rubik.perm_inverse(twist), current_state)
if state not in child:
child[state] = (current_state, twist)
next.append(state)
if state in parent:
found = state
break
if found:
break
if found:
break
backtier = next
mext = []
for current_state in frontier:
for twist in rubik.quarter_twists:
state = rubik.perm_apply(twist, current_state)
if state not in parent:
parent[state] = (current_state, twist)
mext.append(state)
if state in child:
found = state
break
if found:
break
if found:
break
frontier = mext
level += 1
if found is None:
return None
else:
result = []
current_state = found
while current_state != start:
pred_pair = parent[current_state]
result = [pred_pair[1]] + result
current_state = pred_pair[0]
current_state = found
while current_state != end:
succ_pair = child[current_state]
result = result + [succ_pair[1]]
current_state = succ_pair[0]
return result
|
8f07afe6290baa07f560820d2547c247e063b6c5 | ajakaiye33/pythonic_daily_capsules | /analyze_age_in_dict.py | 893 | 3.765625 | 4 | from statistics import mean
def analyze_age_dict(lst):
"""
Receives a list of dictionaries, pulls the value associated with key "age"
from each dictioanry, and return a new dictionary with two keys:
*"average": The average age of the inpu dict
*"dictionary_count": The number of lelement processed
"""
counter = 0
divi = []
say = {}
for di in lst:
for v in di.values():
if di["age"] == v:
counter += 1
divi.append(v)
say["ave_age"] = mean(divi)
say["dict_counter"] = counter
return say
print(analyze_age_dict([{"names": "Bob", "age": 22}, {"name": "Jane", "age": 26}]))
print(analyze_age_dict([{"names": "Hermione", "age": 22}]))
print(analyze_age_dict([{"names": "Bob", "age": 22}, {
"name": "Jane", "age": 26, "name": "Alice", "last_name": "Jones"}]))
|
f10646f9c6ef894a46373b115fc4c9f7b0c26aba | nstvn/Chess | /main.py | 3,609 | 3.875 | 4 | class Chess: #Создали класс для обработки координат
def __init__(self):
self.k = int(
input('Введи координату первой клетки по горизонтали (1-8): ')) # x
self.l = int(
input('Введи координату первой клетки по вертикали (1-8): ')) # y
self.m = int(
input('Введи координату второй клетки по горизонтали (1-8): ')) # x2
self.n = int(
input('Введи координату второй клетки по вертикали (1-8): ')) # y2
def check_color(self): #Создали функцию по сравнению цвета поля
if (self.k + self.l + self.m + self.n) % 2 == 0:
print('Поля одинакового цвета')
else:
print('Поля разного цвета')
def ferz(self): #Создали функцию по проверке угрозы ферзя
if (self.k == self.m) or (self.l == self.n) or (
self.k - self.l == self.m - self.n) or (
self.k + self.l == self.m + self.n):
print(f'Ферзь угрожает полю ({self.m}, {self.n})')
else:
print(f'Ферзь не угрожает полю ({self.m}, {self.n})')
def koni(self): #Создали функцию по проверке угрозы коня
if ((self.n - self.m == 2 or self.m - self.n == 2) and (self.k - self.l == 1 or self.k + self.l == 1)) or (
(self.n - self.m == 1 or self.m - self.n == 1) and (self.l - self.k == 2 or self.k - self.l == 2)):
print(f'Конь угрожает полю ({self.m}, {self.n})')
else:
print(f'Конь не угрожает полю ({self.m}, {self.n})')
def ladia(self): #Создали функцию по проверке хода ладьи
if self.k == self.m or self.l == self.n:
print(f'Ладья дойдет за 1 ход на поле ({self.m}, {self.n})')
else:
print (f'Ладья дойдет за 2 хода. Поле первого хода ({self.m}, {self.l})')
def progylka_ferzia(self): #Создали функцию по проверке хода ферзя
if (self.k == self.m) or (self.l == self.n) or (
self.k - self.l == self.m - self.n) or (
self.k + self.l == self.m + self.n):
print(f'Ферзь дойдет за один ход на поле ({self.m}, {self.n})')
else:
print (f'Ферзь дойдет за 2 хода. Поле первого хода ({self.m}, {self.l})')
def slon(self): #Создали функцию по проверке хода слона
if (self.k - self.l == self.m - self.n) or (self.k + self.l == self.m + self.n):
print(f'Слон дойдет за один ход на поле ({self.m}, {self.n})')
elif (self.k + self.l + self.m + self.n) % 2 == 0:
for x in range(1, 9):
for y in range(1, 9):
if abs(x - self.k) == abs(y - self.l) and abs(x - self.m) == abs(y - self.n):
print(f'Слон дойдет за 2 хода. Поле первого хода ({x}, {y})')
else:
print('Слон не дойдет до второго поля')
a = Chess()
a.check_color()
a.ferz()
a.koni()
a.ladia()
a.progylka_ferzia()
a.slon()
|
2cd9f7700bf18c7226cc0f362f2c969dcad5424d | battulakarthik/my-file2 | /check sub of sting.py | 65 | 3.53125 | 4 | n,m=input().split()
if m in n:
print("yes")
else:print("no")
|
dcdda281c8cc0399a537dfb5e5bc5b018161adb7 | CiceroLino/Learning_python | /Curso_em_Video/Mundo_1_Fundamentos/Usando_modulos_do_python/ex016.py | 407 | 3.78125 | 4 | #Desafio 016 do curso em video
#Programa que mostra sua poção inteira
#https://www.youtube.com/watch?v=-iSbDpl5Jhw&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=17
from math import trunc
num = float(input('Digite um valor: '))
print(f'O valor digitado foi {num} e sua porção inteira é {trunc(num)}')
#Outro método
#print(f'O valor digitado foi {num} e sua porção inteira é {int(num)}')
print()
|
17d7c2abdd72edfbaf3850e170f54c9061d20972 | Aasthaengg/IBMdataset | /Python_codes/p03852/s447757723.py | 80 | 3.828125 | 4 | s = input()
x = 'aiueo'
if s in x :
print('vowel')
else :
print('consonant') |
aedc4d833eb0fc2070338ef92ed82bf90ed7a622 | yunieom/Study.2-Algorithm | /프로그래머스/lv1/42748. K번째수/K번째수.py | 299 | 3.765625 | 4 | def solution(array, commands):
answer = []
arr = []
for i in range(len(commands)):
num1 = commands[i][0]
num2 = commands[i][1]
num3 = commands[i][2]-1
arr = array[num1-1:num2]
arr.sort()
answer.append(arr[num3])
return answer |
b1531fd8b6ba35a322cddfcfd73e790516762d7f | manondesclides/ismrmrd-python-tools | /ismrmrd_to_nifti/flip_image.py | 366 | 3.640625 | 4 |
import numpy as np
def flip_image(img):
"""
Parameters
----------
img : image to flip and rotate to have the same orientation than the real nifti image
Returns
-------
flipped_img : the flipped image
"""
#permute all dimensions to have yxz order
img = img.transpose(1, 2, 0)
flipped_img = img
return flipped_img |
8af272d5a7ed8075724cde28d431fa1618dc736e | shalevy1/coldbrew | /src/examples/add.py | 422 | 3.8125 | 4 | import argparse
parser = argparse.ArgumentParser(description="calculate X + Y")
parser.add_argument("x", type=int, help="the first operand")
parser.add_argument("y", type=int, help="the second operand")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
answer = args.x+args.y
if args.verbose:
print("The answer to %d + %d is %d" % (args.x, args.y, answer))
else:
print(answer) |
8bee0fe382d9fe0f9520aba5e2ef861080f66476 | jshuster7484/VI-Viewer | /test.py | 498 | 3.546875 | 4 | #!/bin/python3
import sys
#a0, a1, a2 = input().strip().split(' ')
#a0, a1, a2 = [int(a0), int(a1), int(a2)]
#b0, b1, b2 = input().strip().split(' ')
#b0, b1, b2 = [int(b0), int(b1), int(b2)]
a0, a1, a2 = [1,2,3]
b0, b1, b2 = [1,4,1]
aliceScore = 0
bobScore = 0
def compare(a, b):
global aliceScore
global bobScore
if a > b:
aliceScore += 1
if b > a:
bobScore += 1
compare(a0, b0)
compare(a1, b1)
compare(a2, b2)
print(str(aliceScore) + " " + str(bobScore)) |
ee222cfec5964fab2209134abfdf4d809125dede | SuryakantKumar/Data-Structures-Algorithms | /Object Oriented Programming/Method-Overriding.py | 1,305 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 16:50:09 2020
@author: suryakantkumar
"""
class Vehicle:
def __init__(self, color, maxSpeed):
self.color = color
self.__maxSpeed = maxSpeed # private attribute
def print_vehicle(self):
print(self.color)
print(self.__maxSpeed)
class Car(Vehicle):
'''self.common_function() calls the child class first.
If the function is unavailable in child class then it searches in parent class.
It means if same function present in both of the classes then,
super().common_function() will override the child class common function.
'''
def __init__(self, color, maxSpeed, numGears, isConvertible):
super().__init__(color, maxSpeed) # Inheriting some properties from vehicle class
self.numGears = numGears
self.isConvertible = isConvertible
def print_vehicle(self):
# self.print_vehicle() # It is calling the Child class print_vehicle() function recursively
super().print_vehicle() # It is accessing Vehicle class i.e, super class print_vehicle() function
print(self.numGears)
print(self.isConvertible)
c = Car('Red', 240, 4, True)
c.print_vehicle() |
fce3ac790f278296a527c5c72e7e26808bf3bc68 | ColonelKASH/Image-Classifier | /untitled1.py | 1,835 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 3 00:00:21 2018
@author: hp
"""
#1 CREATING CNN
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
#initializing CNN
classifier = Sequential()
#Adding Convolutional Layers
classifier.add(Convolution2D(32,( 3, 3), input_shape = (64, 64, 3), activation = 'relu'))
#Max Pooling
classifier.add(MaxPooling2D(pool_size = (2,2)))
#Flatten
classifier.add(Flatten())
#Full Connection
classifier.add(Dense(output_dim = 64, activation = "relu"))
classifier.add(Dense(output_dim = 1, activation = "sigmoid"))
#compiling CNN
classifier.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy"])
#2 Fitting Images to CNN
from keras.preprocessing.image import ImageDataGenerator
Train_data_gen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
Test_data_gen = ImageDataGenerator(rescale = 1./255)
Train = Train_data_gen.flow_from_directory("New folder",
target_size = (64,64),
batch_size = 32,
class_mode = "binary")
Test = Test_data_gen.flow_from_directory("test",
target_size = (64,64),
batch_size = 32,
class_mode = "binary")
classifier.fit_generator(Train, samples_per_epoch = 71,
nb_epoch = 10,
validation_data = Test,
nb_val_samples = 9) |
c406189c6557e72b8b5fcf15182cc99275f8ed0b | umair3/pytorial | /basics/concat.py | 183 | 4.03125 | 4 | # Use plus sign to concat
stringA = "Hello"
stringB = "world!"
print(stringA + " " + stringB)
intA = 1
# print(stringA+intA), can only concat str to str
print(stringA + str(intA))
|
cd4fb79bdf161c93120ccf52c3d87cc9732e8a1b | Felipe017/intropython | /aula2.py | 1,046 | 3.515625 | 4 | import math as mate
print('Aula 2')
print('')
print('Exercicio 1')
print('')
largura = 17
altura = 12.0
delimitador = "."
print('largura/2 = ', largura/2)
print('Tipo do resultado',type(largura/2))
print('')
print('largura/2.0 = ', largura/2.0)
print('Tipo do resultado',type(largura/2.0))
print('')
print('altura/3 = ', altura/3)
print('Tipo do resultado',type(altura/3))
print('')
print('1+2*5 = ', 1+2*5)
print('Tipo do resultado',type(1+2*5))
print('')
print('delimitador*5 =',delimitador*5)
print('Tipo do resultado',type(delimitador*5))
print('')
print('Exercicio 2')
print('')
#help(mate)
mate.pi
r=5
v=(4/3)*pi*r**3
print('Volúme do cubo = ',v)
print('')
print('Exercicio 3')
print('')
l=24.95*0.4*60 #valor do custo do livro com desconto
e=3+59*0.75 #valor do custo de entrega
t=l+e #custo total
print('Custo total será de :R$',t)
print('')
print('Exercicio 4')
print('')
L=632.8*10**(-9)
D=1.98
d=0.250*10**(-3)
y=(D*L)/d
print('A distância entre dois máximos consecutivos será: ',y) |
aff0435bbd23e6a3df9528302bf52001b0c835b0 | flavio0567/DojoAssignments | /Python/FilterByType/FilterByType.py | 403 | 3.703125 | 4 | '''
Filter by Type '''
# Integer
sI = 45
if sI >= 100:
print("That's a big number!")
else:
print("that's a small number!")
# String
bS = "Tell me and I forget. Teach me and I remember. Involve me and I learn."
if len(bS) >= 50:
print("Long sentence.")
else:
print("Short sentence.")
# List
aL = [1,7,4,21]
if len(aL) >= 10:
print("Big list.")
else:
print("Short list.") |
e48d64c44a9442436fbbbfc203b62d44d73e1388 | citroen8897/Python_basic_hw | /lecon_sept/sort_list.py | 919 | 4 | 4 | def sort_ascending(x):
# вариант 1
# temp_2 = [j for j in range(len(x)) if x[j] == -1]
# x.sort()
# x = [j for j in x if j > 0]
# for q in temp_2:
# x.insert(q, -1)
# return x
# вариант 2
temp_1 = [j for j in x if j != -1]
temp_1.sort()
for i in range(len(x)):
if x[i] == -1:
temp_1.insert(i, -1)
return temp_1
test_1 = [-1, 150, 190, 170, -1, -1, 160, 180]
assert sort_ascending(test_1) == [-1, 150, 160, 170, -1, -1, 180, 190]
test_2 = [-1, -1, -1, -1, -1]
assert sort_ascending(test_2) == [-1, -1, -1, -1, -1]
test_3 = [4, 2, 9, 11, 2, 16]
assert sort_ascending(test_3) == [2, 2, 4, 9, 11, 16]
test_4 = [23, 54, -1, 43, 1, -1, -1, 77, -1, -1, -1, 3]
assert sort_ascending(test_4) == [1, 3, -1, 23, 43, -1, -1, 54, -1, -1, -1, 77]
test_5 = [-1]
assert sort_ascending(test_5) == [-1]
print("All tests passed successfully!")
|
a758e353acb0b2432f3f87bb46fabd2e94c1f75a | SpeddieSwagetti/CP1404_Practicals | /prac_01/electricity_bill_estimator.py | 374 | 4.09375 | 4 | """electricity bill estimator"""
price = float(input("Enter price in cents per kWh:"))
daily_use = float(input("Enter kWh usage per day:"))
num_of_days = int(input("Enter number of days in billing period:"))
estimated_bill = price * 0.01 * daily_use * num_of_days
print("Congradulations you millenials! Your bill is: {}. Maybe stop buying icecream".format(estimated_bill)) |
16258c39051e3c1c6be8aaa76c8a353db2b5dc18 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2627/40186/316228.py | 224 | 3.734375 | 4 | n = int(input())
for i in range(n):
a = input()
if a=='22 15':
print(3.02408)
elif a=='20 7':
print(0.66403)
elif a=='20 6':
print(0.48148)
elif a=='20 5':
print('0.33020') |
28114f6d4bb9fe9b40abbebe481dda49f6378592 | leonarita/Python | /Projetos/_Failed/GUI.py | 274 | 3.65625 | 4 | from tkinter import *
def clicked():
app.destroy()
app = Tk()
lab = Label(app, text="Write: ")
lab.grid(row=0, column=0)
en = Entry(app)
en.grid(row=0, column=1)
btn = Button(app, text='click here!', command=clicked)
btn.grid(row=1, columnspan=2)
app.mainloop()
|
24f0c4bb322343b551b71d6d3458c973d05a5598 | hasant99/Python-Class-Projects | /decrypter.py | 3,299 | 4.4375 | 4 | ###Author: Hasan Taleb
###Class: CSc110
###Description: A program that decrypts an
### encrypted file selected by the user.
### It first .combines the encrypted file and
### index files into a list in the order
### they are read. Then this program reorders
### the list numerically to decrypt the file
### and then reassembles the text in the right
### order and writes that information to a new_lst
### file called decrypted.txt.
def create_new_list(encrypted_file, index_file):
'''
This file uses a for loop to take the
information from encrypted_file and index_file
and assemble it into a list. The format of the list
is a line of the encrypted_file followed by it's
corresponding index from index_file.
encrypted_file: The file chosen by the user
that is already encrypted.
index_file: The file used as a key that contains
the indexes corresponding to the out of order lines
in the encrypted_file.
'''
encrypted_lst = []
text_file = open(encrypted_file, 'r')
key_file = open(index_file, 'r')
key_file = key_file.readlines()
i = 0
for line in text_file:
encrypted_lst.append(line.strip('\n'))
encrypted_lst.append((key_file[i]).strip('\n'))
i+=1
return encrypted_lst
def decode_list(encrypted_lst):
'''
This function takes the information from
encrypted_lst and uses a for loop to sort
the list in ascending numeric order. It then
removes the numeric value and adds the
reordered text to new_lst in order to
decrypt the file.
encrypted_lst: A list containing each line of the
encrypted_file followed by it's
corresponding index from index_file.
'''
new_lst= []
while len(encrypted_lst) > 0:
minimum = int(encrypted_lst[1])
for i in range(1, len(encrypted_lst), 2):
if int(encrypted_lst[i]) < minimum:
minimum = int(encrypted_lst[i])
new_lst.append(encrypted_lst[
(encrypted_lst.index(str(minimum)))-1])
encrypted_lst.remove(encrypted_lst[
(encrypted_lst.index(str(minimum)))-1])
encrypted_lst.remove(str(minimum))
return new_lst
def write_decrypted_file(decrypted_lst):
'''
This function takes the information
from decrypted_lst and writes it into
a new file named decrypted.txt.
decrypted_lst: A list containing the
lines from the encrypted file sorted
back into the original order.
'''
decrypted_file = open('decrypted.txt', 'w')
for i in range(0,len(decrypted_lst)):
line = str(decrypted_lst[i])
decrypted_file.write(line + '\n')
decrypted_file.close()
def main():
#Get the desired file to decrypt from the user
encrypted_file = input('Enter the name of' +
' an encrypted text file:\n')
#Get the associated index file from the user
index_file = input('Enter the name of' +
' the encryption index file:\n')
#Run appropriate functions to successfully decrypt file
create_new_list(encrypted_file, index_file)
encrypted_lst = create_new_list(encrypted_file, index_file)
decrypted_lst = decode_list(encrypted_lst)
write_decrypted_file(decrypted_lst)
main()
|
b9ebb5f6d0c4cc3e87bda12b0c3a22f381f87fbe | sevenbella/test | /python/3. 运算符.py | 453 | 3.828125 | 4 | # + - * / 加减乘除
a = 10
b = 20
c = a + b
print(c)
d = a * b
print(d)
e = a - b
print(e)
f = b / a
print(f)
# 取整除 //
a1 = 13
b1 = 3
c1 = a1 // b1
print(c1)
# 取模 取余数 % -- 判断奇偶性 如果对2取余数为0,该数则为偶数
left = 9
right = 2
result = left % right
print(result)
# 取幂 **
first = 5
second = 3
then = first ** second
print(then)
# 赋值运算符 =
a = 15
a += 15 # 等于 a = a + 10
print(a)
|
2ed75d99d9c401ba741032aa94367f20a68ee784 | cobalt-blue0626/The-Blackjack-Game | /hw4_p1.py | 5,212 | 3.671875 | 4 | continue_or_not="y"
while continue_or_not=="y":
rank=["ACE","2","3","4","5","6","7","8","9","10","JACK","QUEEN","KING"]#牌的大小
suit=["SPADE","HEART","DIAMOND","CLUB"]#牌的花色
deckcard=[]
for i in rank:#總共五十二張牌
for j in suit:
deckcard.append(i+"-"+j)
import random
random.shuffle(deckcard)#洗牌
index=random.randint(0,len(deckcard)-1)
card_number=[]
p_hand=[deckcard[0],deckcard[1]]
for card in p_hand:
card1=card.split("-")
card_number=card_number+[card1[0]]
total_number=0
for number in card_number:#判定抽到的兩張牌的大小總和
for n in rank:
if number==n:
if number=="KING" or number=="QUEEN" or number=="JACK":
total_number+=10
elif number=="ACE":
total_number+=11
else:
total_number+=int(n)
if total_number==21:#判定是否已經 blackjack
print("Your value is Blackjack! (21)")
print("Your current value is",total_number)
print("with the hand: "+", ".join(p_hand)+"\n")
i=0
use=0
while True and total_number!=21:
hit_or_stay=input("Hit or stay?(Hit = 1, Stay = 0):")#決定是否繼續抽牌
print()
while not (hit_or_stay=="0" or hit_or_stay=="1"):
print("Invalid input. Try again.")
hit_or_stay=input("Hit or stay?(Hit = 1, Stay = 0):")
print()
if hit_or_stay=="0":
break
if hit_or_stay=="1":
i=i+1
p_hand.append(deckcard[2+i])
card_h=deckcard[2+i].split("-")
card_number=card_number+[card_h[0]]
print("You draw",deckcard[2+i],"\n")
for n in rank:
if card_h[0]==n:
if card_h[0]=="KING" or card_h[0]=="QUEEN" or card_h[0]=="JACK":
total_number+=10
elif card_h[0]=="ACE":
total_number+=11
else:
total_number+=int(card_h[0])
while total_number>21 and card_number.count("ACE")>0 and (not use==card_number.count("ACE")):#判定手牌是否有么點
total_number-=10
use+=1
print("Your current value is",total_number)
if total_number>21:#判定是否已經爆牌
print("Your current value is Bust!(>21)")
print("with the hand: "+", ".join(p_hand)+"\n")
break
if total_number==21:#判定是否已經blackjack
print("Your value is Blackjack! (21)")
print("with the hand: "+", ".join(p_hand)+"\n")
break
print("with the hand: "+", ".join(p_hand)+"\n")
#============================================================================
card_number_d=[]
d_hand=[deckcard[2+i+1],deckcard[2+i+2]]
for card in d_hand:
card1=card.split("-")
card_number_d=card_number_d+[card1[0]]
total_number_d=0
for number in card_number_d:
for n in rank:
if number==n:
if number=="KING" or number=="QUEEN" or number=="JACK":
total_number_d+=10
elif number=="ACE":
total_number_d+=11
else:
total_number_d+=int(n)
if total_number_d==21:
print("Dealer's value is Blackjack! (21)")
print("Dealer's current value is",total_number_d)
print("with the hand: "+", ".join(d_hand)+"\n")
j=0
use=0
while total_number_d<17:#若莊家手牌小於十七,則繼續抽牌直到手牌大小大於等於十七為止
if True:
j+=1
d_hand.append(deckcard[2+i+2+j])
card_h=deckcard[2+i+2+j].split("-")
card_number_d=card_number_d+[card_h[0]]
print("Dealer draw",deckcard[2+i+2+j],"\n")
for n in rank:
if card_h[0]==n:
if card_h[0]=="KING" or card_h[0]=="QUEEN" or card_h[0]=="JACK":
total_number_d+=10
elif card_h[0]=="ACE":
total_number_d+=11
else:
total_number_d+=int(card_h[0])
while total_number_d>21 and card_number_d.count("ACE")>0 and (not use==card_number_d.count("ACE")):
total_number_d-=10
use+=1
print("Dealer's current value is",total_number_d)
if total_number_d>21:
print("Dealer's current value is Bust!(>21)")
print("with the hand: "+", ".join(d_hand)+"\n")
break
if total_number_d==21:
print("Dealer's value is Blackjack! (21)")
print("with the hand: "+", ".join(d_hand)+"\n")
break
print("with the hand: "+", ".join(d_hand)+"\n")
if total_number==21 and (not total_number_d==21):
print("****You beat the dealer !****")
elif total_number_d==21 and (not total_number==21):
print("****Dealer wins !****")
elif total_number>21 and total_number_d<=21:
print("****Dealer wins !****")
elif total_number_d>21 and total_number<=21:
print("****You beat the dealer !****")
elif total_number>21 and total_number_d>21:
print("****You tied the dealer. Nobody wins.****")
elif total_number==21 and total_number_d==21:
print("****You tied the dealer. Nobody wins.****")
elif total_number==total_number_d:
print("****You tied the dealer. Nobody wins.****")
elif total_number<21 and total_number_d<21:
p_difference=21-total_number
d_difference=21-total_number_d
if p_difference>d_difference:
print("****Dealer wins !****")
elif p_difference<d_difference:
print("****You beat the dealer !****")
print()
continue_or_not=input("Want to play again ? (y/n): ")#是否繼續遊玩
while not (continue_or_not=="y" or continue_or_not=="n"):
print("Invalid input. Try again.")
print()
continue_or_not=input("Want to play again ? (y/n): ")
if continue_or_not=="y":
print("===================================================")
print()
|
1a2eae5dbd63453d1885ee561d6652dc233309b5 | imsure/tech-interview-prep | /py/fundamentals/sorting/radix_sort.py | 942 | 3.96875 | 4 | def radix_sort(array):
"""
Radix sort on array of non-negative integers.
:param array:
:return:
"""
if not array:
return []
max_key_len = len(str(max(array)))
array = [str(n)[::-1] for n in array]
sorted_array = array
for i in range(max_key_len):
buckets = {str(i): [] for i in range(10)}
for num in sorted_array:
try:
digit = num[i]
except IndexError:
digit = '0'
buckets[digit].append(num)
tmp = []
for key in range(10):
tmp += buckets[str(key)]
sorted_array = tmp
sorted_array = [int(n[::-1]) for n in sorted_array]
return sorted_array
print(radix_sort([12, 42, 9, 0, 78, 46, 45, 45]))
print(radix_sort([1, 2, 3, 4, 5]))
print(radix_sort([5, 4, 3, 2, 1]))
print(radix_sort([1000, 299, 39, 4556, 9, 538, 4, 90]))
print(radix_sort([1, 10, 100, 1000, 1111])) |
e0e93e77df2c2c20b18bcb53f7a395f72598004c | niushufeng/Python_202006 | /算法代码/面向对象/模块/模块的开发原则/__name__模块.py | 720 | 3.890625 | 4 | # 可以提供全局变量、函数、类, 注意:直接执行的代码不是向外界提供的工具
# 开发原则-- ,每一个文件都是应该可以被导入的
# 一个独立的python 文件就是一个模块
# 在导入文件时, 文件中所有没有任何缩进的代码都会被执行一遍
# 导入模块
# 定义全局变量
# 定义类
# 定义函数
# 在代码的最下方
def say_hello():
print("你好你好,我是 say hello ")
# 如果直接执行模块,得到的值永远是__main__
if __name__ == "__main__":
print(__name__)
# 文件被导入时,能够执行的代码不需要被执行
print("小明开发的模块") # 增加 if 下面的缩进
say_hello()
|
836207c3db3a9d7a5212b24e3d559b83c8d70252 | DigitalCrafts/gists | /Data_Analytics/python training/logical expressions/class exercise solutions/hello-world-multi-non-blank.py | 505 | 4.1875 | 4 | user_input_name = input("Enter a name: ")
length_of_name = len(user_input_name)
if length_of_name > 0:
user_input_place = input("Enter a place: ")
length_of_place = len(user_input_place)
if length_of_place > 0:
message = "Hello, %s! Welcome to %s!" % (user_input_name, user_input_place)
else:
message = "Sorry, %s. We need a place to complete the welcome message :(" % user_input_name
else:
message = "No name entered - cannot print welcome message :("
print(message) |
65e595b5d9aa1b1deb8b4f588e68dcbf5c2b6f97 | GrindelfP/preparing_to_exam | /task_17/17_03_28.py | 587 | 3.59375 | 4 | count = 0
summary = ""
max_good = None
def binar(num) -> int:
num = bin(num)
num = num.replace("0", "", 1)
num = int(num.replace("b", "", 1))
return num
def digits_sum(num) -> int:
sum = 0
while num > 1:
digit = num - num // 10 * 10
sum = sum + digit
num = num // 10
sum = sum + num
return sum
for i in range(31, 2047+1):
number = binar(i)
last_digit = number - number//10*10
if last_digit == 0 and digits_sum(number) == 5 and i % 10 != 0:
count = count + 1
max_good = i
print(count, max_good)
|
2c15acd1289edc33d0915dbfcfe809e1e9ef1e36 | PranshuRaj/PyBattery1.2 | /PyBattery1.2/main.py | 4,423 | 3.828125 | 4 | # python script showing battery details
# If you do not have psutil, pygame module you can install with using pip in Terminal
import psutil # (pip install psutil)
import time
from win10toast import ToastNotifier
toaster = ToastNotifier()
# function returning time in hh:mm:ss
def convertTime(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return "%d:%02d:%02d" % (hours, minutes, seconds)
battery = psutil.sensors_battery()
battery_life = battery.percent
battery_percentage = str(battery_life) + "%"
battery_list = list(battery)
print("Your current battery status:- ", battery_percentage)
if battery_list[2]: # checking if power plugged on.
print("Charger Plugged IN!!")
while battery_life < 100:
if battery_life <= 20:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for 1 Hour ".format(battery_percentage))
time.sleep(3600) # 3600 seconds means 1 Hour
elif 20 < battery_life <= 40:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for 45 minutes ".format(battery_percentage))
time.sleep(2700) # 1800 seconds means half an hour
elif 41 <= battery_life <= 50:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for Half an Hour ".format(battery_percentage))
time.sleep(1800) # 1800 seconds means half an hour
elif 51 <= battery_life <= 60:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for 25 minutes ".format(battery_percentage))
time.sleep(1500) # 1500 seconds means 25 minutes
elif 61 <= battery_life <= 80:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for 20 minutes ".format(battery_percentage))
time.sleep(1200) # 1200 seconds means 20 minutes
elif 81 <= battery_life <= 90:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for 10 minutes ".format(battery_percentage))
time.sleep(600) # 600 seconds means 10
elif 91 <= battery_life <= 95:
battery = psutil.sensors_battery()
battery_life = battery.percent
print("Your battery is {} charged, going for sleep for 7 minutes ".format(battery_percentage))
time.sleep(420) # 420 minutes means 7 minutes
elif 96 <= battery_life <= 98:
battery = psutil.sensors_battery()
battery_life = battery.percent
print(" Battery will full charge soon")
print("Your battery is {} charged, going for sleep for 2 minutes ".format(battery_percentage))
time.sleep(120) # 120 seconds means 2 minutes
elif battery_life == 99:
battery = psutil.sensors_battery()
battery_life = battery.percent
print(" Battery will full charge soon")
print("Your battery is {} charged, going for sleep for 2 minutes ".format(battery_percentage))
time.sleep(30) # 120 seconds means half a minutes
else:
print("Your battery is {} charged, going for sleep fo 2 minutes".format(battery_percentage))
time.sleep(120)
battery = psutil.sensors_battery()
battery_life = battery.percent
else:
print("Battery percentage : ", battery.percent)
toaster.show_toast("PyBattery", "Battery full charged", threaded=True, icon_path=None, duration=3)
if battery.power_plugged:
print("Please Unplug the charger")
else:
print()
# converting seconds to hh:mm:ss
print("Battery left : ", convertTime(battery.secsleft))
print("full charge")
else:
print("Plug In your charger than rerun the program")
while True:
continue
author = "Pranshu raj"
|
643eb9317bf145386fb377fc20295ad7de9a8348 | ICANDIGITAL/crash_course_python | /chapter_8/large_shirts.py | 311 | 4.0625 | 4 | def make_shirt(text='i love python', size='large'):
"""Displays the size and text printed on the shirt."""
print("The selected shirt is a size " + size.lower() + " with a text of: "
+ text.title() + ".")
make_shirt()
make_shirt('i love python','medium')
make_shirt('top of the world ma', 'grande')
|
be020b5de8be2481d03de0eb936179cb1c567b93 | puzzz21/covid-19-data-visualization | /Covid 19 visualization.py | 1,480 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# WHO COVID 19 data visualization using matplotlib
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.axes.Axes as ax
import statsmodels.api as sm
import seaborn as sns
sns.set()
# In[2]:
fullData = pd.read_csv("https://covid.ourworldindata.org/data/ecdc/full_data.csv")
fullData.head()
def plotCountries(location):
locationIndex = fullData.location.str.contains(location)
#Total Cases
totalCases = list(dict(fullData[locationIndex]["total_cases"]).values())
dates = list(dict(fullData[locationIndex]["date"]).values())
xAxisData = dates[0:len(dates): int(len(dates)/ 7) if dates else 30 ]
fig, ax = plt.subplots()
ax.plot(totalCases)
plt.suptitle(location)
ax.set_title("TOTAL CASES")
plt.xlabel("dates")
plt.ylabel("population")
ax.set_xticklabels(xAxisData, rotation = 45)
#New Cases and Death Count
newCases = list(dict(fullData[locationIndex]["new_cases"]).values())
newDeaths = list(dict(fullData[locationIndex]["new_deaths"]).values())
fig, ax = plt.subplots()
ax.plot(newCases, label = "new cases")
ax.plot(newDeaths, label = "deaths")
plt.legend()
plt.suptitle(location)
ax.set_title("New cases and deaths")
plt.xlabel("dates")
plt.ylabel("population")
ax.set_xticklabels(xAxisData, rotation = 45)
list(map(plotCountries, list(fullData.groupby("location").groups))) |
af5aaecfc365941a9fd47bd6cb50ff270af9995c | Shin-jay7/LeetCode | /0402_remove_k_digits.py | 356 | 3.53125 | 4 | from __future__ import annotations
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
digits = []
for digit in num:
while k and digits and digits[-1] > digit:
digits.pop()
k -= 1
digits.append(digit)
return "".join(digits[:-k or None]).lstrip("0") or "0"
|
b0ba166c29bf75e8112079a7d17007a018fb02a8 | xiaolinangela/cracking-the-coding-interview-soln | /Ch3-StacksAndQueues/3.6-AnimalShelter.py | 1,049 | 3.90625 | 4 | from LinkedList import LinkedList
from LinkedList import LinkedListNode
class AnimalShelter:
def __init__(self):
self.dog = LinkedList()
self.cat = LinkedList()
self.order = 0
def enqueue(self,animal,type):
if type == "dog":
self.dog.add([animal],"dog",self.order)
self.order += 1
else:
self.cat.add([animal], "cat", self.order)
self.order += 1
def dequeue_any(self):
if self.dog.head.order < self.cat.head.order:
self.dog.head = self.dog.head.next
else:
self.cat.head = self.cat.head.next
def dequeue_dog(self):
self.dog.head = self.dog.head.next
def dequeue_cat(self):
self.cat.head = self.cat.head.next
if __name__ == "__main__":
a = AnimalShelter()
a.enqueue("dog1", "dog")
a.enqueue("cat1","cat")
a.enqueue("dog2","dog")
a.dog.printNode()
a.cat.printNode()
a.dequeue_any()
a.dequeue_dog()
a.dog.printNode()
a.cat.printNode()
|
f742000fef7316430be53c63a1f6819fa8206779 | kyasui/python_lab | /main.py | 2,281 | 4 | 4 | """Rock Paper Scissors"""
from random import randint
class Player:
def __init__(self, is_human=False):
self.is_human = is_human
def play(self):
if self.is_human == False:
return randint(0,2)
else:
is_recognized_input = False
while is_recognized_input == False:
play = raw_input('ROCK, PAPER or SCISSORS? ')
play = play.lower()
if play == 'rock':
is_recognized_input = True
return 0
elif play == 'paper':
is_recognized_input = True
return 1
elif play == 'scissors':
is_recognized_input = True
return 2
else:
print('Unrecognized play... Try again...')
class Game:
def __init__(self, player_one, player_two):
self.player_one = player_one
self.player_two = player_two
self.choices = {
0: 'Rock',
1: 'Paper',
2: 'Scissors',
}
def start(self):
winner = False
while winner == False:
player_one_score = self.player_one.play()
player_two_score = self.player_two.play()
if player_one_score != player_two_score:
print 'Player One chose ' + self.choices[player_one_score]
print 'Player Two chose ' + self.choices[player_two_score]
result = self.determine_winner(self.choices[player_one_score], self.choices[player_two_score])
print(result)
winner = True
playagain = raw_input('Play Again? Y/N ').lower()
if (playagain == 'y'):
self.start()
else:
print 'Tie, Go Again.'
def determine_winner(self, player_one_play, player_two_play):
if player_one_play == 'Rock':
if player_two_play == 'Paper':
return 'Player One Loses!'
elif player_two_play == 'Scissors':
return 'Player One Wins!'
elif player_one_play == 'Scissors':
if player_two_play == 'Rock':
return 'Player One Loses!'
elif player_two_play == 'Paper':
return 'Player One Wins!'
elif player_one_play == 'Paper':
if player_two_play == 'Scissors':
return 'Player One Loses!'
elif player_two_play == 'Rock':
return 'Player One Wins!'
if __name__ == '__main__':
game = Game(Player(is_human=True), Player(is_human=False))
game.start() |
d35ffabcd7f1863d68b80d7accb2ab5d0d6f7a25 | bhaktijkoli/python-training | /example11.py | 227 | 4.09375 | 4 | def checkPrime(x):
for i in range(2, x):
if x % i == 0:
print("Not a prime number")
break;
else:
print("Print number")
x = int(input("Enter any number\n"))
checkPrime(x) |
9eda5983a75b5e8e381a1812999172d6670acd85 | lucascv/Python | /PycharmProjects/guppe/sec7_p1_ex16.py | 310 | 3.859375 | 4 | A = []
cont = 0
while cont < 5:
A.append(float(input('Digite um valor: ')))
cont = cont + 1
codigo = int(input('Digite o código: '))
if codigo == 1:
print(A)
elif codigo == 2:
A.reverse()
print(A)
elif codigo == 0:
print('Fim.')
else:
print('Codigo inválido.')
|
f53955ba654339dbef22693d261860b21d1bc503 | hanrosen/206-final-project | /date.py | 3,765 | 3.78125 | 4 | def date_conversion(date):
split = date.split()
year = str(date.split()[-1])
if "January" in date:
month = '01'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "February" in date:
split = date.split()
month = '02'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "March" in date:
split = date.split()
month = '03'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "April" in date:
split = date.split()
month = '04'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "May" in date:
split = date.split()
month = '05'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "June" in date:
split = date.split()
month = '06'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "July" in date:
split = date.split()
month = '07'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "August" in date:
split = date.split()
month = '08'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "September" in date:
split = date.split()
month = '09'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "October" in date:
split = date.split()
month = '10'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "November" in date:
split = date.split()
month = '11'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
elif "December" in date:
split = date.split()
month = '12'
if len(split[1]) == 4:
day = '0' + split[1][0]
release = "{}-{}-{}".format(year, month, day)
else:
day = split[1][:2]
release = "{}-{}-{}".format(year, month, day)
# else:
# release = None
return release
date_conversion("December 12nd, 2017")
|
8826a67eb7e86248a2ce567fafa34d2d084ee9d8 | maxmyth01/unit1 | /stringAnalysis.py | 787 | 4.15625 | 4 | #Max Low
#9-1-17
#stringAnalysis.py - Studies a sentance and counts the amount of words letter and scans for a letter and word
sentance = input('Enter a Sentance')
sentance = sentance.upper()
space = (' ')
totalWords= (sentance.count(space)+1)
totalCharactures = len(sentance)
totalLetters = (totalCharactures-totalWords-1)
print('Your sentance has', totalWords ,'words and', totalCharactures ,'characters and', totalLetters ,'letters')
letter = input('Enter a character to search for:')
letter = letter.upper()
selectLetter = sentance.count(letter)
print('Your sentance has', selectLetter ,'of the character',letter)
word = input('Enter a word to search for:')
word = word.upper()
selectWord = sentance.count(word)
print('Your sentance has', selectWord ,'of the word',word)
|
c2f47c69e1d85f5e5a7249b8482039a28e42383c | roshan-shahi/basicpython | /assignment.py | 294 | 3.65625 | 4 | v=25
u=0
t=10
a=(v-u)/t
print(a)
f_name=input"(enter first name")
l_name=input("enter last name")
full name=f_name+" "+l_name
print(full_name)
#question 3
user_input=(input("enter something")
print(user_input +10)
#question 4
print(type(4))
print(str(45))
print(eval("2+3")
|
13145c8d90d36f5915ce4ddca79d74f1142b91e9 | abecus/Queues | /pyqueues/heap.py | 1,338 | 3.65625 | 4 | def heapify(arr: list, *, i: int=None) -> None:
def helper(i):
# goes from parent to the child (down)
"""
comparing children and spawing parent to min of children if exist,
and doing same on swapped parent node
"""
while i<nTillLastRow:
ch1 = 2*i +1
try:
if arr[ch1]>arr[ch1+1]: ch1 += 1
except: pass
if arr[ch1]<arr[i]:
arr[i], arr[ch1] = arr[ch1], arr[i]
i=ch1
continue
break
nTillLastRow = len(arr)//2
if i!=None:
helper(i)
return
for i in reversed(range(nTillLastRow)):
# main heapify call
helper(i)
def heapPush(heapArr: list, val: int) -> None:
"inserts the given element into the heap Array"
heapArr.append(val)
i = len(heapArr)-1
while i>0:
parent = i-1 //2
if heapArr[parent]>heapArr[i]:
heapArr[parent], heapArr[i] = heapArr[i], heapArr[parent]
i = parent
continue
break
def heapPop(heapArr: list) -> "element":
"returns min element from Array (heap)"
heapArr[0], heapArr[-1] = heapArr[-1], heapArr[0]
toReturn = heapArr.pop()
heapify(heapArr, i=0) # relaxing
return toReturn
if __name__ == "__main__":
temp = [16, 4, 10, 14, 7, 9, 3, 2, 8, 1, 2, 3]
# temp = [10, 20, 15, 12, 40, 25, 18, 40]
# temp = [9,8,5,6,2,3,4,1]
heapify(temp)
heapPush(temp, 0)
print("temp", temp)
print([heapPop(temp) for _ in range(len(temp))])
|
4f3122886e73268be07b9d8f6e2cc3c151f0701b | xdkernelx/fundamentals_of_cs | /interactive_python_p1/guess_the_number.py | 2,858 | 4.125 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui, random, math
secret_number = 0
secret_range = 100
guesses = 0
message = "Welcome!"
# helper function to start and restart the game
def new_game():
"""
Even though it doesn't matter in the given ranges
We subtract one since the upper number is not
included as a possible answer. [0. range)
"""
global secret_number, guesses
secret_number = random.randrange(0,secret_range)
guesses = int(math.ceil(math.log(secret_range - 1) / math.log(2)))
frame.set_draw_handler(draw)
print "The range is 0 to", secret_range
return None
def decrement():
global guesses
guesses -= 1
return None
def validate(guess):
try:
int(guess)
return int(guess)
except ValueError:
print "Oops! That was not a valid number. Try again..."
return None
def print_screen(flag, guess):
# -1 is lower, 0 is equal, 1 is higher
global message
print "Guess was", guess
print "Number of guesses left:", guesses
if flag == -1:
print "Lower!"
message = "Lower!"
elif flag == 0:
print "Correct!"
message = "Good Job!"
elif flag == 1:
print "Higher!"
message = "Higher!"
else:
message = "Error!"
print "Something weird happen. Our top coding monkeys are on it."
frame.set_draw_handler(draw)
return None
# define event handlers for control panel
def range100():
global secret_range
secret_range = 100
new_game()
return None
def range1000():
global secret_range
secret_range = 1000
new_game()
return None
def draw(canvas):
canvas.draw_text(message, [50,112], 48, "Red")
def input_guess(guess):
# main game logic goes here
guess = validate(guess)
if guess is not None:
decrement()
if guess < secret_number:
print_screen(1, guess)
elif guess == secret_number:
print_screen(0, guess)
else:
print_screen(-1, guess)
if guesses == 0:
print "\nYou are out of guesses"
print "Starting new game... \n"
new_game()
# create frame
frame = simplegui.create_frame("Guess the number!", 300, 200)
# register event handlers for control elements and start frame
frame.add_button("Range is 1K", range1000, 200)
frame.add_button("Range is 1C", range100, 200)
frame.add_input("Add a guess", input_guess, 200)
frame.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
|
0b7240eb61885f354ee22282ace2166661e0374a | chjdm/PythonCrashCourse | /learning_complete/dream_resort.py | 467 | 3.875 | 4 | dream_resorts = {}
active = True
while active:
name = input("Thank you for take in the poll, what's your name, please?")
resort = input("If you could visit one place in the world, where would you go?")
dream_resorts[name] = resort
repeat = input("Would you like to take another poll?(yes/no)")
if repeat == "no":
active = False
for name, resort in dream_resorts.items():
print(name.title() + " like go to " + resort.title() + ".") |
3f75d473f0522f86bd5f578f44bb1e2be41059bf | kemingy/daily-coding-problem | /src/prefix_map_sum.py | 1,412 | 3.953125 | 4 | # Implement a PrefixMapSum class with the following methods:
# • insert(key: str, value: int): Set a given key's value in the map.
# If the key already exists, overwrite the value.
# • sum(prefix: str): Return the sum of all values of keys that begin with
# a given prefix.
# For example, you should be able to run the following code:
# mapsum.insert("columnar", 3)
# assert mapsum.sum("col") == 3
# mapsum.insert("column", 2)
# assert mapsum.sum("col") == 5
class Char:
def __init__(self, char, value=0):
self.char = char
self.value = value
self.next = {}
class PrefixMapSum:
def __init__(self):
self.premap = {}
def insert(self, key, value):
premap = self.premap
for char in key:
if char not in premap:
premap[char] = Char(char)
premap[char].value += value
premap = premap[char].next
def sum(self, prefix):
premap = self.premap
value = 0
for char in prefix:
if char not in premap:
return value
value = premap[char].value
premap = premap[char].next
return value
if __name__ == '__main__':
mapsum = PrefixMapSum()
mapsum.insert('columnar', 3)
assert mapsum.sum('col') == 3
mapsum.insert('column', 2)
assert mapsum.sum('col') == 5
|
82b50e1c6ba982ba840a70206ab157bcf7d0552d | newfull5/SW-Expert-Academy | /2025. N줄덧셈.py | 80 | 3.640625 | 4 | n = int(input())
temp = 0
for i in range(0,n+1):
temp += i
print(temp)
|
98eb14f1737d85be3a3a5477c7eef01e67d812b7 | bond400apm/MetroHasting | /lib/pdfs.py | 1,048 | 3.53125 | 4 | import numpy as np
import math
# This defines a Gaussian pdf with mean value "a" and standard deviation 1
def gauspdf(x,a):
'''
input:x function variable(float)
input:a Gaussian mean(float)
output: The corrsponding value of x for the given Guassian mean(float)
'''
N = np.sqrt(np.log(a)/(2*np.pi))
P = N*math.pow(a,-1*x*x/2)
return P
#This estimate the likelihhod of a parameter value for a given function and data set
def likelihood(funcs,parameter,*data):
'''
input:funcs The single sample probability function(float)
input:parameter The parameter need to be estimated(float)
input:*data The given data set to estimate the likelihood(list or any number of float)
output: likelihood(float)
'''
L = 1
for x in data[1:]:
L = L+np.log(funcs(x,parameter))
return L
#This function transfers a likelihood to a Bayesian posterior
def posterior(a,like,funcs,prior=1.0,normalization=1.0,*data):
P = np.exp(like(funcs,a,*data))*prior/normalization
return P
|
c2cbbe84babd60c1e5c7f52920552fd0da142d3f | MATATAxD/untitled1 | /10.22/计数排序.py | 454 | 3.640625 | 4 | from typing import List
from randomList import randomList
def countSort(List):
if len(List) <= 1:
return List
maxv = max(List)
count_list = [0] * (maxv + 1)
for i in range(len(List)):
count_list[List[i]] += 1
sort_list = []
for i in range(len(count_list)):
for j in range(count_list[i]):
sort_list.append(i)
return sort_list
l = [1, 1, 2, 4, 4, 2, 3, 5, 7, 8, 9, 8]
print(countSort(l))
|
22cd8e457c474f9b9dbbcdf16f023769393f0175 | Artem-max-eng/lesson1 | /dtypes.py | 396 | 3.859375 | 4 | a = input("Как вас зовут? ")
print(f'Пошел нахуй, {a}!')
b = int(input("Сколько вам лет? "))
if (b < 18):
print('Не получилось, не фартануло(')
elif (b > 18):
print('Welcome to the club, buddy!')
else:
print(f'Неплохо тебя жизнь поматала, я в свои {b} еще в горшок ходил...')
|
fcb7da07131c68db22ca06f808757e4babf2db79 | coreyarch1234/Tweet-Generator | /random-dict/main.py | 1,319 | 3.96875 | 4 | #The goal is to take the words text file and create a program that takes in an integer representing
#a number of words, n, takes a random set and outputs that set in a sentence (grammar/sentence structure does not matter)
#Handles reading text file
def read_in(word_text):
words = open(word_text, 'r')
word_list = words.readlines()
for i in word_list:
thisline = i.split(" ")
return thisline
#Handles reading input from user
num_count = int(raw_input())
import random
import sys
def make_list(word_list):
this_line = read_in(word_list)
word_list = []
for word in this_line:
word_list.append(word)
return word_list
def random_list(a):
b = []
temp_word = ""
length = len(a)
for i in range(len(a)):
rand_num = random.randint(0, length - 1)
random_word = a[rand_num]
a.remove(random_word)
b.append(random_word)
length -= 1
return b
def random_sequence(num_count, word_list):
array = []
return_array = []
random = make_list(word_list)
for rand in random_list(random):
array.append(rand)
for count in range(0, num_count):
return_array.append(array[count])
print(return_array)
if __name__ == '__main__':
random_sequence(num_count, 'words.txt')
|
00c2578b02e0d96648a494620210693e5f5cc0d1 | Rylan12/Project-Euler | /solved/p51.py | 3,183 | 3.75 | 4 | from math import sqrt
from solved.p27 import is_prime
from solved.p46 import get_primes
def list_primes(start, stop):
result = [True for _ in range(stop)]
result[0], result[1] = False, False
for i in range(round(sqrt(stop) + 1)):
if result[i]:
for j in range(i * i, len(result), i):
result[j] = False
return [i for (i, is_prime) in enumerate(result) if is_prime and i > start]
def is_eight_prime_value_family(num):
num = str(num)
for first in range(len(num)):
for second in range(first + 1, len(num)):
total = 0
for replacement in range(10):
new_num = num[:first] + str(replacement) + num[first + 1: second] + str(replacement) + num[second + 1:]
# print(new_num)
if is_prime(int(new_num)):
total += 1
if total == 8:
return True
return False
def is_8_prime_value_number(number, indices):
# print_the_thing = number == 121313
prime_count = 0
not_prime = 0
number = str(number)
for i in range(10):
for j in indices:
number = number[:j] + str(i) + number[j + 1:]
if is_prime(int(number)) and number[0] != '0':
# if print_the_thing:
# print(number)
prime_count += 1
else:
not_prime += 1
if not_prime >= 3:
return False
return prime_count == 8
def get_replaceable_digits(number):
number = str(number)
digits = [number[i] for i in range(len(number))]
duplicates = []
for d in ['0', '1', '2']:
current = [d, 0, []]
for i in range(len(digits)):
if digits[i] == d:
current[1] += 1
current[2].append(i)
if current[1] > 1:
duplicates.append(current)
return duplicates
def get_lowest_prime_with_pattern(num, indices_to_ignore):
num = str(num)
indices_to_save = []
for i in range(len(num)):
if i not in indices_to_ignore:
indices_to_save.append(i)
primes = list_primes(10 ** (len(num) - 1), 10 ** len(num))
for prime in primes:
prime = str(prime)
for i in indices_to_save:
if prime[i] != num[i]:
break
else:
return prime
return False
if __name__ == '__main__':
# Length of number
for n in range(4, 10):
# List of primes of give length
primes = list_primes(10 ** (n - 1), 10 ** n)
# print(primes)
for prime in primes:
replaceable = get_replaceable_digits(prime)
for i in replaceable:
if is_8_prime_value_number(prime, i[2]):
print(prime)
# print(get_lowest_prime_with_pattern(prime, i[2]))
quit(0)
# Stopped at 5310001
# primes = get_primes(100, 10000000)
# print(primes)
# for i in range(200001, 10000000, 2):
# if is_prime(i):
# if is_eight_prime_value_family(i):
# print(i)
# break
# if i % 1000 == 1:
# print(i)
|
de3f0b2d8ff4066e7d02882a4eb8c5f0f0b3b9fe | yanfriend/python-practice | /variables/class_obj.py | 816 | 3.5625 | 4 | class TestClass(object):
c = 299792458 #this is a class variable
def __init__(self):
self.e = 2.71 #instance variable
def phiFunc(self):
self.phi = 1.618 #will become an instance variable after phiFunc is called
x=224 #this is a method variable and can't be accessed outside this method
assert TestClass.c == 299792458
try:
print TestClass.e #Not defined
except AttributeError:
pass
testInst = TestClass()
assert testInst.c == 299792458 #instance gets c, currently a ref to the class var
assert testInst.e == 2.71 #got e because of __init__
try:
print testInst.phi #error since not defined yet
except AttributeError:
pass
testInst.phiFunc()
assert testInst.phi == 1.618 #now its here
try:
testInst.x #still undefined
except AttributeError:
pass
|
fc0301fc1de493a983e1853355453bc23e3276e2 | Cuize/data-structures-and-algorithms | /quicksort/main.py | 1,322 | 3.921875 | 4 | nums=input("input nums with . to separate")
try:
nums=[int(x) for x in nums.split(".")]
except:
nums=nums.split(".")
print(f"your input is {nums}")
print("*"*10)
choice=input("find kth smallest element or simply sort the array? (enter 0 for kth smallest element 1 for sorting)")
while choice not in "01":
choice=input("find kth smallest element or simply sort the array? (enter 0 for kth smallest element 1 for sorting)")
if choice=="1":
print("Now run quicksort")
from quicksort import quicksort
quicksort(nums)
print("*"*10)
print("\n")
print(f"sorted nums: {nums}")
else:
print("Now find the kth smallest element")
print("\n")
k=int(input("please input the value of k"))
from findkthsmall import findkthsmall
ans=findkthsmall(nums,k)
if k==1:
print("*"*10)
print("\n")
print(f"the smallest element of {nums} is {ans}")
print("\n")
print("*"*10)
elif k==2:
print("*"*10)
print("\n")
print(f"the 2nd smallest element of {nums} is {ans}")
print("\n")
print("*"*10)
elif k==3:
print("*"*10)
print("\n")
print(f"the 3rd smallest element of {nums} is {ans}")
print("\n")
print("*"*10)
else:
print("*"*10)
print("\n")
print(f"the {k}th smallest element of {nums} is {ans}")
print("\n")
print("*"*10)
|
948bff87c6165853e7f6f59c5e1c54c559d8a2cb | bevisLee/portfolio | /Pythonproject/about_python/abuout_python_0909_numpy.py | 2,317 | 3.984375 | 4 | import numpy as np
L = list(range(10))
L
L2 = [str(c) for c in L]
L2
type(L2[0])
L3 = [True, "2", 3.0, 4]
L3
[type(item) for item in L3]
import array
L = list(range(10))
A = array.array('i', L)
A
# integer array:
np.array([1, 4, 2, 5, 3])
np.array([3.14, 4, 2, 3])
np.array([1, 2, 3, 4], dtype='float32')
# nested lists result in multi-dimensional arrays
np.array([range(i, i + 3) for i in [2, 4, 6]])
# Create a length-10 integer array filled with zeros
np.zeros(10, dtype=int)
# Create a 3x5 floating-point array filled with ones
np.ones((3, 5), dtype=float)
# Create a 3x5 array filled with 3.14
np.full((3, 5), 3.14)
# Create an array filled with a linear sequence
# Starting at 0, ending at 20, stepping by 2
# (this is similar to the built-in range() function)
np.arange(0, 20, 2)
# Create an array of five values evenly spaced between 0 and 1
np.linspace(0, 1, 5)
# Create a 3x3 array of uniformly distributed
# random values between 0 and 1
np.random.random((3, 3))
# Create a 3x3 array of normally distributed random values
# with mean 0 and standard deviation 1
np.random.normal(0, 1, (3, 3))
# Create a 3x3 array of random integers in the interval [0, 10)
np.random.randint(0, 10, (3, 3))
# Create a 3x3 identity matrix
np.eye(3)
# Create an uninitialized array of three integers
# The values will be whatever happens to already exist at that memory location
np.empty(3)
import numpy as np
np.random.seed(0) # seed for reproducibility / 동일한 값이 출력되도록 고정
x1 = np.random.randint(10, size=6) # One-dimensional array
x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array
print("x3 ndim: ", x3.ndim)
print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)
print("dtype:", x3.dtype)
print("itemsize:", x3.itemsize, "bytes")
print("nbytes:", x3.nbytes, "bytes")
x1
x1[0]
x1[4]
x1[-1]
x1[-2]
x2
x2[0, 0]
x2[2, 0]
x2[2, -1]
x2[0, 0] = 12
x2
x1[0] = 3.14159 # this will be truncated!
x1
x = np.arange(10)
x
x[:5] # first five elements
x[5:] # elements after index 5
x[4:7] # middle sub-array
x[::2] # every other element
x[1::2] # every other element, starting at index 1
x[::-1] # all elements, reversed
x[5::-2] # reversed every other from index 5
x2
|
fdda3cc80293b04b785fb99be0d3b8e9d0485f4d | ursueugen/Rosalind_Bioinformatics_Problems | /Enumerate_Gene_Orders/gene_orders.py | 913 | 3.96875 | 4 | n = 5
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return factorial(n-1) * n
def all_permutations(n):
permutations = []
# elements of list
elements = list(map(str, range(1, n+1)))
#permutations.append(elements) # first, natural ordering
# initialization
for e in elements:
permutations.append(e)
# grow
for _ in range(n-1):
new_permutations = []
for perm in permutations:
for e in elements:
if e not in perm:
new_permutations.append(perm+e)
else:
pass
permutations = new_permutations[:]
assert len(permutations) == factorial(n)
return permutations
permutations = all_permutations(n)
print(len(permutations))
for perm in permutations:
print(" ".join(list(perm))) |
84968c0de10f36b4b3146b9f64133de27f107d37 | jlunder00/blocks-world | /world.py | 4,175 | 4.03125 | 4 | '''
Programmer: Jason Lunder
Class: CPSC 323-01, Fall 2021
Project #4 - Blocks world
9/30/2021
Description:
This is an object representing the world that blocks live in. It has a set of locations and blocks distributed in those locations, according to the number of places and number of blocks passed in in the init function. It can add blocks to the world, generate a set of valid moves for the current board state, move blocks between locations, check to see if the victory conditions have been met and print a representation of the board.
'''
import random, location, block
class BlockWorld:
def __init__(self, num_places, num_blocks):
self.num_places = num_places
self.num_blocks = num_blocks
self.locations = [location.Location() for i in range(self.num_places)]
self.add_blocks()
while(self.check_victory_condition()):
self.add_blocks()
def add_blocks(self):
"""
Add all of the blocks in the range of possible block ids to random locations in the block world
Parameters
----------
Returns
"""
for i in range(self.num_blocks):
j = random.randint(0, self.num_places-1)
self.locations[j].place_block(block.Block(i, True))
def move_block(self, oldLocation, newLocation):
"""
Move a block from one location to another
Parameters
----------
oldLocation : the index within the locations list of the location to take the block from
newLocation : the index within the locations list of the location to add the block to
Returns
"""
block_in_transit = self.locations[oldLocation].remove_block()
self.locations[newLocation].place_block(block_in_transit)
def valid_moves(self):
"""
Generate all possible legal moves in the current position
Parameters
----------
Returns
A list of all the possible moves as a list of tuples where the first index is the old location and the second is the new location
"""
moves = []
for i in range(len(self.locations)):
if len(self.locations[i].current_blocks) == 0:
continue
for j in range(-1,2):
if i+j > -1 and i+j < self.num_places and j != 0:
moves.append((i, i+j))
return moves
def check_victory_condition(self):
"""
Evaluate the current board state to see if a victory condition has been met
Parameters
----------
Returns
A boolean that is true if the board is in a win state and false otherwise
"""
for location in self.locations:
if len(location.current_blocks) == 0:
continue
if len(location.current_blocks) > 0 and len(location.current_blocks) != self.num_blocks:
return False
block_ids = [block.id_num for block in location.current_blocks]
if sorted(block_ids) == block_ids:
return True
else:
return False
def show(self):
"""
Print out the current board state
Parameters
----------
Returns
"""
overall_print = [['N ' for j in range(0, self.num_places)] for i in range(0, self.num_blocks)]
print('___________________________________')
for i in range(self.num_blocks):
for j in range(len(self.locations)):
if i < (self.num_blocks-len(self.locations[j].current_blocks)):
overall_print[i][j] = 'N '
else:
index = (i-(self.num_blocks-len(self.locations[j].current_blocks)))
overall_print[i][j] = str(self.locations[j].current_blocks[(len(self.locations[j].current_blocks)-1)-index])
for i in range(len(overall_print)):
for j in range(len(overall_print[i])):
print(overall_print[i][j], end='')
print()
print('___________________________________')
|
24e7d078ff7b03e86e77050a9ff7203f61a2141a | dvdgatik/python_basico | /aproximacion.py | 557 | 3.890625 | 4 | objetivo = int(input('Escoge un numero: '))
epsilon = 0.0001 #que tan_ cerca queremos llegar de la respuesta
paso = epsilon**2 #numero mas pequeño 0.01*0.01
respuesta = 0.0
#abs valor absoluto
while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo: #la segunda iteracion nos protege contra negativos
#print(abs(respuesta**2 - objetivo), respuesta)
respuesta += paso
if abs(respuesta**2 - objetivo) >= epsilon:
print(f'No se encontro la raiz cuadrada de {objetivo}')
else:
print(f'La raiz cuadrada de {objetivo} es {respuesta}')
|
d9b37faeaef7a76b6802edd21a5cc193009b5bf8 | TeamAkatsuki/TeamAkatsuki | /team-akatsuki/kimhr/world_cup.py | 2,356 | 3.546875 | 4 | import random
france = ["돈까스", "짜장면", "햄버거", "냉면", "덮밥", "초밥", "삼겹살", "라면"]
random.shuffle(france)
f = []
def ideal_type():
if len(a)%2 == 0:
loop = len(a) // 2
for i in range(0, loop):
while True:
if loop == 1:
print("<<결승>>\n")
else:
print("<<제 %d강>>\n" %(2*loop))
print("%s vs %s" %(a[i], a[i+1]))
print("왼쪽음식이 끌리면 1번,오른쪽음식이 끌리면 2번을 선택")
print("\n 입력:", end= ' ')
temp = int(input())
print()
if temp == 1:
a.remove(a[i+1])
break
elif temp == 2:
a.remove(a[i])
break
else:
print("잘못 입력하셨습니다. 다시 입력하세요.")
print()
elif len(a)%2 != 0: #홀수명이면 한 명 부전승
workover = a[-1] #부전승
a.remove(a[-1])
loop = len(a) // 2
for i in range(0, loop): #대결 팀 배정
while True:
if loop == 1:
print("<<결승>>\n")
else:
print("<< 제 %d강 >>\n " %(2*loop))
print("%s vs %s" %(a[i], a[i+1]))
print("왼쪽음식이 끌리면 1번,오른쪽음식이 끌리면 2번을 선택")
print("\n 입력:", end = ' ')
temp = int(input())
print()
if temp == 1:
a.remove(a[i+1])
break
elif temp == 2:
a.remove(a[i])
break
else:
print("잘못 입력하셨습니다. 다시 입력하세요.")
print()
a.append(workover)
while True:
print("실행하려면 1번 종료하려면 2번을 입력하세요.")
print("\n 입력:", end= '')
c = int(input())
print()
if c == 1:
a = france[:]
break
else:
print("잘못 입력하셨습니다. 다시 입력하세요.")
while len(a) != 1:
ideal_type()
print("당신의 오늘 점심은", a[0], "입니다.") |
bdbc0649db0bdb0587a778ac139ded3882f46812 | siddhant283/Python | /Generators/fib.py | 206 | 3.875 | 4 | def fib(number):
f0 = 0
f1 = 1
for i in range(number):
yield f0
temp = f0 + f1
f0 = f1
f1 = temp
for item in fib(8):
print(item)
|
51e6916967527c638f29fdef6d32caeacf77e789 | starlordali4444/ALI_INFY | /GENERIC/PROGRAM/PYTHON/while.py | 93 | 3.9375 | 4 | #WAP to take input untill alpha is given
a=""
while (a!="alpha"):
a=input("Enter a word") |
ecb625664c7559f017a5dc4d1411a1ebe9579e0f | chachout/Python-petits-programmes | /Convertisseur de degrés fahrenheit en degrés celsius et inverse.py | 469 | 3.859375 | 4 | b=int(input("Est ce que la température de départ est en fahrenheit [mettre 1] ou en celsius [mettre 0] ou en Kelvin [mettre 2] : " ))
if b==1 :
f=float(input("température en °F : "))
c=(f-32)/1.8
print (f,"°F=",c,"°C")
elif b==2 :
k=float(input("température en °K : "))
c=k-273.15
f=c*1.8+32
print (k,"°K",c,"°C",f,"°F")
else :
c=float(input("température en °C : "))
f=c*1.8+32
print (c,"°C",f,"°F")
|
0806650eef0c3b5ef2ab5274b2d2454313a428e3 | srknthn/InformationSecurity | /TheKey/Columnar_Encrypt_KeyString.py | 1,105 | 3.78125 | 4 | __author__ = 'sr1k4n7h'
import re
# def sort_indices(word): # FAILING FOR DUPLICATE LETTERS IN THE KEY
# """ sorting the indices in the key """
# h, k = {}, 0
# for i in sorted(word):
# h.__setitem__(i, k)
# k += 1
# return [h[i] for i in word]
# SORTING THE INDICES OF THE KEY
sorted_indices = lambda key: [f[1] for f in sorted([(k[1], i) for i, k in enumerate(sorted([(key[i], i) for i in range(len(key))]))])]
def columnar_transposition(text, keyword):
text = re.sub('[^A-Z]', '', text.upper()) # REMOVING ALL THE PUNCTUATIONS, WHITESPACES AND CONVERTING TO UPPER CASE
indices = sorted_indices(keyword)
key_length = len(keyword)
encrypted = ''
for i in range(key_length):
encrypted += text[indices.index(i)::key_length] # OBTAINING THE LETTERS IN COLUMNS THROUGH LIST SLICING
return encrypted
print("COLUMNAR TRASNSPOSITION - ENCRYPTED TEXT : " + columnar_transposition(input("ENTER THE PLAIN TEXT : "),
input("ENTER THE KEY STRING: ")))
|
3bcda5c77649694afc33a194dc72307c60350cd5 | tommady/Hackerrank | /Algorithms/strings/sherlock_and_anagrams.py | 480 | 3.625 | 4 | # http://www.geeksforgeeks.org/anagram-substring-search-search-permutations/
from collections import defaultdict
for _ in range(int(input())):
s = input()
len_s = len(s)
d = defaultdict(int)
for i in range(len_s):
for j in range(1, len_s-i+1):
sub_s = s[i:i+j]
sub_s = sorted(sub_s)
d["".join(sub_s)] += 1
answer = 0
for v in d.values():
answer += v*(v-1) // 2
print(answer)
|
6ca3b9eba574bce83ea095d2f2dc8fd4369012ee | mkmad/ctci | /ctci/trees_graphs/dfs_bfs.py | 1,984 | 4.0625 | 4 | import pprint
pp = pprint.PrettyPrinter(indent=4)
import Queue
myqueue = Queue.Queue() # supports put() and get()
# Check if empty using empty()
# This is a adjacency set. Sets are used
# as its much better since they eliminate
# duplicate entry.
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])
}
# There is nothing like visit left first then
# right, just go through the depth of neighbours
# one by one.
visited = set()
visited_ = set()
def dfs(graph, start, visited):
# Note this base condition
if not visited:
visited.add(start)
for val in graph[start] - visited:
if val not in visited:
print "Visiting {0} -> {1}".format(start, val)
# Add it to visited just before calling dfs
visited.add(val)
dfs(graph, val, visited)
return visited
def bfs(graph, start, visited):
# Note this base condition
if not visited:
visited.add(start)
for val in graph[start] - visited:
if val not in visited:
print "Visiting {0} -> {1}".format(start, val)
# Add it to visited just before putting in the queue
myqueue.put(val)
visited.add(val)
while not myqueue.empty():
bfs(graph, myqueue.get(), visited)
return visited
if __name__ == '__main__':
print "\nGraph\n"
pp.pprint(graph)
print "\nDFS\n"
dfs(graph, 'A', visited)
print "\nBFS\n"
bfs(graph, 'A', visited_)
print '\n'
'''
Notes:
1) In DFS you only need one for loop that is to iterate through
the neighbours of the node
2) In BFS you need two iteration, one is for the neighbours of
the neighbours, and other is to iterate through the queue.
This second iteration is taken for granted in DFS as recurssion
maintains the stack for us.
'''
|
4a6f84e6dfd4184ed924bdc46b9bdadfdfc67375 | phaustin/pythonlibs | /pyutils/pyutils/translate.py | 789 | 3.8125 | 4 | #http://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str
import string
letter_set = frozenset(string.ascii_lowercase + string.ascii_uppercase)
## tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase,
## string.ascii_lowercase * 2)
tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase,
string.ascii_lowercase + string.ascii_uppercase)
deletions = ''.join(ch for ch in map(chr,range(256)) if ch not in letter_set)
## from string import maketrans, translate
## >>> table = maketrans('', '')
## >>> translate(orig, table, table[128:])[/color][/color][/color]
def test_translate(s):
return string.translate(s, tab, deletions=deletions)
|
b2c039093374d5b0bdc0f37af63629da930c822a | CarlVs96/Curso-Python | /Curso Python/1 Sintaxis Básica/Video 6 - Funciones Parametrizadas/Funciones_parametrizadas.py | 103 | 3.546875 | 4 | def suma(num1, num2):
resultado=num1+num2
return resultado
almacenaRes=suma(5,8)
print(almacenaRes) |
2dd4c16eeadb05beb1f1cc0e44e7c09a2bc3f798 | Khushisomani/codes | /29099417.py | 125 | 3.5 | 4 | # cook your dish here
import math
for _ in range(int(input())):
a,b=map(int,input().split())
print((2*math.gcd(a,b))) |
851ce203ef5aac5e3e6867c02eda07b3da84fdf4 | shanbumin/py-beginner | /026-image/demo08/main.py | 1,807 | 3.546875 | 4 | import random
from PIL import Image, ImageDraw, ImageFont
# Pillow中有一个名为ImageDraw的模块,该模块的Draw函数会返回一个ImageDraw对象,
# 通过ImageDraw对象的arc、line、rectangle、ellipse、polygon等方法,
# 可以在图像上绘制出圆弧、线条、矩形、椭圆、多边形等形状,也可以通过该对象的text方法在图像上添加文字。
def random_color():
"""生成随机颜色"""
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
return red, green, blue
width, height = 800, 600
# 创建一个800*600的图像,背景色为白色
image = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
# 创建一个ImageDraw对象
drawer = ImageDraw.Draw(image)
# 通过指定字体和大小获得ImageFont对象
font = ImageFont.truetype('Kongxin.ttf', 32)
# 通过ImageDraw对象的text方法绘制文字
drawer.text((300, 50), 'Hello, world!', fill=(255, 0, 0), font=font)
# 通过ImageDraw对象的line方法绘制两条对角直线
drawer.line((0, 0, width, height), fill=(0, 0, 255), width=2)
drawer.line((width, 0, 0, height), fill=(0, 0, 255), width=2)
xy = width // 2 - 60, height // 2 - 60, width // 2 + 60, height // 2 + 60
# 通过ImageDraw对象的rectangle方法绘制矩形
drawer.rectangle(xy, outline=(255, 0, 0), width=2)
# 通过ImageDraw对象的ellipse方法绘制椭圆
for i in range(4):
left, top, right, bottom = 150 + i * 120, 220, 310 + i * 120, 380
drawer.ellipse((left, top, right, bottom), outline=random_color(), width=8)
# 显示图像
image.show()
# 保存图像
#image.save('result.png')
#todo 注意:上面代码中使用的字体文件需要根据自己准备,可以选择自己喜欢的字体文件并放置在代码目录下。
|
b679dc21315dd8c732528f6ae9b5fa813bf85148 | MaliYudina/AdPY | /HW2/countries_parser.py | 1,140 | 3.640625 | 4 | import json
SOURCE_FILE = 'countries.json'
FILE_TO_WRITE = 'countries_link.txt'
"""
Написать класс итератора, который по каждой стране из файла countries.json
ищет страницу из википедии.
Записывает в файл пару: страна – ссылка.
"""
class WikipediaData:
def __init__(self, FILE_TO_WRITE, output):
self.countries = json.load(open(FILE_TO_WRITE))
self.ind = -1
countries = json.load(open(SOURCE_FILE))
self.max_range = len(countries)
self.out = open(output, 'w', encoding='utf8')
def __iter__(self):
return self
def __next__(self):
self.ind += 1
while self.ind >= self.max_range:
self.out.close()
raise StopIteration
return self.countries[self.ind]['name']['official']
def write_country(self, country):
url = f'https://en.wikipedia.org/wiki/{country}'
self.out.write(f'{country} - {url}\n')
result = WikipediaData(SOURCE_FILE, FILE_TO_WRITE)
for country in result:
result.write_country(country)
|
49727e39eeb0d01c83cf1847d1d1c476bd99c471 | IIT-Lab/sumo-rl | /agents/agent.py | 533 | 3.5 | 4 | from abc import ABC, abstractmethod
class Agent(ABC):
def __init__(self, state_space, action_space):
self.state_space = state_space
self.action_space = action_space
@abstractmethod
def new_episode(self):
pass
@abstractmethod
def observe(self, observation):
''' To override '''
pass
@abstractmethod
def act(self):
''' To override '''
pass
@abstractmethod
def learn(self, action, reward, done):
''' To override '''
pass
|
eee7ca33cb637679d21d9eb85fb3762faee1dee2 | ttong-ai/repl-vendor-management | /utils.py | 858 | 3.625 | 4 | from typing import Any
BIG_NUMBER = 100_000
def ifnone(a: Any, b: Any) -> Any:
"""`a` if `a` is not None, otherwise `b`."""
return b if a is None else a
def levenshtein(s: str, t: str, ignore_case=False) -> int:
""" Implementation of classic Levenshtein edit distance. """
if s is None or t is None:
return BIG_NUMBER
if ignore_case:
s = s.lower()
t = t.lower()
if s == t:
return 0
elif len(s) == 0:
return len(t)
elif len(t) == 0:
return len(s)
v0 = list(range(len(t) + 1))
v1 = v0.copy()
for i in range(len(s)):
v1[0] = i + 1
for j in range(len(t)):
cost = 0 if s[i] == t[j] else 1
v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost)
for j in range(len(v0)):
v0[j] = v1[j]
return v1[len(t)]
|
9d3c7c23828758141ffceef8a47e817b9356b15e | tomviner/project-euler | /problem-5.py | 1,227 | 4.03125 | 4 | """
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import itertools
from collections import Counter
from common import prime_factors, product
def divisible_by_range(x, n):
"""
>>> divisible_by_range(2520, 10)
True
>>> divisible_by_range(1000, 10)
False
"""
for i in range(n, 1, -1): # fail quicker by starting high
if x % i:
return False
return True
def smallest_dividible_brute_force(n):
"""
This takes 11 minutes for n=20 on a netbook!
>>> smallest_dividible_brute_force(10)
2520
"""
for x in itertools.count(n):
if divisible_by_range(x, n):
return x
def smallest_dividible(n):
"""
>>> smallest_dividible(10)
2520
"""
factors = Counter()
for i in range(1, n+1):
facs = Counter(prime_factors(i))
for fac, count in list(facs.items()):
factors[fac] = max(count, factors[fac])
return product(fac**count for (fac, count) in list(factors.items()))
if __name__ == '__main__':
print(smallest_dividible(20))
|
350e6c9c135545e4c0c1c4a4ca4a3b73d77f0da3 | riemannzeta1191/PyDev | /Multithreading/Threading_experiments.py | 3,766 | 3.96875 | 4 | import threading, math
from multiprocessing import Process
#
# Py_BEGIN_ALLOW_THREADS
# sleep((int)secs); A thread can bypass the GIL by releasing it when it enters a I/O blocking
# Py_END_ALLOW_THREADS instruction,during which other threads can run in parallel untill is asks
# back the GIL.Cpython interpreter only allows a thread at a time not the memory
# which can spawn n number of threads using the os-kernel.But spawning itself
# is a memory consuming process and thus multithreading is a performance degenerating
# feature in python.In contrast to the performance GIL protects the shared resources
# to not vanish into aether as it hinders threads to decrease the ref count of the
# shared object to not become 0 ,which in turn would lead to the garbage allocation of
# the object called by the interpreter using __del__ built_in method.GIL primarily
# helps in memory management within the call stack and the objects in the heap.Ideally
# it's not a feature for the end user's routine use.
def non_threaded():
return prime_range(1,100)
def threaded():
t1 = threading.Thread(name="threaded-1",target=prime_range,args=(1,20))
t2 = threading.Thread(name="threaded-2",target=prime_range,args=(21,40))
t3 = threading.Thread(name="threaded-3",target=prime_range,args=(41,60))
t4 = threading.Thread(name="threaded-4",target=prime_range,args=(61,80))
t5 = threading.Thread(name="threaded-5",target=prime_range,args=(81,100))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t1.join()
t2.join()
t3.join()
t4.join()
t5.join()
#
# --------Results--------
# ('Non threaded Duration: ', 0.00012200000000000405, 'seconds') for 2 threads
# ('Threaded Duration: ', 0.0014069999999999985, 'seconds')
#Multithreading if it's CPU bound job becomes very costly for the Cpython since all threads wait
#for each other to complete in addition to the overhead of spawning new threads.One processor
#at a time should be acting upon one thread and carrying on the work.
# --------Results--------
# ('Non threaded Duration: ', 0.0001250000000000001, 'seconds') for 3 threads
# ('Threaded Duration: ', 0.004196999999999999, 'seconds')
# --------Results--------
# ('Non threaded Duration: ', 0.0003919999999999965, 'seconds') for 5 threads
# ('Threaded Duration: ', 0.007214999999999999, 'seconds')
#
print ("Finishing Catalan...")
def catalan_number(num):
if num <= 1:
return 1
res_num = 0
for i in range(num):
res_num += catalan_number(i) * catalan_number(num-i-1)
return res_num
def catalan_num_range(m,n):
k = (n-m)
for i in range(k):
print catalan_number(i),
def is_prime(n):
if n>2 and n%2==0:
return False
for i in range(3, int(math.sqrt(n)+1)):
if n % i == 0:
return False
return True
def prime_range(m,n):
k = n-m
l = []
for i in range(k):
if is_prime(i):
l.append(i)
if __name__ == '__main__':
import time
print("--------Nonthreaded calculation--------")
nTstart_time = time.clock()
non_threaded()
nonThreadedTime = time.clock() - nTstart_time
print("--------Threaded calculation--------")
Tstart_time = time.clock()
threaded()
threadedTime = time.clock() - Tstart_time
print("--------Results--------")
print ("Non threaded Duration: ",nonThreadedTime, "seconds")
print ("Threaded Duration: ",threadedTime, "seconds")
|
08cedf0a93b6ec05555c16f917eb0dad790ac4fb | MaximOksiuta/for-dz | /dz7/1.py | 3,220 | 3.671875 | 4 | class Matrix:
"""перегрузка конструктора"""
def __init__(self, matrix):
self.matrix = matrix
"""перегрузка __str__"""
def __str__(self):
self.result = '' # очистка итоговой строки
self.matrix = self.checker(self.matrix)
"""формирование матрицы"""
for i in self.matrix:
for n in i:
self.result += f'{n} '
self.result += '\n'
return self.result # возвращаем готовую матрицу
"""метод для проверки матрицы и устронения не соответствий"""
def checker(self, mat, m=0, ls=1):
"""создание списка длин строк (если нужно)"""
if ls == 1:
ls = [len(i) for i in mat]
"""нахождение максимального количества чисел в строке (если нужно)"""
if m == 0:
m = max(ls)
"""дополнение строк '0' (если нужно)"""
c = 0
for i in ls:
if i != m:
for n in range(0, m - i):
mat[c].append(0)
c += 1
return mat # возвращаем корректную матрицу
"""перегрузка __add__"""
def __add__(self, other):
s_len = len(self.matrix) # нахождение количества строк 1 матрицы
o_len = len(other.matrix) # нахождение количества строк 2 матрицы
"""проверка и исправление различий в количестве строк"""
if s_len < o_len:
for i in range(0, o_len - s_len):
self.matrix.append([])
elif s_len > o_len:
for i in range(0, s_len - o_len):
other.matrix.append([])
ls = [len(i) for i in self.matrix] # создание списка длин строк 1 матрицы
ls2 = [len(i) for i in other.matrix] # создание списка длин строк 2 матрицы
lm = ls + ls2 # соединение двух списков для нахождения максимального количества чисел в строке
m = max(lm)
self.matrix = self.checker(self.matrix, m, ls) # обращаемся к функции checker для проверки и исправления строк
other.matrix = other.checker(other.matrix, m, ls2)
self.result = '' # очистка итоговой строки
"""формирование матриц и их сложение"""
for i in range(0, len(self.matrix)):
for n in range(0, len(self.matrix[i])):
self.result += f'{self.matrix[i][n] + other.matrix[i][n]} '
self.result += '\n'
return self.result # возвращаем готовую матрицу
matrix = [[1, 2], [3, 4], [5, 6]]
matrix1 = [[7, 8], [9, 10], [11, 12, 13], []]
M = Matrix(matrix)
M1 = Matrix(matrix1)
print(M)
print(M1)
print(M+M1)
|
04a51dd1d8febc64518da9c2b924f8e5c59ad130 | dev-arctik/Basic-Python | /2. Data type.py | 297 | 3.78125 | 4 | name="Dev"
age=17
sex="male"
hobby=["guitar","mechatronics"]
#type keyword will show the datatype of keyword
print("data type of",name, " is ", type(name))
print("data type of",age, " is ", type(age))
print("data type of", sex, " is ", type(sex))
print("data type of", hobby, " is ", type(hobby))
|
92bcc845b38c034232a03b6a8841a451ce914991 | mur78/PythonPY100 | /Занятие1/Домашнее_задание/task1/main.py | 413 | 3.90625 | 4 | # Напишите ваше решение
# Напишите ваше решение
speed = float(input('Задайте скорость передачи данных: '))
time = float(input('Время скачивания: '))
coast = float(input('Цена за 1 ГБ: '))
size = (time * speed) # Б за время
size_gb = size // (1024 * 1024)
coast_gb = (size_gb * coast)
print(size_gb)
print(coast_gb)
|
36390b2bd3234a89c3d601e26fb3b65ebe76f748 | iftikhar1995/Python-DesignPatterns | /Creational/Builder/ComputerBuilder/SubObjects/hard_disk.py | 895 | 4.25 | 4 | class HardDisk:
"""
HardDisk of a computer
"""
def __init__(self, capacity: str) -> None:
self.__capacity = capacity
def capacity(self) -> str:
"""
A helper function that will return the capacity of the hard disk.
:return: The capacity of the hard disk.
:rtype: str
"""
return self.__capacity
def __str__(self) -> str:
"""
Overriding the magic method to send custom representation
:return: The custom representation of the object
:rtype: str
"""
disk = dict()
disk['Capacity'] = self.__capacity
return str(disk)
def __repr__(self) -> str:
"""
Overriding the magic method to send custom representation
:return: The custom representation of the object
:rtype: str
"""
return self.__str__()
|
2a119025f1fc545c0b541ee1cf6f7f74f49f7c79 | jhanse9522/toolkitten | /Python_Hard_Way_W2/ex15.py | 997 | 4.53125 | 5 | from sys import argv
script, filename = argv
txt = open(filename) #the open command takes a parameter, in this case we passed in filename, and it can be set to our own variable. Here, our own variable stores an open text file. Note to self: (filename) and not {filename} because filename is already a variable label created in line 3.
print(f"Here's your file {filename}:")
print(txt.read()) #call a function on an opened text file named "txt" and that function we call is "read". We call "read" on an opened file. It returns a file and accepts commands. ****You give a FILE a command using dot notation.
txt.close()
print("Type the filename again:")
file_again = input("> ") #sets user input received at prompt "> " equal to variable called "file_again"
txt_again = open(file_again) #opens our sample txt file again and stores opened file in a variable called txt_again
print(txt_again.read()) #reads the file now stored under txt_again and prints it out again.
txt_again.close()
|
f40c2e15549842e0a96344d4c6d92bfa9d18527b | stcatz/hackerrank | /warmup/find-digits/main.py | 147 | 3.5 | 4 | num = input()
for i in range(num):
x = raw_input()
count = 0
for i in x:
if( int(i)!=0 and int(x) % int(i) == 0):
count += 1
print count
|
440ecfcb604be2ed9d23dc9c296ca5a89001a6ab | JLLangy/74hc595 | /random_example.py | 1,060 | 4.03125 | 4 | # Example of displaying eight-digit random numbers using
# 8 x seven-segment displays controlled by 74HC595 shift register
# Author: John-Lee Langford
# Last update: 26-July-2021
# URL: mr.langford.com
import time
import ssd74hc595
import random
# Define GPIO outputs
dataPin = 11
latchPin = 15
clockPin = 13
# Create object
Display = ssd74hc595.sevenseg(dataPin, latchPin, clockPin)
# Display a single character in on a specific display and repeat to build-up an eight character output
# Useage: Display.Single(character [int / str], displayNumber [0 - 9], decimal point [True / False])
# Note: display 0 is on the right of the board
while True:
# Pick a random number
randomNumber = str(random.randint(0, 99999999))
# If the number is less than 8 digits, populate the missing numbers with spaces
while len(randomNumber) < 8:
randomNumber = " " + randomNumber
# Reverse number
randomNumber = randomNumber [::-1]
# Cycle through displays 2000 times
for x in range(2000):
for i in range(8):
Display.Single(randomNumber[i], i, False)
|
ba7c817bc94abdab6cb620e39d71e0fa176df978 | shimoishiryusei/school_programing_backup | /Code_Py/selection_sort.py | 365 | 3.703125 | 4 | def selection_sort(li):
l = li.copy()
n = len(l)
for i in range(n):
min_num = i
for j in range(i,n):
if l[j] < l[min_num]:
min_num = j
l[i], l[min_num] = l[min_num], l[i]
return l
n_len = int(input("配列の要素数:"))
li = [int(input()) for _ in range(n_len)]
print(selection_sort(li))
|
c7fcbf2081ddeb126ebf304b44a51093e30c31a6 | Zylophone/practice | /airbnb/find_median.py | 655 | 3.734375 | 4 | import sys
def find_median(nums):
n = len(nums)
start, end = -sys.maxint - 1, sys.maxint
if n % 2 == 0:
return float(find_k(nums, n / 2 - 1, start, end) + find_k(nums, n / 2, start, end)) / 2
else:
return find_k(nums, n / 2, start, end)
def find_k(nums, k, start, end):
if start >= end:
return start
mid = start + (end - start) / 2
cnt = 0
for n in nums:
if n < mid:
cnt += 1
if cnt == k:
return mid
elif cnt < k:
start = mid + 1
else:
end = mid
return find_k(nums, k, start, end)
print find_median([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
|
64917c8ea283c73aaa626b16276c4919d1153f8c | miaopei/MachineLearning | /LeetCode/github_leetcode/Python/jump-game-ii.py | 1,098 | 3.78125 | 4 | # Time: O(n)
# Space: O(1)
#
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
#
# Each element in the array represents your maximum jump length at that position.
#
# Your goal is to reach the last index in the minimum number of jumps.
#
# For example:
# Given array A = [2,3,1,1,4]
#
# The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
#
# not pass on leetcode because of time limit
class Solution(object):
# @param A, a list of integers
# @return an integer
def jump(self, A):
jump_count = 0
reachable = 0
curr_reachable = 0
for i, length in enumerate(A):
if i > reachable:
return -1
if i > curr_reachable:
curr_reachable = reachable
jump_count += 1
reachable = max(reachable, i + length)
return jump_count
if __name__ == "__main__":
print Solution().jump([2,3,1,1,4])
print Solution().jump([3,2,1,0,4])
|
0e0d3e616a3c1658b0202c990ed4e569692e3b19 | deepshikha-hub/C179 | /project_C179.py | 1,875 | 3.671875 | 4 | from tkinter import *
import random
root = Tk()
root.title("Encapsulation")
root.geometry("500x400")
root.config(bg="white")
label_score = Label(root, text="Score : 0",font=("Bahnschrift Light",15,"bold") ,bg="white")
label_score.place(relx=0.1,rely=0.1, anchor= CENTER)
label_name = Label(root,font=("Arial",40),bg="white")
label_name.place(relx=0.5,rely=0.3, anchor= CENTER)
input_value = Entry(root)
input_value.place(relx=0.5,rely=0.5, anchor= CENTER)
class game:
def __init__(self):
self.__score = 0
def updateGame(self):
self.text = ["BLACK","PINK","GREEN","BLUE","YELLOW","RED"]
self.random_number_for_text = random.randint(0,5)
self.color = ["black","pink","green","blue","yellow","red"]
self.random_number_for_color = random.randint(0,5)
label_name["text"] = self.text[self.random_number_for_text]
label_name["fg"] = self.color[self.random_number_for_color]
def __update_score(self,input_value):
if(input_value == self.color[self.random_number_for_color]):
print(self.color[self.random_number_for_color])
self.__score = self.__score + random.randint(0,10)
label_score["text"] = "Score : "+str(self.__score)
def get_user_value(self, input_value):
self.__update_score(input_value)
obj = game()
def getInput():
value = input_value.get()
obj.get_user_value(value)
obj.updateGame()
input_value.delete(0,END)
btn = Button(root, text="CHECK" ,command=getInput, bg="IndianRed1", fg="white", relief=FLAT, padx=10, pady=1, font=("Arial",15))
btn.place(relx=0.35,rely=0.65, anchor= CENTER)
btn = Button(root, text="START" ,command=obj.updateGame, bg="dark olive green", fg="white", relief=FLAT, padx=10, pady=1, font=("Arial",15))
btn.place(relx=0.65,rely=0.65, anchor= CENTER)
root.mainloop() |
972264af5c4f31025982a6dff82e6decd279dd31 | RogerWoodman/simple-image-zoom | /zoomregion.py | 3,268 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Simple example allows for a selected region to be zoomed. The selected region is resized and
joined horizontally to the main image
@author: Roger Woodman
"""
import cv2
import numpy
class ZoomRegion():
def __init__(self, image):
"""Initialise drawing variables"""
# Flag for wether the user has clicked and now dragging
self.drawing = False
# Points for the rectangle
self.point1 = (-1, -1)
self.point2 = (-1, -1)
# Initial image
self.imageMain = image
# Image to draw on
self.imageDraw = self.imageMain.copy()
def draw(self, event, x, y, params, flags):
"""Handles mouse callback events"""
if(event == cv2.EVENT_LBUTTONDOWN and not self.drawing):
self.drawing = True
self.point1 = (x, y)
if (event == cv2.EVENT_MOUSEMOVE and self.drawing):
self.imageDraw = self.imageMain.copy()
self.point2 = (x, y)
cv2.rectangle(self.imageDraw, self.point1, self.point2, (0,255,0), 1)
# Flip the points if the rectangle has been created from bottom to top or right to left
roiPoint1 = list(self.point1)
roiPoint2 = list(self.point2)
if(roiPoint1[0] > roiPoint2[0]):
roiPoint1[0], roiPoint2[0] = roiPoint2[0], roiPoint1[0]
if(roiPoint1[1] > roiPoint2[1]):
roiPoint1[1], roiPoint2[1] = roiPoint2[1], roiPoint1[1]
# Get the region of interest
imageROI = self.imageMain[roiPoint1[1]:roiPoint2[1], roiPoint1[0]:roiPoint2[0]]
# If the region is larger than 1 x 1 then reszize the selected region
if(imageROI.shape[0] > 1 and imageROI.shape[1] > 1):
imageROI = cv2.resize(imageROI, (0,0), fx=3, fy=3)
# Get image and ROI dimensions
height1, width1 = self.imageDraw.shape[:2]
height2, width2 = imageROI.shape[:2]
# Create empty matrix
tempImage = numpy.zeros((max(height1, height2), width1+width2,3), numpy.uint8)
# Combine 2 images
tempImage[:height1, :width1,:3] = self.imageDraw
tempImage[:height2, width1:width1+width2,:3] = imageROI
# Set image to draw as combination of two images
self.imageDraw = tempImage
if event == cv2.EVENT_LBUTTONUP:
if(self.drawing):
self.point2 = x, y
self.drawing = False
if __name__ == '__main__':
# Load image
#image = numpy.zeros((512, 512, 3), numpy.uint8)
image = cv2.imread(r'test_image.jpg')
# Create drawing object
drawTest = ZoomRegion(image)
# Create an openCV window
cv2.namedWindow('Simple image zoom')
# Attach an even handler to the window
cv2.setMouseCallback('Simple image zoom', drawTest.draw)
print("Press Escape to exit the program")
# Loop until user presses escape
while(True):
cv2.imshow('Simple image zoom', drawTest.imageDraw)
# Press escape to exit the program
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# close CV window
cv2.destroyAllWindows() |
a7a57c23a4eead638ca64a2cc27a515bf5621db6 | ddgvv/dd | /bs22.py | 64 | 3.578125 | 4 | n=input()
rn=n[::-1]
if (n==rn): print("yes")
else: print("no")
|
2074279bd49c8301220952574ca8fd8ba4378ebb | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/hrdtim002/question2.py | 1,073 | 4.1875 | 4 | """Vending Machine
Tim Hardie
16-4-14"""
def calc_change (remaining):
# calculating the different number of each coin
num_dollars = remaining//100
remaining %= 100
num_25c = remaining//25
remaining %= 25
num_10c = remaining//10
remaining %= 10
num_5c = remaining//5
remaining %= 5
num_1c = remaining
# printing how many of each coin will be required
if num_dollars: print(num_dollars, "x $1")
if num_25c: print(num_25c, "x 25c")
if num_10c: print(num_10c, "x 10c")
if num_5c: print(num_5c, "x 5c")
if num_1c: print(num_1c, "x 1c")
if __name__ == '__main__':
# gets how much user must pay
cost = eval (input ("Enter the cost (in cents):\n"))
remaining = cost
# runs until users has paid full cost
while (remaining > 0):
deposit = eval (input ("Deposit a coin or note (in cents):\n"))
remaining -= deposit
# user's change
if remaining:
print ("Your change is:")
calc_change (abs(remaining)) |
5351f25080022c776eaa4dacc5ed9711433be566 | akshitbhalla2/10-days-of-statistics | /62.py | 338 | 3.59375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
mystdin = []
for line in sys.stdin:
mystdin.append(line)
arr = mystdin[0].split(" ")
arr = [float(a) for a in arr]
lam1, lam2 = arr
e1 = 160 + 40*(lam1**2 + lam1)
e2 = 128 + 40*(lam2**2 + lam2)
print("{:.3f}".format(e1))
print("{:.3f}".format(e2))
|
97900b474c12a27042348dd84bda6cf2df6180c8 | Adil-Anzarul/Pycharm-codes | /OOPS 5 Class methods in python T56.py | 576 | 3.890625 | 4 | class Employee:
no_of_leaves=8
def __init__(self,a,b,c): #this is constructor
self.name=a
self.salary=b
self.role=c
def printdetails(self):
return f" The name is {self.name}, salary is {self.salary} and role is {self.role} "
@classmethod
def change_leaves(cls,newleaves):
cls.no_of_leaves=newleaves
harry=Employee("Harry",5245,"Instructor")
rohan=Employee("Rohan",5875,"Student")
rohan.change_leaves(45)
print(harry.no_of_leaves)
Employee.change_leaves(852)
print(harry.no_of_leaves)
print(rohan.no_of_leaves)
|
368e44f656262bede1918067e516f96d493d97a2 | maelizarova/python_geekbrains | /lesson_2/task_3/main.py | 795 | 3.71875 | 4 | seasons_as_list = [[12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], 'fall', 'summer', 'spring', 'winter']
seasons_as_dict = {(12, 1, 2): 'winter', (3, 4, 5): 'spring', (6, 7, 8): 'summer', (9, 10, 11): 'fall'}
month = int(input('Please, enter the number of month: '))
# первый вариант для списка:
for idx in range(len(seasons_as_list) // 2):
try:
season = seasons_as_list[idx].index(month)
print(seasons_as_list[-season])
except ValueError:
continue
# второй вариант для списка:
for idx in range(len(seasons_as_list) // 2):
if month in seasons_as_list[idx]:
print(seasons_as_list[-(idx + 1)])
for key in seasons_as_dict:
if month in key:
print(seasons_as_dict.get(key)) |
d7a1f102cc9862394b025f6c76064ba2c753d2b3 | jgonzalezzu/MinTIC2022-UNAB-G63 | /CICLO-1/EjerciciosClase/S4/DiccionariosYTuplas10.py | 436 | 4.125 | 4 | # Semana 4 - Clase 2 - Diccionarios y tuplas - Ejercicio 10
#TODO: Acceder a los elementos del diccionario
diccionairo = {'four':'cinco'}
diccionairo1 = {'one':'uno', 'two':'dos'}
# Cuando de busca un valor existente este va a retornar el valor asociado a ese valor, de lo contrario imprime 'not está'
dato = diccionairo1.get('one','no está')
print('el dato es',dato)
dato = diccionairo1.get('three','no está')
print('el dato', dato) |
f0eff5a456adcc8e731f1c2c8baac79e82cddce5 | JamesMsuya/algorithms. | /theft_141044093.py | 1,758 | 3.625 | 4 | """
This algorithm finds the possible maximum values in the next column.
It assumes the values in first columns are the maximum values the in the second values for each row
the maximum value can be sum of itself and the left top(X[i][j] + X[i-1][j-1]) or left(X[i][j] + X[i][j-1]) or
left bottom(X[i][j] + X[i-1][j+1]). For values in the top row maxisum can be itself and left(X[i][j] + X[i][j-1])
or left bottom(X[i][j] + X[i-1][j+1]) and Lastly for values in bottom row maxisum can be itself and left(X[i][j] + X[i][j-1])
or left top(X[i][j] + X[i-1][j-1]). and last before it return it check which element in the last column has the maximum sunm of coins.
Then it return that value.
Every colums its does m additions and three comparisons. since there are n colums totoal additions are n*m and
total of 3*m*n comparisons. So in worst case it is O(m*n).
"""
def theft(_2dlist):
if len(_2dlist)==0 or len(_2dlist[0])==0:
return 0
temp = _2dlist.copy()
col= len(_2dlist[0])
row = len(_2dlist)
for i in range(1,col,1):
res = -1
for j in range(row):
if j > 0 and j < row-1:
temp[j][i] += max(temp[j][i-1],temp[j - 1][i - 1],temp[j + 1][i - 1])
elif j == 0 :
temp[j][i] += max(temp[j][i-1],temp[j + 1][i - 1])
elif j == row-1:
temp[j][i] += max(temp[j][i-1], temp[j - 1][i - 1])
res = max(temp[j][i], res)
return res
amountOfMoneyInLand= [[1,3,1,5],[2,2,4,1],[5,0,2,3],[0,6,1,2]]
res = theft(amountOfMoneyInLand)
print(res) #Output: 16
amountOfMoneyInLand= [[10,33,13,15],[22,21,4,1],[5,0,2,3],[0,6,14,2]]
res = theft(amountOfMoneyInLand)
print(res) #Output: 83 |
857cec22c729161d21d60703d22a6798015aa009 | Amrutak2/Python | /ClassNdObject.py | 248 | 3.609375 | 4 | class MyClass():
name = ""
rno = ""
def display(self):
print("Name:", self.name)
print("Roll number:",self.rno)
p1 = MyClass()
p1.name = "A"
p1.rno = 1
p1.display()
p1.name = "B"
p1.rno = 2
p1.display() |
29fa455bb84dadc0835bdbe2968b9e9acc926e08 | notalexg/Ch.04_Conditionals | /4.3_Quiz_Master.py | 4,144 | 3.6875 | 4 | '''
QUIZ MASTER PROJECT
-------------------
The criteria for the project are on the website. Make sure you test this quiz with
two of your student colleagues before you run it by your instructor.
'''
corr = 0
wrng = 0
ans = int(input("\n\033[1;34mHow many wins does NA have at worlds 2020?"))
if ans == 2:
print("\033[92mThank FlyQuest and G2 for ruining the meme. Take a point")
corr = corr + 1
else:
print("\033[31mIncorrect")
print("\033[0mThe correct answer was 1")
wrng = wrng + 1
ans = input("\n\033[1;34mWho is going to win worlds?")
if ans.upper() == "TOP" or ans.upper() == "TOP ESPORTS" or ans.upper() == "JDG" or ans.upper() == "JD GAMING":
print("\033[32mPossibly, Here's a point.")
corr = corr + 1
elif ans.upper() == "SNG" or ans.upper() == "SUNING" or ans.upper() == "LGD" or ans.upper() == "LGD GAMING":
print("\033[32mPossibly, Here's a point.")
corr = corr + 1
elif ans.upper() == "DRX" or ans.upper() == "DWG" or ans.upper() == "DAMWON GAMING" or ans.upper() == "GG":
print("\033[32mPossibly, Here's a point.")
corr = corr + 1
elif ans.upper() == "GENG" or ans.upper() == "MACHI" or ans.upper() == "G2" or ans.upper() == "G2 ESPORTS":
print("\\033[32mPossibly, Here's a point.")
corr = corr + 1
elif ans.upper() == "PSG" or ans.upper() == "PSG TALON" or ans.upper() == "UOL" or ans.upper() == "UNICORNS OF LOVE":
print("\033[32mPossibly, Here's a point.")
corr = corr + 1
elif ans.upper() == "FNC" or ans.upper() == "FNATIC" or ans.upper() == "RGE" or ans.upper() == "ROGUE":
print("\033[32mPossibly, Here's a point.")
corr = corr + 1
elif ans.upper() == "TSM" or ans.upper() == "TL" or ans.upper() == "TEAM LIQUID" or ans.upper() == "FLQ":
print("\033[31mReally? NA? hahahha negative 1 points.")
print("\033[0mThe correct answer was literally anyone else but an NA team.")
corr = corr - 1
wrng = wrng + 1
elif ans.upper() == "TSM" or ans.upper() == "TL" or ans.upper() == "TEAM LIQUID" or ans.upper() == "FLQ":
print("\033[31mReally? NA? hahahha negative 1 points.")
print("\033[0mThe correct answer was literally anyone else but an NA team.")
corr = corr - 1
wrng = wrng + 1
else:
print("\033[31mThat either isn't a team competing, or you typed it in wrong, no consequences")
ans = input("\n\033[1;34mAre Mr. Hermons' and Joes' puns bad?")
if ans.upper() == "YES":
print("\033[32mCorrect!")
corr = corr + 1
else:
print("\033[31mIncorrect")
print("\033[0mThe correct answer was yes.")
wrng = wrng + 1
ans = input("\n\033[1;34mIs coding hard?")
if ans.upper() == "NO":
print("\033[32mCorrect!")
corr = corr + 1
else:
print("\033[31mIncorrect")
print("\033[0mThe correct answer was no.")
wrng = wrng + 1
print("\n\033[0mA. These questions are fantastic")
print("\033[0mB. These questions are hard to think of")
print("\033[0mC. This quiz is cool")
print("\033[0mD. Mr. Hermon is a bad teacher")
ans = input("\n\033[1;34mWhich of these statements are true?")
if ans.upper() == "B":
print("\033[32mCorrect!")
corr = corr + 1
else:
print("\033[31mIncorrect")
print("\033[0mThe correct answer was B.")
wrng = wrng + 1
ans = input("\n\033[1;34mFill in the blank, 'Jake is a(n) _____")
if ans.upper() == "IDIOT":
print("\033[32mCorrect!")
corr = corr + 1
else:
print("\033[31mIncorrect")
print("\033[0mThe correct answer was 'idiot'.")
wrng = wrng + 1
ans = input("\n\033[1;34mWho is my favorite LOL player?")
if ans.upper() == "CAPS" or ans.upper() == "PERKZ":
print("\033[32mCorrect!")
corr = corr + 1
else:
print("\033[31mIncorrect")
print("\033[0mThe correct answers were either Caps or Perkz")
wrng = wrng + 1
ttlscr = int(corr / (corr+wrng)*100)
print("\n\033[0mYour final score is:")
print(corr,"/",(corr+wrng))
print(ttlscr, "%\n")
if ttlscr > 90:
print("\033[0mStop taking your own test Alex")
elif ttlscr >= 80:
print("\033[0mPretty good, thats a B!")
elif ttlscr == 69:
print("\033[0mNICE")
else:
print("\033[0mI cant be asked to make a statment regarding your score, try again I guess...")
|
0c54c9540df623bbd5b56c5629bdcfb9849f9d30 | varijak454/python-learning | /sort-numbers.py | 371 | 3.9375 | 4 |
# Importig libraries
import random
# to generate random number list
numbers = random.sample(range(1, 50), 7)
# printing result
print ("Random number list is : " + str(numbers))
# Sorting on Ascending order
numbers.sort()
print("Sording Ascending order:", numbers)
# Sorting on descending order
numbers.sort(reverse=True)
print("Sording Descending Order:", numbers) |
4b99ed12510ec3412cba7a6126b6d88aa6192813 | andrecrocha/Fundamentos-Python | /Fundamentos/Aula 21 - Funções (parte 2)/exercicio101.py | 681 | 4.0625 | 4 | """Desafio 101. Crie um programa que tenha uma função chamada voto(). Ele vai receber o parâmetro de o ano de nascimento
de uma pessoa, retornando um valor literal, VOTO OBRIGATÓRIO, VOTO OPCIONAL, NÃO VOTA"""
def voto(ano):
from datetime import date # Você pode fazer a importação dentro de uma função
atual = date.today().year
idade = atual - ano
if 18 <= idade < 65:
return f'Com {idade} anos: VOTO OBRIGATÓRIO!'
elif idade >= 65:
return f'Com {idade} anos: VOTO OPCIONAL!'
else:
return f'Com {idade} anos: NÃO VOTA!'
# Programa Principal
n = int(input("Em que ano você nasceu? "))
print(voto(n))
|
936b3abfafeee8de92355161e81f2cf35625caf2 | kuaikang/python3 | /基础知识/1.语法基础/13.dict字典-增删改查.py | 658 | 3.71875 | 4 | print("字典是key-value的数据类型".center(50, "-"))
print("字典是无序的,key不能重复")
info = {"stu1": "tom", "stu2": "jack", "stu3": "lucy"}
print(info)
# 添加
info["stu4"] = "bob"
# 修改
info["stu1"] = "zhang"
# 删除
# info.pop("stu2") # 标准删除方法
# del info["stu3"]
# 查找
print('-----',info.get("stu11")) # 不存在的时候返回
# print(info["stu0"]) # 不存在时会报错
print(info)
print()
import sys
for key in info.keys():
sys.stdout.write(key + " ")
print()
for val in info.values():
sys.stdout.write(val + " ")
print()
for key, val in info.items():
sys.stdout.write(key + "-->" + val + " ")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.