blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
42c0521c1e092ccec6538319d1aa4f40d3c01284 | blue-eagle-089/class-110 | /python/SDP.py | 551 | 3.8125 | 4 | import csv
import math
with open('data.csv', newline='')as f:
reader = csv.reader(f)
datalist = list(reader)
data = datalist[0]
def mean(data):
length = len(data)
total = 0
for i in data:
total = total+int(i)
mean = total/length
return mean
squares = []
for a in data:
meandif = int(a)-mean(data)
meandif = meandif**2
squares.append(meandif)
meansum = 0
for b in squares:
meansum = meansum + b
ans = meansum/(len(data)-1)
SD = math.sqrt(ans)
print(SD) |
92f25d14a48f8f182d06f0b07cc13be2e36d5755 | yenext1/python-bootcamp-september-2020 | /lab11/exercise_5.py | 690 | 4.09375 | 4 | # get rand num (1,1M) and return if can be divided by 7,13,and 15
from random import randint
n1 = randint(1,10)
n2 = randint(1,10)
print(f"N1 is {n1}, N2 is {n2}")
for i in range(n1*n2):
num = i+1
if (num % n1 + num % n2 == 0):
print(f"The smallest multiplpliable number is {num}")
break
"""
Uri's comments:
==============
* Very good! This code works.
* You don't really use i in your for loop. You can loop directly on num
with range(1, n1 * n2 + 1)
* Just a note - this works for numbers <= 10, but if the numbers would be
bigger (~6 digits or more), then this algorithm is very unefficient,
and there are algorithms which are much more efficient.
"""
|
eb1282fcb31e82f4b2278cac77e0b6ecd70f7c84 | bread-kun/MyGobang | /gobang_min.py | 6,914 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
class GoBang():
PLAYER_1,PLAYER_2 = 1,2
history_1 = []
history_2 = []
WIN,LOSS = 500000000,-500000000
GUESS_RANGE = 2
def __init__(self, size):
self.map = [[0]*size for i in range(size)]
def move(self, player, node):
assert len(node) is 2 , ("An Error happend on move function because node:",node)
y,x = node
assert self.map[y][x] is 0, ("",node,"点都点过了还想怎样?搞事情是吧")
self.map[y][x] = player
self.get_history(player).append((y,x))
# recall current player abode step, if recall_step is bigger than 1, that will recall enemy step
def recall(self, player, recall_step = 1):
history = self.get_history(player)
assert len(history) > 1, "no more history on current player: {}".format(player)
y,x = history.pop()
self.map[y][x] = 0
if recall_step > 1:
self.recall(self.get_enemy(player), recall_step-1)
def get_history(self, player):
return self.history_1 if player is self.PLAYER_1 else self.history_2
def get_enemy(self,player):
return self.PLAYER_2 if player is self.PLAYER_1 else self.PLAYER_1
# robot win return LOSS; user win return WIN; none win return 0
def think(self,player):
enemy = self.get_enemy(player)
# check enemy win
if self.isWin(enemy):
print("player win!!")
return self.LOSS;
size = len(self.map)
history = self.get_history(enemy)
# 1.as first player
if len(history)<1:
self.move(player,(random.randrange(size//3,size//3*2-1),random.randrange(size//3,size//3*2-1)))
return 0
# 2.as second player;choose a node near center
elif len(history)+len(self.get_history(player)) == 1:
y,x = history[0]
_maybe = ((y-1,x-1),(y+1,x-1),(y+1,x+1),(y-1,x+1))
center = size//2
# min idx and v
minn = [0,999999]
i = 0
for y,x in _maybe:
v = (center-y)**2+(center-x)**2
if v < minn[1]:
minn = [i,v]
i += 1
print("robot none guess: ",(_maybe[minn[0]][0],_maybe[minn[0]][1]))
self.move(player,(_maybe[minn[0]][0],_maybe[minn[0]][1]))
return 0
else:
node = self.guess(player)
print("robot guess: ",node)
self.move(player,node)
if self.isWin(player):
print("robot win!!")
return self.WIN
return 0
def isWin(self,player):
return True if self.analyze(player) == self.WIN else False
# return a node can move
def guess(self,player,deep = 2):
# return a set content node witch around by enemy node depend by _range
def __guess_set__(maps,player,_range=2):
guess_set = set()
for y,x in self.get_history(player):
for i in range(-_range, _range+1):
for j in range(-_range, _range+1):
if y+i<0 or x+j<0 or y+i>=len(maps) or x+j>=len(maps):
continue
if maps[y+i][x+j] is not 0:
continue
guess_set.add((y+i,x+j))
return guess_set
# 模拟行为,return moveable node
def __simulate__(maps,player,guess_set,tree = []):
enemy = self.get_enemy(player)
for n in guess_set:
self.move(player,n)
if self.analyze(player) == self.WIN:
return n
###############################
# key: node position; child: after guess_set; score: score
tree.append({"key":n, "child":[],"child_score":0 ,"score":(self.analyze(player)-self.analyze(enemy))})
_idx = len(tree)-1
# enemy want to get max score, then ignore other score
_enemy_max_scores = -9999
_max_node = []
for enemy_n in __guess_set__(maps,enemy):
self.move(enemy,enemy_n)
##########
_c_score = self.analyze(enemy)-self.analyze(player)
if _c_score > _enemy_max_scores:
_enemy_max_scores = _c_score
_max_node = [enemy_n]
elif _c_score == _enemy_max_scores:
_max_node.append(enemy_n)
##########
self.recall(enemy)
tree[_idx]["child"] = _max_node
tree[_idx]["child_score"] = _enemy_max_scores
###############################
self.recall(player)
# stop the enemy win key
max_enemy_score = [0,-999]
# find min enemy max score and max robot , minus eachother compare
# 1 的所有最大可行域中最小值,2 最大值,对比二者中最终 1 的最大值是否“差异过大”
# 0: node_index, 1 child score
defender_mod = [[0],self.WIN]
i = 0
for n in tree:
# take enemy min score 暂时未考虑多个最小
if n["child_score"] < defender_mod[1]:
defender_mod = [[i],n["child_score"]]
elif n["child_score"] == defender_mod[1]:
defender_mod = [[i],n["child_score"]]
if n["child_score"] > max_enemy_score[1]:
max_enemy_score = [i,n["child_score"]]
pass
i += 1
if max_enemy_score[1]/self.WIN>0.75:
return tree[max_enemy_score[0]]["child"][0]
res_idx_list = defender_mod[0]
rand_idx = random.randrange(0,len(res_idx_list))
return tree[res_idx_list[rand_idx]]["key"]
return __simulate__(self.map, player,__guess_set__(self.map,player))
def analyze(self, player):
def __isWin__(linkcountlist):
for k,v in linkcountlist.items():
if v[0]>=5:
return True
return False
def __link_analy__(linkcountlist,style, flags, flagkey, x,y):
size = len(self.map)
if flags[flagkey] is 1:
if x >= size-1 or x < 0 or y >= size-1 or y < 0:
flags[flagkey] = -1
else:
if self.map[y][x] is player:
linkcountlist[style][0] += 1
elif self.map[y][x] is 0:
flags[flagkey] = 0
else:
flags[flagkey] = -1
history = self.get_history(player)
if len(history)<1:
return 0
res_score = 0
for y,x in history:
link_count_info = {"ls":[1,0],"rs":[1,0],"ver":[1,0],"hor":[1,0]}
flags = {"ls_up":1,"ls_down":1,"rs_up":1,"rs_down":1,"left":1,"right":1,"up":1,"down":1}
for i in range(1,5):
__link_analy__(link_count_info,"ls",flags,"ls_up",x-i,y-i)
__link_analy__(link_count_info,"ls",flags,"ls_down",x+i,y+i)
__link_analy__(link_count_info,"rs",flags,"rs_up",x+i,y-i)
__link_analy__(link_count_info,"rs",flags,"rs_down",x-i,y+i)
__link_analy__(link_count_info,"ver",flags,"left",x-i,y)
__link_analy__(link_count_info,"ver",flags,"right",x+i,y)
__link_analy__(link_count_info,"hor",flags,"up",x,y-i)
__link_analy__(link_count_info,"hor",flags,"down",x,y+i)
if __isWin__(link_count_info):
return self.WIN
# 遮挡值 0 + 1 | 1 + 1 | 0 + 0
link_count_info["ls"][1] = -flags["ls_up"] + (-flags["ls_down"])
link_count_info["rs"][1] = -flags["rs_up"] + (-flags["rs_down"])
link_count_info["ver"][1] = -flags["left"] + (-flags["right"])
link_count_info["hor"][1] = -flags["up"] + (-flags["down"])
_t_score = 0
for v in link_count_info.values():
link,block = v[0],v[1]
if link > 4:
_t_score += 999999999
break
assert block in [0,1,2], "an Error in value count with value link:{} block:{}".format(link,block)
if block is 2:
_t_score += 1
elif block is 1:
_t_score += 10**link/2
else:
_t_score += 10**link
res_score += _t_score
return res_score |
c78eb372194d81c21efe8005bedfa6a4a807e7cb | RadkaValkova/SoftUni-Web-Developer | /Programming Fundamentals Python/Preparation/Next Happy Year.py | 405 | 3.703125 | 4 | current_year = int(input())
next_happy_year = current_year
while True:
a = str(next_happy_year)[0]
b = str(next_happy_year)[1]
c = str(next_happy_year)[2]
d = str(next_happy_year)[3]
if a != b and a != c and a != d and b != c and b != d and c != d:
next_happy_year = (f'{a}{b}{c}{d}')
print(next_happy_year)
break
next_happy_year = int(f'{a}{b}{c}{d}') + 1
|
fa42a64780f1d8e4132362adc54f18e70f0777fe | Lukezio/gamestyle-imitation | /bounding_box.py | 1,788 | 3.84375 | 4 | """This module provides all functionalities for bounding boxes"""
from point import Point
class BoundingBox:
"""Represents a bounding box"""
TL_TO_BR = 0
BR_TO_TL = 1
POINT_ORDER = 0
def __init__(self, label, point_1, point_2):
self.label = label if label is not None else ''
self.top_left = point_1
self.bottom_right = point_2
def set_boundings(self, point_1, point_2):
"""Set new boundings"""
self.top_left = point_1
self.bottom_right = point_2
def set_label(self, label):
"""Set the label"""
self.label = label
def get_label(self):
""""Returns the label"""
return self.label
def get_top_left(self):
"""Returns point 1"""
return self.top_left
def get_point_2(self):
"""Returns point 2"""
return self.bottom_right
@staticmethod
def create_from_points(point_1, point_2, label=None):
"""Create a bounding box from 2 points"""
_p1 = Point.get_top_left(point_1, point_2)
_p2 = Point.get_top_left(point_1, point_2)
if BoundingBox.POINT_ORDER == BoundingBox.TL_TO_BR:
return BoundingBox(label, _p1, _p2)
return BoundingBox(label, _p2, _p1)
def __str__(self):
"""tostring"""
return "Label: " + self.label + ", TL: " + str(self.top_left) + ", BR: " + str(self.bottom_right)
if __name__ == "__main__":
#For testing
p1 = Point(20, 300)
p2 = Point(50, 400)
p3 = Point(50, 100)
p4 = Point(300, 20)
bb1 = BoundingBox("test", p1, p2)
bb2 = BoundingBox("test", p3, p4)
bb3 = BoundingBox.create_from_points(p2, p4)
print(p1)
print(p2)
print(p3)
print(p4)
print(bb1)
print(bb2)
print(bb3)
|
f9a45ece6c4b02ab294cc9c658658b439182fd4f | SLarbiBU/Homework | /ps1pr1.py | 1,408 | 3.890625 | 4 | #
# ps1pr2.py - Problem Set 1, Problem 1
#
# Indexing and slicing puzzles
#
# name: Sarah Larbi
# email: slarbi@bu.edu
#
# If you worked with a partner, put his or her contact info below:
# partner's name:n/a
# partner's email: n/a
#
#
# List puzzles
#
pi = [3, 1, 4, 1, 5, 9]
e = [2, 7, 1]
# Example puzzle (puzzle 0):
# Creating the list [2, 5, 9] from pi and e
answer0 = [e[0]] + pi[-2:]
print(answer0)
# Puzzle 1:
# creating the list[7, 1] from pi and e
answer1 = [e[1] , e[2]]
print(answer1)
# Puzzle 2
# Creating the list [9,1,1] from pi and e
answer2 = pi[-1:0:-2]
print(answer2)
# Puzzle 3:
# Creating the list [1,4,1,5,9] from pi and e
answer3 = pi[1:]
print(answer3)
# Puzzle 4:
# Creating the list [1,2,3,4,5] from pi and e
answer4 = e[-1::-2] + pi[0::2]
print(answer4)
#
# String puzzles
#
b = 'boston'
u = 'university'
t = 'terriers'
# Puzzle 5
# Creating the string 'bossy'
answer5 = b[:3] + t[-1] + u[-1]
print(answer5)
# Puzzle 6:
# Creating the string 'stone'
answer6 = b[2:] + t[1]
print(answer6)
# Puzzle 7:
# Creating the string 'street'
answer7 = b[2:4] + t[2] + 2*t[1] + t[0]
print(answer7)
# Puzzle 8:
# Creating the string 'nonononono'
answer8 = 5*b[-1:-3:-1]
print(answer8)
# Puzzle 9:
# Creating string 'bestever'
answer9 = b[0] + u[4::2] + t[1] + u[3:6]
print(answer9)
# Puzzle 10:
# Creating string 'serenity'
answer10 = t[-1::-2] + b[-1] + u[-3::1]
print(answer10)
|
f3b280b452dd96cc471b8e91db79423abc1a979d | richardochandra/PrakAlPro-B | /LAB-4-Modular Programing.py | 2,602 | 3.5625 | 4 | # Richardo Chandra H
# 71200642
# Universitas Kristen Duta Wacana
# Pertemuan 4 ( Modular Programming )
""" Pak Roni mendapat pekerjaan baru yang sangat sensitif dengan waktu sehingga dia harus benar-benar melakukan hal yang diperintahkan oleh atasannya di waktu yang
sudah di tentukan oleh atasannya. Pak Roni merasa terlalu ribet jika dia harus membuka kalkulator untuk mengkonversi dari satuan waktu ke satuan waktu yang lain sehingga
ia meminta untuk dibuatkan program kalkulator konversi waktu dengan batasan jam, menit, dan detik
input :
- memilih konversi waktu
- jumlah waktu
proses :
- menghitung waktu
-menampung pada suatu variabel
output :
- hasil dari konversi waktu
"""
#Code
def jam_menit(jam):
menit = jam *60
return menit
def menit_detik(menit):
detik = menit*60
return detik
def detik_menit(detik):
menit = detik/60
return menit
def menit_jam(menit):
jam = menit/60
return jam
def jam_detik(jam):
detik = (jam*60)*60
return detik
def detik_jam(detik):
jam = (detik/60)/60
return jam
print("=== Selamat datang pada program kalkulator konversi waktu ===")
print("""Apa konversi waktu yang ingin anda gunakan?
1. Jam ke menit
2. Menit ke detik
3. Jam ke detik
4. Detik ke menit
5. Menit ke jam
6. Detik ke jam
""")
try :
jenis = int(input("Masukan pilihan konversi (hanya angka) : "))
if jenis == 1 :
jam = float(input("Masukan jam yang ingin anda konversi ke menit = "))
print(f"Jam yang anda masukan menjadi {jam_menit(jam)} menit")
elif jenis == 2 :
menit = float(input("Masukan menit yang anda ingin konversi ke detik = "))
print(f"Menit yang anda masukan menjadi {menit_detik(menit)} detik")
elif jenis == 3 :
jam = float(input("Masukan jam yang ingin anda konversi ke detik = "))
print(f"Jam yang anda masukan menjadi {jam_detik(jam)} detik")
elif jenis == 4 :
detik = int(input("Masukan detik yang anda ingin konversi ke menit = "))
print(f"Detik yang anda masukan menjadi {detik_menit(detik)} menit")
elif jenis == 5 :
menit = float(input("Masukan menit yang anda ingin konversi ke jam = "))
print(f"Menit yang anda masukan menjadi {menit_jam(menit)} jam")
elif jenis == 6 :
detik = int(input("Masukan detik yang anda ingin konversi ke jam = "))
print(f"Detik yang anda masukan menjadi {detik_jam(detik)} jam")
else :
print("Input yang anda masukan salah")
except :
print("Input yang anda masukan tidak valid") |
1716bbc31bd9f0f91114e31e43b3a50405c03009 | UrvashiBhavnani08/Python | /Maximum_three_numbes.py | 155 | 3.71875 | 4 | def Maximum(num1, num2, num3):
tup1 = (num1, num2, num3)
return max(tup1);
num1 = 100
num2 = 202
num3 = 30
print(Maximum(num1,num2,num3))
|
140cc4a1d14db1a453f8280a279850c2ab712bce | lldenisll/learn_python | /aulas/busca_sequencial.py | 184 | 3.6875 | 4 | def busca(lista,elemento):
for i in range(len(lista)):
if lista[i] == elemento:
return i #fazer retornar a posição sem usar a função index
return False |
4cfe556db8573dd1cef05719c712d1dd9198d0cb | piyush-arora/kodingBackup | /laravel/public/ML/hello_world/hello_world.py | 885 | 3.859375 | 4 | # for reshaping
import numpy as np
# for ML
import sklearn
# Describe features as arrays as training sets
features = [
[140 , 1] , # 140g smooth
[130 , 1] , # 130d smooth
[150 , 0] , # 150g bumpy
[170 , 0] , # 170g bumpy
];
# Decribe labels as arrays as right labels for corresponding each set
labels = [ 0, # apple
0, # apple
1, # orange
1 # orange
];
# Create an empty classifier called tree
classifier = tree.DecisionTreeClassifier();
# train the classifier with the training data
classifier.fit(features,labels);
# new data to test out algo
data = [150,0];
# reshape inorder to make it work
np.reshape(data, (-1, 1))
# predict the label
print classifier.predict(np.reshape(data, (1, -1)));
|
e63042bd361dd38beb304b96fba2b10e2bdadfd1 | jinxiang2/L1 | /Action2 jx.py | 752 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
班里有5名同学,现在需要你用Python来统计下这些人在语文、英语、数学中的平均成绩、
最小成绩、最大成绩、方差、标准差。然后把这些人的总成绩排序,得出名次进行成绩输出
(可以用numpy或pandas)
@author: JinXiang2
"""
from pandas import Series, DataFrame
data = {'语文': [68, 95, 98, 90,80], '数学': [65, 76, 86, 88, 90], '英语': [30, 98, 88, 77, 90]}
df1 = DataFrame(data)
df2 = DataFrame(data, index=['张飞', '关羽', '刘备', '典韦', '许褚'], columns=['语文', '数学', '英语'])
print(df2)
print(df2.describe())
print(df2.var())
zongfen=df2.sum(1)
zongfen2= zongfen.sort_values(0, ascending=False)
print(zongfen2) |
be395b94f6424f6c82a65e1ac37d2dd770bbbf48 | 5064/algorithms | /sort/merge_sort.py | 958 | 4.125 | 4 | def merge_sort(list_, left, right):
if right - left == 1:
return
mid = left + (right-left) // 2
# 左半分 [left, mid) をソート
merge_sort(list_, left, mid)
# 右半分 (mid, right] をソート
merge_sort(list_, mid, right)
# 左と右のソート結果をコピー(右はリバース)
buffer = []
i = left
while i < mid:
buffer.append(list_[i])
i += 1
i = right - 1
while i >= mid:
buffer.append(list_[i])
i -= 1
# merge
iter_left = 0
iter_right = len(buffer) - 1
i = left
while i < right:
if buffer[iter_left] <= buffer[iter_right]:
list_[i] = buffer[iter_left]
iter_left += 1
else:
list_[i] = buffer[iter_right]
iter_right -= 1
i += 1
if __name__ == "__main__":
list_ = [8, 2, 5, 9, 3, 6, 1, 4, 7, 0]
merge_sort(list_, 0, len(list_))
print(list_)
|
3f2cb4cfdf35c690a36f078a52afec79bb4e53a0 | darrenwshort/itp_week_3 | /day_3/exercise.py | 1,749 | 3.546875 | 4 | import os
import requests
import json
import openpyxl
response = requests.get("https://rickandmortyapi.com/api/character")
# print(response)
# json.loads() - takes text string and converts it to dict (clean_data)
clean_data = json.loads(response.text)
# grab only results list from clean_data dict
# 'results' is list of character dicts
results = clean_data['results']
############## Rick & Morty API exercise ################
# go through results for each row in an excel spreadsheet
# grab the name, species, gender, location name
# create workbook
wb = openpyxl.Workbook()
# name of output file/workbook
output_file = 'RickNMortyOutput.xlsx'
# grab sheet; randomly grabbing active sheet
sheet = wb.active
# create headers/column titles on 1st row of sheet
sheet['A1'] = "Name"
sheet['B1'] = "Species"
sheet['C1'] = "Gender"
sheet['D1'] = "Location"
################## FOR SELF ONLY ######################
# clear terminal for better readabilty of output/errors
# when running script
os.system('clear')
#######################################################
# initialize counter to 2 (2nd row; "1st row" after header row)
# loop through each Rick and Morty character, populating 1 row
# per show character.
# increment 'counter' as each character is processed.
counter = 2
for character in results:
sheet['A' + str(counter)] = character['name']
sheet['B' + str(counter)] = character['species']
sheet['C' + str(counter)] = character['gender']
sheet['D' + str(counter)] = character['location']['name']
counter += 1
# delete existing output file before save
# try-except in case file doesn't exist.
try:
os.remove(output_file)
except:
pass
# save workbook to file.
wb.save(filename = output_file)
|
9d9d79e9640bd41ef4633a70d7c3dd0331d98c59 | wiggiddywags/python-playground | /pascals_triangle.py | 779 | 4.46875 | 4 |
# Udacity Exercise: Write a function to produce the next layer of Pascal's triangle
# Each layer is one larger than the previous layer, and each element in
# the new layer is the sum of the two elements above it in the previous
# layer. For example, `(1, 3, 3, 1) -> (1, 4, 6, 4, 1)`.
# Add a layer/row to Pascal's triangle.
# Each layer should be a tuple.
def add_layer(triangle):
new_row = list()
last_row = triangle[-1]
for a, b in zip(last_row + (0,), (0,) + last_row):
new_row.append(a + b)
triangle.append(tuple(new_row))
pascals_triangle = [
(1,),
(1, 1),
(1, 2, 1),
(1, 3, 3, 1),
]
# Add a few layers to test.
for _ in range(7):
add_layer(pascals_triangle)
# Print Triangle
for row in pascals_triangle:
print(row)
|
3bd3de9948e931c067350b65c5982b94354591ed | alekseiaks/asjfgh | /task_2 .py | 266 | 3.953125 | 4 | seconds = int(input("Какое количество секунд перевести в формат времени - чч:мм:сс? "))
hh = seconds // 3600
mm = (seconds - hh * 3600) // 60
ss = seconds - mm * 60 - hh * 3600
print(f"{hh:02d}:{mm:02d}:{ss:02d}")
|
27d54a10d99da8f9fce0d22521b586e50e816189 | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/16-String-Swapping/String_swapping.py | 494 | 4.25 | 4 | # purpose Create a single string separated with space from two strings by swapping the character at position 1
string = input("Enter 2 string separated by space : ")
string = string.split(' ')
# swapping two at position 1
print(string[0][0] + string[1][1] + string[0][2:] + " " + string[1][0] + string[0][1] + string[1][2:])
# swapping and making the swapped item UPPERCASE
print(string[0][0] + string[1][1].upper() + string[0][2:] + " " + string[1][0] + string[0][1].upper() + string[1][2:])
|
aa7b05e701a74934562ca0ddba710606778a596c | Bohdan-Panamarenko/oop-second-lab | /2.py | 755 | 3.78125 | 4 | class Rational:
def __init__(self, numerator: int = 1, denominator: int = 1):
biggest_dem = self._biggest_denominator(numerator, denominator)
if biggest_dem != 0:
numerator /= biggest_dem
denominator /= biggest_dem
self._numerator = int(numerator)
self._denominator = int(denominator)
def __str__(self):
return f"{self._numerator}/{self._denominator}"
def fraction(self):
return self._numerator / self._denominator
def _biggest_denominator(self, a: int, b: int):
while a != 0 and b != 0:
if a > b:
a = a % b
else:
b = b % a
return a + b
r = Rational(2, 8)
print(r)
print(r.fraction())
|
f87b68525023f7c231b86614afa65e8c681a2bbb | jinshunlee/ctci | /2-linked-lists/1_removeDups.py | 1,314 | 3.890625 | 4 | # Remove Dups! Write code to remove duplicates from an unsorted linked list.
# FOLLOW UP
# How would you solve this problem if a temporary buffer is not allowed?
from LinkedList import LinkedList
# Time O(n)
# Space O(n)
def removeDuplicates(xs):
seen = set()
cur = xs.head
prev = None
while cur is not None:
if cur.data in seen:
prev.next = cur.next
else:
seen.add(cur.data)
prev = cur
cur = cur.next
return xs
# Time O(n^2)
# Space O(1)
def removeDuplicatesFollowUp(xs):
pt1 = xs.head
while (pt1.next is not None):
cur_value = pt1.data
pt2 = pt1.next
while(pt2.next is not None):
if cur_value == pt2.data:
pt1.next1 = pt1.next.next
else:
pt2 = pt2.next
pt1 = pt1.next
return xs
if __name__ == "__main__":
xs = LinkedList()
xs.add(1)
xs.add(3)
xs.add(3)
xs.add(1)
xs.add(5)
ys = LinkedList()
ys.add(1)
ys.add(2)
ys.add(3)
ys.add(4)
ys.add(5)
removeDuplicates(xs).print_list()
removeDuplicates(ys).print_list()
removeDuplicatesFollowUp(xs).print_list()
removeDuplicatesFollowUp(ys).print_list()
|
3362a29d83724e4dfdb2c666510a88eca0ae5a4d | brian-tle/csc645-networks | /labs/lab8/server.py | 3,938 | 3.8125 | 4 | ########################################################################################################################
# Class: Computer Networks
# Date: 02/03/2020
# Lab3: TCP Server Socket
# Goal: Learning Networking in Python with TCP sockets
# Student Name:
# Student ID:
# Student Github Username:
# Instructions: Read each problem carefully, and implement them correctly. Your grade in labs is based on passing
# all the unit tests provided.
# The following is an example of output for a program that pass all the unit tests.
# Ran 3 tests in 0.000s
# OK
# No partial credit will be given. Labs are done in class and must be submitted by 9:45 pm on iLearn.
########################################################################################################################
######################################### Server Socket ################################################################
"""
Create a tcp server socket class that represents all the services provided by a server socket such as listen and accept
clients, and send/receive data. The signatures method are provided for you to be implemented
"""
import pickle
import socket
from threading import Thread
# import urllib.request
class Server(object):
def __init__(self, ip_address='127.0.0.1', port=6000):
# create an INET, STREAMing socket
self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
self.ip = ip_address
self.port = port
self.serversocket.bind((ip_address, port))
def _listen(self):
"""
Private method that puts the server in listening mode
If successful, prints the string "Listening at <ip>/<port>"
i.e "Listening at 127.0.0.1/10000"
:return: VOID
"""
try:
self.serversocket.listen(5)
# uncomment the line below to router point of entry ip address
# self.ip = urllib.request.urlopen('http://ifconfig.me/ip').read()
print("Listening for new peers at " + str(self.ip) + "/" + str(self.port))
except Exception as error:
print(error)
def _accept_clients(self):
"""
Accept new clients
:return: VOID
"""
while True:
try:
# accept connections from outside
(clientsocket, address) = self.serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a threaded server
Thread(target=self.client_thread, args=(clientsocket, address)).start()
print("Client: " + str(address[1]) + " just connected")
except Exception as error:
print(error)
# noinspection PyMethodMayBeStatic
def append_to_file(self, data, file="connFile.txt"):
f = open(file, "a+")
f.write(data)
f.write('\n')
f.close()
# noinspection PyMethodMayBeStatic
def _send(self, client_socket, data):
"""
:param client_socket:
:param data:
:return:
"""
data = pickle.dumps(data)
client_socket.send(data)
# noinspection PyMethodMayBeStatic
def _receive(self, client_socket, max_buffer_size=4096):
raw_data = client_socket.recv(max_buffer_size)
return pickle.loads(raw_data)
def client_thread(self, clientsocket, address):
"""
Implement in lab4
:param clientsocket:
:param address:
:return:
"""
server_ip = str(address[0] + "/" + str(self.port))
client_id = address[1]
data = {'clientid': client_id, 'server_ip': server_ip}
self._send(clientsocket, data)
def run(self):
self._listen()
self._accept_clients()
|
7a18406342ff44d555b6f737f01629128455ed04 | bhavybhatia/password-generator | /pasgenerator.py | 359 | 3.9375 | 4 | import random
chars="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789!@#$%^&*"
len=int(input("Enter Length of password : "))
n=int(input("Enter number of passwords you want : "))
passwords=''
for i in range(n):
passwords=''
for c in range(len):
passwords+=random.choice(chars)
print(passwords)
input(" Press any key to exit !!! ")
|
ac75656a5b4c2420e9a32095cb1f14c46ad3dcf0 | Jaybsoni/Orbit-Simulator | /objects.py | 2,634 | 3.78125 | 4 | class SpaceDebri(): # Quick Update
def __init__(self, mass, position, velocity):
"""
:param mass: float
:param position: list of floats
:param velocity: list of floats
:param acceleration: list of floats
Initializes an instance of the SpaceDebri object with above specifications
"""
self.mass = mass
self.position = position
self.velocity = velocity
def dist(self, other):
"""
:param other:
:return:
calculates the distance between two instances of the spacedebri objects
"""
x1 = self.position[0]
x2 = other.position[0]
y1 = self.position[1]
y2 = other.position[1]
z1 = self.position[2]
z2 = other.position[2]
r = ((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)**0.5
return r
def update_position(self):
# updates the position field based on the velocity of the space debri (time evolves it)
delta_x = (self.velocity[0])*self.dt
delta_y = (self.velocity[1])*self.dt
delta_z = (self.velocity[2])*self.dt
new_x = self.position[0] + delta_x
new_y = self.position[1] + delta_y
new_z = self.position[2] + delta_z
self.position = [new_x, new_y, new_z]
# print("The new position is ({},{},{})".format(new_x,new_y,new_z)) for debug purposes
@classmethod
def from_string(cls, string_data):
# alternate constructor of instances of space debri (to easily make instances via .txt or .csv files)
mass, pos_x, pos_y, pos_z, vel_x, vel_y, vel_z = string_data.split(" ")
pos = [float(pos_x), float(pos_y), float(pos_z)]
vel = [float(vel_x), float(vel_y), float(vel_z)]
return cls(float(mass), pos, vel)
def update_velocity(self):
# updates the velocity of the space debri via the acceleration
delta_x = (self.acceleration[0]) * self.dt
delta_y = (self.acceleration[1]) * self.dt
delta_z = (self.acceleration[2]) * self.dt
new_x = self.velocity[0] + delta_x
new_y = self.velocity[1] + delta_y
new_z = self.velocity[2] + delta_z
self.velocity = [new_x, new_y, new_z]
def collision_check(self, other):
# determines if the space debri instance is within contact distance of another piece of space debri
distance = self.dist(other)
radius1 = self.radius
radius2 = other.radius
if (radius1 + radius2) >= distance:
return True
def relative_position_vector(self, other):
# returns a lst of positions which corresponds to the vector going from self --> other and vice versa
x1 = self.position[0]
x2 = other.position[0]
y1 = self.position[1]
y2 = other.position[1]
z1 = self.position[2]
z2 = other.position[2]
S_O = [(x2 - x1), (y2 - y1), (z2 - z1)]
O_S = [-1*S_O[0], -1*S_O[1], -1*S_O[2]]
return S_O, O_S |
1e87f8304843df12c463f191b24b66a5ecffc2ef | code5023/python_proj | /1week/homework-04-diamond.py | 1,043 | 3.59375 | 4 | total_lines = 10 # 표현 할 전체 라인수
lines = int(total_lines / 2) # 상단 하단을 구분하기 위한 중간 라인
print("===== 다이아몬드 =====")
# # 우측만 튀어나온 형태
# for i in range(1, total_lines):
# if i <= lines:
# zero = lines - i
# one = i
# print("1 " * one)
# else:
# zero = i - lines
# one = total_lines - i
# print("1 " * one)
# # 좌측만 튀어나온 형태
# for i in range(1, total_lines):
# if i <= lines:
# zero = lines - i
# one = i
# print(" " * zero + "1")
# else:
# zero = i - lines
# one = total_lines - i
# print(" " * zero + "1")
# 전체 다이아몬드 형태
for i in range(1, total_lines):
if i <= lines:
zero = lines - i
one = (i * 2) - 1
print("0" * zero + "1" * one + "0" * zero)
else:
zero = i - lines
one = ((total_lines - i) * 2) - 1
print("0" * zero + "1" * one + "0" * zero)
|
cb306dff4134be19d2940658e141d74f4b1871ea | Ktsunezawa/Python-practice | /3step/0702/for_dic.py | 282 | 3.515625 | 4 | addresses = {
'名無権兵衛': '千葉県千葉市美芳町1−1−1',
'山田太郎': '東京都練馬区蔵王町2−2−2',
'鈴木花子': '埼玉県所沢市大竹町3−3−3',
}
for key, value in addresses.items():
print(key, ':', value)
|
7579afdc211671b68087eccbc1c6af6919ff700c | Seanistar/Carmen | /science/4_maxtrices.py | 550 | 3.84375 | 4 | # functions for working with matrices
#
def shape(A):
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return num_rows, num_cols
def make_matrix(num_rows, num_cols, entry_fn):
return [[entry_fn(i, j) for j in range(num_cols)]
for i in range(num_rows)]
def matrix_add(A, B):
if shape(A) != shape(B):
raise ArithmeticError("cannot add matrices with different shapes")
num_rows, num_cols = shape(A)
def entry_fn(i, j): return A[i][j] + B[i][j]
return make_matrix(num_rows, num_cols, entry_fn)
|
97b711496e5c087883c82ea79f9d2b1d6c4d5362 | Murbr4/Python | /PythonExercicios/ex015.py | 192 | 3.65625 | 4 | dias = int(input('Quantos dias você ficou com o carro: '))
km = float(input('quantos km rodado: '))
total = (dias * 60) + (km * 0.15)
print('O preço total a pagar é {:.2f}'.format(total)) |
03c87803bec04a8fd63508a7f23bb7489ac05153 | shiraz-30/Intro-to-Python | /Python/Python_concepts/twoD_list.py | 306 | 3.6875 | 4 | li = [[1,2,3], [4,5,6], [7,8,9]]
for i in range(0, len(li)):
print(li[i])
y = []
n = int(input())
m = int(input())
for i in range(0, n):
y.append([]) # appending the 'i'th row
for j in range(0, m):
x = int(input())
y[i].apppend(x)
print(y)
print(y[0][1]) # accessing 1st column of the 0th row
|
b4448e467b38fefe05ef32a4ec43f6a89eb5ccab | fulcorno/Settimane | /Settimana04/leggidato.py | 927 | 4.09375 | 4 | # Lettura di un dato dall'utente controllando che sia nell'intervallo giusto
# ESEMPIO: leggiamo un dato intero tra 1 e 100
valido = False
while not valido:
dato = int(input("Inserisci un numero tra 1 e 100: "))
if dato < 1 or dato > 100: # condizione di errore
print('Dato errato, ripeti')
else:
valido = True
valido = False
while not valido:
dato = int(input("Inserisci un numero tra 1 e 100: "))
if 1 <= dato <= 100: # condizione di ok
valido = True
else:
print('Dato errato, ripeti')
while not valido:
dato = input("Inserisci un numero tra 1 e 100: ")
if not dato.isnumeric():
print('Deve essere numerico')
else:
dato = int(dato)
if dato < 1 or dato > 100: # condizione di errore
print('Dato errato, ripeti')
else:
valido = True
# while valido is True:
# while valido == True:
print(dato)
|
c21acb3cfdc8914512ca30d88c5ccda754054930 | T3ch1n/MathProject | /main.py | 891 | 3.859375 | 4 | from tkinter import *
window = Tk()
window.title("My application")
window.geometry("500x500")
head = Label(text="Welcome to Application").pack()
def calculation():
age=txt_age.get()
age=int(age)
disease=txt_disease.get()
disease=int(disease)
if disease==1:
disease=True
else:
disease=False
print(age)
print(disease)
txt_age=StringVar()
label1 = Label(text="อายุเท่าไหร่").pack()
entry1 = Entry(window,textvariable=txt_age).pack()
txt_disease=StringVar()
label2 = Label(text="มีโรคประจำตัวไหม").pack()
label3 = Label(text="ถ้ามีใส่ 1 ถ้าไม่มี่ใส่ 2").pack()
entry2 = Entry(window,textvariable=txt_disease).pack()
btn1 = Button(window,text="calculate",command=calculation).pack()
window.mainloop() |
e94ae8c0ff205b067db3b5d8beaad0406fbeef23 | joaovlev/estudos-python | /Desafios/Mundo 2/desafio042.py | 816 | 4.1875 | 4 | # Refazendo o exercício 35 do mundo 1 (triângulo)
print('Analisador de Triângulos\n')
r1 = float(input('Digite um segmento: '))
r2 = float(input('Digite outro segmento: '))
r3 = float(input('Digite mais um segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2 and r1==r2==r3:
print('Os segmentos podem formar um triângulo!\n')
print('O triângulo será equilátero.')
elif r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2 and r1 == r2 or r2 == r3 or r1 == r3:
print('Os segmentos podem formar um triângulo!\n')
print('O triângulo será isósceles.')
elif r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2 and r1 != r2 != r3:
print('Os segmentos podem formar um triângulo!\n')
print('O triângulo será escaleno.')
else:
print('Seus segmentos não podem formar um triângulo')
|
12e58e334c8b2376febc0a1550ed574a2ed9285f | Aditya-Pundir/VSCode_python_projects | /VS_Code_Folder_2/python_learning_in_1_video_cwh/pr_2_Q5.py | 171 | 3.53125 | 4 | letter = "Dear Harry, This Python course is nice! Thanks!"
print(letter)
formatted_letter = "\nDear Harry,\n\tThis Python course is nice!\nThanks!"
print(formatted_letter) |
68f0d7933980ca89b97f1ac9d1ab5d8f8e8389dd | ToT-2020-PA/digital.chest | /Test_Cel.py | 138 | 3.875 | 4 | t1 = float(input('qual a temperatura em Fahrenheit? °F '))
t2 = (t1-32)*(5/9)
print('A temperatura em Celsius é {:.1f}°C'.format(t2)) |
bc3397b8b71118e290b4c04a945a4f7a079fdfec | ngrundback/Fall_2019_Lessons | /daily_problem/49_binary_tree_check.py | 777 | 3.875 | 4 | class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.root = False
def binary_tree_check(root, l=None, r=None):
if root is None:
return True
if (l != None and root.data <= l.data):
return False
if (r != None and root.data >= r.data):
return False
return binary_tree_check(root.left, l, root) and binary_tree_check(root.right, root, r)
root = Node(10)
root.left = Node(6)
root.right = Node(12)
root.right.right = Node(100)
root.right.left = Node(11)
root.left.left = Node(1)
root.left.right = Node(7)
print(binary_tree_check(root))
# 10
# 6 12
# 1 5 50 100
|
200bafee7d2e29f111111761fe73e13869903719 | siramkalyan/wordcheats | /__init__.py | 594 | 3.71875 | 4 | from itertools import permutations
from nltk.corpus import words
def valid_word(list_of_words,list_of_sizes):
if type(list_of_sizes) == int :
list_of_sizes = list(list_of_sizes)
list_of_english_words=[]
for i in list_of_sizes:
possible_permutations=list(permutations(list_of_words,i))
for j in possible_permutations:
k="".join(p for p in j)
if k in words.words():
if k not in list_of_english_words:
list_of_english_words.append(k)
return list_of_english_words
|
8877f359a4cde598d561c2c72c790aa7c8b67f04 | jorgeOmurillo/Python | /sorting and searching/insert_sort.py | 288 | 3.828125 | 4 | def insert_sort(A):
for x in range(1, len(A)):
current = A[x]
index = x
while index > 0 and A[index-1] > current:
A[index] = A[index-1]
index -= 1
A[index] = current
return A
print(insert_sort([78,89,123,2,5,9,1]))
|
85572e470c172c4f1ceae678eeb0ae5b2a806d18 | bexcite/interview-zoo | /codility/2-cyclic-rotation.py | 1,386 | 4.0625 | 4 | '''
A zero-indexed array A consisting of N integers is given. Rotation of the array
means that each element is shifted right by one index, and the last element of
the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The
goal is to rotate array A K times; that is, each element of A will be shifted
to the right by K indexes.
Write a function:
def solution(A, K)
that, given a zero-indexed array A consisting of N integers and an integer K,
returns the array A rotated K times.
For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should
return [9, 7, 6, 3, 8].
Assume that:
N and K are integers within the range [0..100];
each element of array A is an integer within the range [-1,000..1,000].
In your solution, focus on correctness. The performance of your solution will
not be the focus of the assessment.
'''
def solution(A, K):
buf = [None] * K
# Copy last K elements to temp buffer
for i in xrange(1, K + 1):
buf[-i] = A[-i]
# Shift elements by K, from end of array
for i in xrange(1, len(A) - K + 1):
A[-i] = A[-i - K]
# Copy temp buf to array
for i in xrange(K):
A[i] = buf[i]
return A
if __name__ == '__main__':
assert solution([3, 8, 9, 7, 6], 3) == [9, 7, 6, 3, 8]
assert solution([3, 8, 9, 7, 6], 1) == [6, 3, 8, 9, 7]
|
6a7298ac93df72e398f28fc909350f19049cac47 | sabrinachowdhuryoshin/30-Days-of-Code-Challenge-HackerRank | /Day04.py | 301 | 3.875 | 4 | # Day04
# Given an integer n, print its first 10 multiples. Each multiple n x i (where 1 <= i <= 10) should be printed on a new line in the form: n x i = result.
# Constraints 2 <= n <= 20
# The code starts here:
n = int (input())
for i in range (1,11):
x = n*i
print (n, "x", i, "=", x)
|
735addbec8387512368fc3e3acc6b44ad2866e07 | birgire18/Assignment-5-Algorithms-and-git | /git_sequence.py | 341 | 3.84375 | 4 | n = int(input("Enter the length of the sequence: ")) # Do not change this line
count = 3
sequence = [1, 2, 3]
print(sequence[0])
print(sequence[1])
print(sequence[2])
while count != n:
newnum = int(sequence[count-3]) + int(sequence[count-2]) + int(sequence[count-1])
sequence.append(newnum)
print(sequence[count])
count += 1
|
574b2f94c787bb2c0d32ca02c06634509c589a1c | iarimanfredi/Esercitazione | /main.py | 267 | 3.84375 | 4 | def tree(n):
for j in range(n+1):
print('{}'.format(mess), end = ' ')
print('\n')
print('Scrivi il messaggio da stampare e quante volte lo vuoi stampare\n')
mess = input('Messaggio --> ')
t = int(input('Numero --> '))
for i in range(t):
tree(i)
|
130b5eb05fffcd522e3abde49e714d028e996b4b | fivetentaylor/intro_to_programming | /leet_solutions/taylor_swap_nodes_in_pairs.py | 1,078 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(iterable):
head = ListNode(0)
ptr = head
for i in iterable:
ptr.next = ListNode(i)
ptr = ptr.next
if head.next:
return head.next
def linked_to_list(linked):
ptr = linked
l = []
while ptr:
l.append(ptr.val)
ptr = ptr.next
return l
def swap_pairs(head: ListNode) -> ListNode:
# if empty or sinlge node list just return
if head is None or head.next is None:
return head
# put a dummy node at the front of the list
# so the first swap can be handled the same
# as the subsequent swaps
front = ListNode(-1)
front.next = head
l = head
r = head.next
head = front
while True:
l.next = r.next
front.next = r
r.next = l
front = l
if l.next is None:
break
l = l.next
if l.next is None:
break
r = l.next
return head.next
|
2754829119354f71fa4a181fb9b560da5223dfe7 | rafaxtd/URI-Judge | /AC02/donation.py | 208 | 3.578125 | 4 |
buy = True
vic = 0
while buy == True:
n = float(input())
if n == -1.0:
buy = False
else:
vic += n
real = vic * 2.50
print(f'VC$ {vic:.2f}')
print(f'R$ {real:.2f}')
|
45b4cf78245c2b4dde6b5df53c262eba40a92058 | daniel-reich/ubiquitous-fiesta | /6CGomPbu3dK536PH2_15.py | 129 | 3.625 | 4 |
def accumulating_list(lst):
relst=[]
for i in range(1,len(lst)+1):
relst.append(sum(lst[:i]))
return relst
|
3db957615cb0f6fe50d1ae5583777cac35349e9f | SCismycat/AlgoWithLeetCode | /algos/Random_areas.py | 355 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Leslee
# @Email : leelovesc@gmail.com
# @Time : 2019.10.15 13:33
import random
# 给定一个1-5的函数,随机生成1-7的函数
def random7():
a = random.randint(0,5)-1
b = random.randint(0,5)-1
num = 5*a +b
if(num>20):
return random7()
else:
return num % 7 + 1 |
adeb41f43ffcd09d1e20e6004688c075c2d7c467 | shubhi1998/Beginner-Python-Programming- | /Course 2: Python Data Structures/Week 2/Ex-2.py | 894 | 4.25 | 4 | Write a program to prompt for a file name, and then read through the
file and look for lines of the form:
X-DSPAM-Confidence:0.8475
When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart
the line to extract the floating-point number on the line. Count these lines and
then compute the total of the spam confidence values from these lines. then compute the total of the spam confidence values from these lines.
CODE
filename = input("Enter the file name")
try:
fhand = open(filename)
except:
print("This file can't be printed")
quit()
count =0
sum =0.0
for line in fhand:
line = line.rstrip()
if line.startswith("X-DSPAM-Confidence:"):
atpos = line.find(":")
spos = line[atpos+1:]
sum = sum + float(spos)
count=count+1
avg=sum/count
print"Average of confidence values: ",avg
|
ed608d54ea2240467c60b231313280a45de13e15 | adityamhatre/DCC | /dcc #4/first_missing_positive_integer.py | 3,276 | 4.25 | 4 | import unittest
"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other
words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and
negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
"""
def first_missing_positive_integer(arr):
"""
Move every element to it's index position
Meaning if current element is 1, swap it with a[0]. Because a[1-1]=a[0]
Meaning if current element is 2, swap it with a[1]. Because a[2-1]=a[1]
Ignore elements less than 1 and greater than size of array, because that would mean array has missing elements
and those missing elements are not in that skipped elements.
For eg., [1, 2, -1, 10]
1 and 2 are in correct place
-1 is ignored
10 is ignored, because it's place is a[9]. But out array size is 4.
Then just iterate over array to check if index, value pair matches as value==index+1
If all values match, that means all elements are at correct place. Return the size of array + 1
This function returns the missing positive integer from the array
:param arr: The input array
:return: int; the missing positive integer
"""
# Edge case -->
if not arr:
return 1
# <-- Edge case
# Iterate over array to move elements to "correct" place
i = 0
while i < len(arr):
curr = arr[i]
if not curr: # Skipping None elements
i += 1
continue
if 0 >= curr or curr >= len(arr): # Skipping elements which are less than 1 and greater than len of arr
i += 1
continue
if i + 1 == curr: # Skipping elements which are already in place
i += 1
continue
if curr == arr[curr - 1]: # Duplicate element check
i += 1
continue
arr[i], arr[curr - 1] = arr[curr - 1], arr[i]
if i != 0:
i -= 1
else:
i = 0
# Iterate over array
for i, v in enumerate(arr):
if arr[i] == i + 1: # If this condition meets, element is in place. So skip
continue
else: # Else return index+1
return i + 1
# All elements in place, return next integer, i.e., len(arr) + 1
return len(arr) + 1
class Test(unittest.TestCase):
def test_normal_case_1(self):
self.assertEqual(first_missing_positive_integer([3, 4, -1, 1]), 2)
def test_normal_case_2(self):
self.assertEqual(first_missing_positive_integer([1, 2, 0]), 3)
def test_empty(self):
self.assertEqual(first_missing_positive_integer([]), 1)
def test_with_none_elements_and_duplicates(self):
self.assertEqual(first_missing_positive_integer([-1, 1, 2, None, 2, 0]), 3)
def test_with_none_elements(self):
self.assertEqual(first_missing_positive_integer([None]), 1)
self.assertEqual(first_missing_positive_integer([None, None, None, None]), 1)
def test_all_present_with_negatives(self):
self.assertEqual(first_missing_positive_integer([3, 2, 4, -1, -2, 1]), 5)
if __name__ == '__main__':
unittest.main()
|
84ab96e19c7cc9d821681a534b8988fd868c5d3b | mashpolo/leetcode_ans | /400/leetcode461/ans.py | 716 | 3.71875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@desc:
@author: Luo.lu
@date: 2018-11-5
"""
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
bin_x = bin(x)[2:]
bin_y = bin(y)[2:]
if len(bin_x) >= len(bin_y):
bin_y = [0]*(len(bin_x) - len(bin_y)) + list(bin_y)
else:
bin_x = [0]*(len(bin_y) - len(bin_x)) + list(bin_x)
res = 0
print(bin_x, bin_y)
for x in range(len(bin_x)):
if int(bin_x[x]) != int(bin_y[x]):
res += 1
return res
if __name__ == '__main__':
A = Solution()
print(A.hammingDistance(1,4))
|
91216a83c779698ad7952bae61efb4890d2a4c1b | Bertram-Liu/Note | /NOTE/02_PythonBase/day08/exercise/set_del_repeat.py | 733 | 3.96875 | 4 | # 练习:
# 1. 写程序,任意输入多个正整数,当输入小于零的数时结束输入
# 1. 打印出您输入的这些数的种类有多少种?(去重)
# 2. 去掉重复的整数,把剩余的这些数的和打印出来!
# 如:
# 输入: 1
# 输入: 2
# 输入: 2
# 输入: 3
# 输入: -1
# 种类 : 3
# 和是 : 6
L = [] # 列表容器放入用户输入的原始数据
while True:
x = int(input("请输入正整数: "))
if x < 0:
break # 退出循环
L.append(x)
# 程序走到此处,用户输入结束
s = set(L) # 用列表创建一个集合(自动去重)
print("种类数为:", len(s))
print("去重后的和是:", sum(s))
|
97f72cf10a81d856078ad13144e46820a589222a | Valleka/Ucode_Python_Marathon | /spr03/t07_calculambdor/calculator.py | 608 | 3.84375 | 4 | operations = {
'add' : lambda x, y : x + y,
'sub' : lambda x, y : x - y,
'mul' : lambda x, y : x * y,
'div' : lambda x, y : x / y,
'pow' : lambda x, y : x ** y
}
def calculator(operator, num_1, num_2):
if operator not in operations:
raise ValueError('Invalid operation. Available operations: add, sub, mul, div, pow')
if (type(num_1) != int and type(num_1) != float) or (type(num_2) != int and type(num_2) != float):
raise ValueError("Invalid numbers. Second and third arguments must be numerical")
else:
return operations.get(operator)(num_1, num_2)
|
847003c2fb0e52dec3d3728ff3dabe51d10cc53a | xggxnn/webApp | /python3/jiujiuchengfa.py | 203 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
# Filename : jiujiuchengfa.py
# author by : xggxnn.top
# 九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print('{0}X{1}={2}\t'.format(j,i,i*j),end='')
print("") |
6567fdea0696752c141af9eee62692fd1bffc4dc | Gowtham-cit/Algorithms-Python | /Code/linear_search.py | 758 | 3.84375 | 4 | """
Linear search is one of the simplest searching algorithms,
and the easiest to understand. We can think of it as a ramped-up version of o
ur own implementation of Python's in operator
"""
#return the position of the element if available
def LS(lst, find):
for i in range(len(lst)):
if lst[i] == find:
return i
return 0
lst = [int(x) for x in input().split()]
find = int(input())
ans = LS(lst, find)
if ans:
print(f"{ans} is the position of the element")
else:
print("Oops...! Not found anything")
"""
Test case 1:
input:
1 2 3 4 5 6 7 8
3
output:
2 is the position of the element
Test case 2:
input:
1 2 3 4 5 6 7 8
0
output:
Oops...! Not found anything
"""
|
6f64e64ac8407f423447f448ce2d8451ec053a40 | Team-Tomato/Learn | /Juniors - 1st Year/Subhiksha.B/employee_info2.py | 1,400 | 4.21875 | 4 | class Employee:
Member = 0
Name = ""
Age = 0
Gender = ""
Salary = 0
def get_info(self):
self.Member = int(input("Enter the number of employee detail to be entered:"))
for i in range(self.Member):
print(i +1,end =".")
self.Name = input("Enter employee name :")
self.Age = int(input("Enter employee age :"))
self.Gender = (input("Enter employee gender :"))
self.Salary = int(input("Enter employee's salary:"))
print("\n")
def show_info(self):
self.Member = int(input("Enter the number of employee detail to be viewed:"))
for i in range(self.Member):
print(i +1,end =".")
print("Name of the Employee:",self.Name)
print("Age of the Employee:",self.Age)
print("Gender of the Employee:",self.Gender)
print("Salary of the Employee:",self.Salary)
print("\n")
if __name__== '__main__':
emp = Employee()
ch =int(input("\nEnter 1.get the info of employees\nEnter 2.Show the info of employees\nEnter 3.Exit\n"))
while ch != 3:
if ch == 1:
emp.get_info()
else:
emp.show_info()
ch =int(input("\nEnter 1.get the info of employees\nEnter 2.Show the info of employees\nEnter 3.Exit\n"))
if ch == 3:
print("You entered choice 3 to Exit") |
113d507a5970e1db48dcb3c039723f0250b8280b | prernaranjan123/pythan | /table.py | 137 | 4.03125 | 4 | n=int(input("Enter number whose table is to print : "))
print("Table of number : ",n)
for i in range(1,11):
print(n,"*",i,"=",n*i) |
1f0fbfeae970acf5e549edf14d9a24b6b10f4110 | paalso/learning_with_python | /ADDENDUM. Think Python/09 Case study - word play/9-1.py | 277 | 3.921875 | 4 | '''
Exercise 9.1. Write a program that reads words.txt and prints only the words
with more than 20 characters (not counting whitespace).
'''
with open('words.txt', 'r') as f:
words_longer20 = [line.rstrip() for line in f if len(line) > 21]
print(words_longer20)
|
192b375424e1f940f314ab82889d6aa730a8a7af | praveendareddy21/ProjectEulerSolutions | /src/project_euler/problem6/__init__.py | 3,469 | 3.8125 | 4 | '''
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred
natural numbers and the square of the sum.
'''
#My forum answer:
#
#This is a trivial problem. For each part (sum of squares, and square of sums)
#there's two ways you can do either:
#
#1) naive method -- do loop from 1 up to n, adding to total
#2) smart method -- use Gauss' formula
#
#I did both, so that I could time both:
#
#[code]
#def squares_sum_loop(num):
# '''
# Returns the square of the sum of the 1st num numbers using naive loop
# @param num: the limit to sum to
# @type num: int
# @return: (1+2+...+num)^2
# @rtype: int
# '''
# total = 0
# for factor in range(1, num+1):
# total += factor
# return total**2
#
#def squares_sum_gauss(num):
# '''
# Returns the square of the sum of the 1st num numbers using Gauss' method
# for summing 1..n
# @param num: the limit to sum to
# @type num: int
# @return: (1+2+...+num)^2
# @rtype: int
# '''
# total = int(num * (num + 1) / 2)
# return total * total
#
#def sum_squares_loop(num):
# '''
# Returns the sum of squares of the 1st num numbers using naive loop.
# @param num: the limit to sum to
# @type num: int
# @return: (1^2+2^2+...+num^2)
# @rtype: int
# '''
# total = 0
# for factor in range(1, num+1):
# total += factor ** 2
# return total
#
#def sum_squares_formula(num):
# '''
# Returns the sum of squares of the 1st num numbers using smart formula:
# n*(n+1)*(2n+1)/6
# @param num: the limit to sum to
# @type num: int
# @return: (1^2+2^2+...+num^2)
# @rtype: int
# '''
# return num * (num + 1) * (2 * num + 1) / 6
#
#def prob6(lim, sum_of_squares, square_of_sums):
# '''
# Solves problem #6 -- naive approach
# '''
# return square_of_sums(lim) - sum_of_squares(lim)
#
#print prob6(100, sum_squares_formula, squares_sum_gauss)
#[/code]
#
#Note my prob6 function is parameterized by the functions for calculating the
#sum of squares and square of sums, thereby allowing me to "plug & play"
#different ways of calculating these values.
#
#Using the timeit module, I got the following results for timing (numbers are
#in secs for 10000 runs of calulating the 1..100 answer):
#
#Timing Results:
#--------------------
#Naive sumsquares, Gauss squaresum : 0.59817518707
#Naive sumsquares, naive squaresum : 0.8145099447
#Gauss sumsquares, naive squaresum : 0.281725470695
#Gauss sumsquares, Gauss squaresum : 0.0393293002323
#--------------------
#Fastest time: Gauss sumsquares, Gauss squaresum - 0.0393293002323 (95.0% faster
#than slowest)
#Slowest time: Naive sumsquares, naive squaresum - 0.8145099447
#
#So that Gauss guy was pretty smart eh? :)
#
#If all you want is the answer, and want it fast, you could do it as a 1-liner:
#
#[code]
#int(num * (num + 1) / 2)**2 - num * (num + 1) * (2 * num + 1) / 6
#[/code]
#
#PS -- all my solutions to ProjectEuler problems can be found on GitHub at
#https://github.com/pzelnip/ProjectEulerSolutions |
84a7a218d63595d45065b74480eeb28352ec61b4 | poojagmahajan/python_exercises | /full_speed_educative/List/average_list.py | 268 | 3.953125 | 4 |
# Average of given list
def getAverage():
l1 = [1, 4, 9, 10, 23]
avg = sum(l1) / len(l1)
return avg
avg = getAverage()
print(avg)
########## OR
l = [1,4,9,10,23]
list_sum = sum(l)
list_length = len(l)
average = list_sum/list_length
print(average)
|
2665eaabe98d2654c7bd2222f35eec2bfab04d62 | wrzzd/AlgorithmCode | /LeetCode/94.py | 827 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# if not root: return []
# return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
res = []
current = root
if not root: return res
while root:
if not root.left:
res.append(root.val)
root = root.right
else:
left = root.left
while left.right:
left = left.right
left.right = root
left.right.left = None
root = root.left
return res
|
d9e6142a29f8024d9e90061aa3adbe9348fe809d | DayGitH/Python-Challenges | /DailyProgrammer/DP20120927C.py | 1,072 | 3.640625 | 4 | """
[9/27/2012] Challenge #101 [difficult] (Boolean Minimization)
https://www.reddit.com/r/dailyprogrammer/comments/10lbjo/9272012_challenge_101_difficult_boolean/
For difficult 101, I thought I'd do something with binary in it.
Write a program that reads in a file containing 2^n 0s and 1s as ascii characters. You will have to solve for N given
the number of 0s and 1s in the file,
as it will not be given in the file. These 0s and 1s are to be interpreted as the outputs of a truth table in N
variables.
Given this truth table, output a minimal boolean expression of the function in some form. (
[Hint1](http://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm),
[hint2](http://en.wikipedia.org/wiki/Karnaugh_map))
For example, one implementation could read in this input file
0000010111111110
This is a 4-variable boolean function with the given truth table. The program could minimize the formula, and could
output
f(abcd)=ac'+ab'+bcd'
or
f(0123)=02'+01'+123'
"""
def main():
pass
if __name__ == "__main__":
main()
|
0b02745df7f650b7860c9420c6d5ce92fa624522 | MaximSungmo/practice01 | /prob09.py | 382 | 3.625 | 4 | # 주어진 if 문을 dict를 사용해서 수정하세요.
menu = input('메뉴: ')
# if menu == '오뎅':
# price = 300
# elif menu == '순대':
# price = 400
# elif menu == '만두':
# price = 500
# else:
# price = 0
#
# print('가격: {0}'.format(price))
menu_list = {'오뎅' : 300, '순대' : 400, '만두' : 500}
print('가격 :', menu_list.get(menu) or 0) |
62409ab4a825e5181bf951c676799a2885470658 | vishalisairam/TrustSimulation | /11Nov_ProjectPractive | 1,714 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 10:51:33 2020
@author: vishali
"""
import axelrod as axe
import random
class Player:
def __init__(self,name = False):
pass
class HumanPlayer:
def __init__ (self, otherStrategy, name = False):
self.otherStrategy = axe.Human()
self.name = name
class Compstrategy(Player):
def __init__ (self, strategies):
self.strategies = strategies
def strategies (self):
class player1(Compstrategy):
self.player1 = axe.TitForTat()
class player2(Compstrategy):
self.player2 = axe.Defector()
class player3(Compstrategy):
self.player3 = axe.Cooperator()
class player4(Compstrategy):
self.player4 = axe.GrudgerAlternator()
class player5(Compstrategy):
self.player5 = axe.Grudger()
A = player1()
B = player2()
C = player3()
D = player4()
E = player5()
human = HumanPlayer()
playerlist = [A, B, C, D, E]
compstrategylist = random.choice(playerlist)
print(compstrategylist)
class Match():
""" Repeated game between computer and human """
def _init_(self, Compstrategy, HumanPlayer, match):
self.Compstrategy = Compstrategy
self.HumanPlayer = HumanPlayer
self.match = axe.Match()
def match():
players = [compstrategylist, human]
match = axe.Match(players = [A,B], turns =5)
match.play()
|
3c5dfd814bd3fa93a9f8f71e1104fb6b68663df0 | kuzja111/IML | /ex3/models.py | 5,177 | 3.78125 | 4 | import numpy as np
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from abc import ABC, abstractmethod
class Classifier(ABC):
"""
abstract Classifier class that all classes inherit from
"""
def __init__(self):
self.model = None
@abstractmethod
def fit(self, X, y):
"""
this method learns the parameters of the model and stores the trained model (namely, the variables that
define hypothesis chosen) in self.model. The method returns nothing.
:param X: training set as X(m over d)
:param y: (d rows of +-1)
"""
pass
@abstractmethod
def predict(self, X):
"""
predicts the label of each sample.
:param X: unlabled test set with m' rows and d columns
:return: vector of predicted labels y with m' rows of +1 or -1
"""
pass
def score(self, X, y):
"""
:param X: unlabled test set with m' rows and d columns
:param y: true labels - vector of predicted labels y with m' rows of +1 or -1
:return: dictionary with relevant scores
"""
self.fit(X, y)
y_hat = self.predict(X)
m = len(y_hat)
positive = sum([1 for item in y if item == 1])
negative = sum([1 for item in y if item == -1])
false_positive = sum([1 for i in range(m) if y_hat[i] == 1 and y[i] == -1])
false_negative = sum([1 for i in range(m) if y_hat[i] == -1 and y[i] == 1])
true_positive = sum([1 for i in range(m) if y_hat[i] == 1 and y[i] == 1])
true_negative = sum([1 for i in range(m) if y_hat[i] == -1 and y[i] == -1])
return {
'num_samples': X.shape[0],
'error': (false_positive + false_negative) / (positive + negative),
'accuracy': (true_positive + true_negative) / (positive + negative),
'FPR': false_positive / negative,
'TPR': true_positive / positive,
'precision': true_positive / (true_positive + false_positive),
'specificity': true_negative / negative
}
class Perceptron(Classifier):
def __init__(self):
super().__init__()
self._w = None # module weights initialization
def fit(self, X, y):
new_X = np.insert(X, 0, 1, axis=1) # add column of ones to the beginning of X (for the non-homogenous case)
m, d = new_X.shape[0], new_X.shape[1]
self._w = np.zeros(d)
changed_w = True # if we didnt enter the inner if for all i in m, we can return
while changed_w:
changed_w = False
for i in range(m):
if y[i] * np.dot(self._w, new_X[i]) <= 0:
changed_w = True
self._w += (y[i] * new_X[i])
def predict(self, X):
return np.sign(np.insert(X, 0, 1, axis=1) @ self._w)
def score(self, X, y):
return super().score(X, y)
class LDA(Classifier):
def __init__(self):
# two lists (one for +1 and the other for -1) of delta function for every row in X
super().__init__()
self.d_pos = None # delta plus function
self.d_neg = None # delta neg function
def fit(self, X, y):
X_pos = X[y == 1]
X_neg = X[y == -1]
mu_pos = np.array([np.mean(row) for row in X_pos.T])
mu_neg = np.array([np.mean(row) for row in X_neg.T])
sigma_inv = np.linalg.pinv(np.cov(X.T))
prob_pos = sum([1 for i in y if i == 1]) / len(y)
prob_neg = sum([1 for i in y if i == -1]) / len(y)
self.d_pos = lambda x: x.T @ sigma_inv @ mu_pos - 0.5 * mu_pos.T @ sigma_inv @ mu_pos + np.log(prob_pos)
self.d_neg = lambda x: x.T @ sigma_inv @ mu_neg - 0.5 * mu_neg.T @ sigma_inv @ mu_neg + np.log(prob_neg)
def predict(self, X):
m = X.shape[0]
d_pos_arr = [self.d_pos(x) for x in X]
d_neg_arr = [self.d_neg(x) for x in X]
argmax_index = [np.argmax([d_pos_arr[i], d_neg_arr[i]]) for i in range(m)]
return [1 if argmax_index[i] == 0 else -1 for i in range(m)]
def score(self, X, y):
return super().score(X, y)
class SVM(Classifier):
def __init__(self):
super().__init__()
self.model = SVC(C=1e10, kernel='linear')
def fit(self, X, y):
self.model.fit(X, y)
def predict(self, X):
return self.model.predict(X)
def score(self, X, y):
return self.model.score(X, y)
class Logistic(Classifier):
def __init__(self):
super().__init__()
self.model = LogisticRegression(solver='liblinear')
def fit(self, X, y):
self.model.fit(X, y)
def predict(self, X):
return self.model.predict(X)
def score(self, X, y):
return self.model.score(X, y)
class DecisionTree(Classifier):
def __init__(self):
super().__init__()
self.model = DecisionTreeClassifier(max_depth=5)
def fit(self, X, y):
self.model.fit(X, y)
def predict(self, X):
return self.model.predict(X)
def score(self, X, y):
return self.model.score(X, y)
|
a0c6915a3e0a9a8dcb2d65b1eaf0c1763d7cbeb9 | nguyeti4/cs362_hwk4 | /test_fullname.py | 788 | 3.75 | 4 | import unittest
import fullname
class Fullname(unittest.TestCase):
def test_full(self):
actual = fullname.gen_fullname("Timothy","Nguyen")
expected = "Timothy Nguyen"
self.assertEqual(actual,expected)
def test_full_exception(self):
with self.assertRaises(ValueError) as exception_context:
fullname.gen_fullname("","Nguyen")
self.assertEqual(
str(exception_context.exception),"You are missing a first name"
)
def test_full_exception2(self):
with self.assertRaises(ValueError) as exception_context:
fullname.gen_fullname("Timothy","Ngu123")
self.assertEqual(
str(exception_context.exception),"All characters in last name must be a letter"
)
|
798b5a5e0227ba766e323eb9f91eb09821d5a34c | chousemath/pygame_projects | /breakout/homework_problem_1.py | 562 | 4 | 4 | def sum_missing_numbers(nums):
minimum = min(nums)
maximum = max(nums)
total = 0
for num in range(minimum, maximum):
if num not in nums:
total += num
return total
ans1 = sum_missing_numbers([4, 3, 8, 1, 2])
assert ans1 == 18, f'expected 18, got {ans1}'
# 5 + 6 + 7 = 18
ans2 = sum_missing_numbers([17, 16, 15, 10, 11, 12])
assert ans2 == 27, f'expected 27, got {ans2}'
# 13 + 14 = 27
ans3 = sum_missing_numbers([1, 2, 3, 4, 5])
assert ans3 == 0, f'expected 0, got {ans3}'
# No Missing Numbers
print('Everything okay')
|
deb7710637b2d7d43c35fcf60e71481e059ef6a0 | jtlai0921/Python- | /ex04/for_2.py | 55 | 3.5625 | 4 | sum = 0
for x in range(-3, 3):
sum += x
print(sum)
|
72fd26de55a4748d45652a31191f09bece86ef5a | WayneChen1994/Python1805 | /day02/zuoye.py | 1,090 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Wayne.Chen
# year = int(input("请输入一个年份:"))
# if year%100 != 0 and year%4 == 0 or year%400 ==0:
# print("%d为闰年"%year)
# else:
# print("%d不是闰年"%year)
# num = int(input("请输入一个三位数:"))
# bai = num // 100
# ge = num % 10
# shi = num // 10 % 10
# if num == ge**3+shi**3+bai**3:
# print("%d为水仙花数"%num)
# else:
# print("%d不为水仙花数"%num)
# num = int(input("请输入一个五位数:"))
# wan = num //10000
# ge = num % 10
# shi = num //10 % 10
# qian = num // 1000 % 10
# if wan == ge and qian == shi:
# print("%d为回文数"%num)
# else:
# print("%d不为回文数"%num)
# import random
# print("开始游戏".center(50, "*"))
# ya = input("买定离手,押大还是押小?【大/小】")
# jiang = random.randrange(1, 7)
# print("开奖号码", jiang)
# if ya == "大" and jiang > 3 or ya == "小" and jiang < 4:
# print("庄家喝酒。。。")
# else:
# print("先干为敬。。。")
|
fd4c6c02fc7059661fcfe861f1c156e4487f11d5 | Bidesh15-8550/Python-Machine-Learning-and-Django-Projects | /Python basics/logical operators.py | 306 | 4 | 4 | has_high_income = True
has_good_credit = True
if has_high_income or has_good_credit: #and, or,NOT are logical operators
print("Eligible for loan")
has_criminal_record = False
if has_good_credit and not has_criminal_record:
print("Eligible for loan")
else:
print("Not eligible") |
d1b6e1a8d572a5d15b6b3274b1c3de7cbee721c4 | zsakhalin/learning_py | /tutorials/book-self-taught-programmer/chapt6/6-10.py | 324 | 3.609375 | 4 | str66 = "oiuytyuil \" okonbghjlo".replace("o", "O")
print(str66)
print(str66.index("j")) # index of "j"
str69 = "t"
print(str69 + str69 + str69)
print(3*str69)
str610 = "И незачем так орать! Я и в первый раз прекрасно слышал."
ind = str610.index("!")
print(str610[:(ind + 1)]) |
0629673f5d2d7efd55941343d50096c716db6449 | shapigou123/Programming | /python_advance_skill/7_1__yy.py | 1,695 | 3.578125 | 4 | #coding=utf-8
#继承内置的tuple
class IntTuple(tuple):
#修改实例化行为,就要修改__new__方法,是一个静态方法
#当我们创建一个实例的时候,__new__要先于__init__方法
#第一个参数是一个类对象,其他参数和__init__一样
def __new__(cls, iterable):
#使用一个生成器对象,下面就是生成器表达式
g = (x for x in iterable if isinstance(x,int)
and x>0)
#在其内部调用父类的__new__方法,来创建真正的tuple
#cls是当前类的一个子类
return super(IntTuple,cls).__new__(cls,g)
#考虑改变传入的iterable参数手工指定[1,4],但任然不行!
#在self在传入到__init__后,内置的元组就已经创建好了。所以
#在之后的任何位置都不能改变。考虑是谁创建了self这个实例__new__
def __init__(self, iterable):
#super(IntTuple,self).__init__([1, 6, 3])
#print self
#调用父类的__init__方法
super(IntTuple,self).__init__(iterable)
#after
#在这里不能修改self了,self是内置类型tuple的实例
#而tuple是不可变对象,即不能从self中删除元素
t = IntTuple([1, -1, 'abc', 6, ['x', 2], 3])
print t
class Player(object):
def __init__(self, uid, name, stat=0, level=1):
self.uid = uid
self.name = name
self.stat = stat
self.level = level
#Player2的实例要比Player的实例使用的内存要小!
class Player2(object):
__slots__ = ['uid', 'name', 'stat', 'level']
def __init__(self, uid, name, stat=0, level=1):
self.uid = uid
self.name = name
self.stat = stat
self.level = level
with open('demo.txt', 'w') as f:
f.write('abcdef')
f.writelines(['xyz\n', '123\n'])
#f.close() |
d3b90c124f87051c8bdd21e83dca649c3d58dda0 | angelaliu2015/mycode | /lab05.py | 814 | 4 | 4 | #!/usr/bin/env python3
dic = {"Flash":{"Speed": "Fastest", "Intelligence": "Lowest", "Strength": "Lowest"}, "Batman":{"Speed": "Slowest", "Intelligence": "Highest", "Strength": "Money"}, "Superman":{"Speed": "Fast", "Intelligence": "Average", "Strength": "Strongest"}}
char_name = input("which character do you want to know about?(Flash, Batman, Superman) :")
char_stat = input("What statistic do you want to know about? (strength, speed, or intelligence) :")
subdic = dic.get(char_name)
#print("The character you want to know: ")
#print(dic.get(char_name," the name does not present"))
#print(subdic.get(char_stat,"the statistic do you want to know about does not present"))
print(char_name,"'s",char_stat,' is: ',subdic.get(char_stat))
print(f"{char_name}'s {char_stat} is: {dic.get(char_name).get(char_stat)}")
|
dc5b3d13cab6de1badf832c8ddeb7bfc30f8205d | brtcrt/Short-Python-Todo-List | /main.py | 4,775 | 3.8125 | 4 | import tkinter as tk # Import the modules for interfaces.
from tkinter import messagebox # Fucking pop-up windows. It works brilliantly though. Also super easy to use.
import json # Standard json library. Using this for data storage. Unstable but works.
from tkinter import ttk # For quick access to parts like the Button.
from tkcalendar import Calendar # Used for the date picking.
from datetime import date # Used for setting starting date.
with open('tasks.json') as json_file:
try:
tasks_loaded = json.load(json_file) # Getting the saved info from the json file.
except KeyError:
print("Some random key error from start up or the json file was changed.") # Problems with using .json as a db.
task = {
"tasks": [
]
} # Using a dictionary to store data whilst the program is running. This also makes converting to json easy.
try:
tasks_list = tasks_loaded["tasks"]
print(tasks_list)
task["tasks"] = tasks_list # Current data is set to saved data on start up. Basically how the save-load system works.
except KeyError:
print("Some random key error from start up or the json file was changed.") # Problems with using .json as a db.
addedTask = "" # To put all the info received in to order.
def PickDate(): # To pick a date for the task.
def print_sel():
global addedTask
global tasks_list
global task
if addedTask == "": # Solves a problem where the program would die if the user enters an empty string. Idk who'd do that, but yeah. Just in case.
messagebox.showinfo("Something bad happened :(", "Please enter your task first!") # Also to keep everything in order. (Task first, date second)
else:
print(task)
this_date = cal.selection_get()
task["tasks"].append(str(addedTask) + " --- Task Date: " + str(this_date)) # Combines the task & date into a single string so it is easier to display.
messagebox.showinfo("Success!", "Set the date for the task! Don't forget to submit the task to your list!") # Just to give some feedback to the user.
top = tk.Toplevel(root)
cal = Calendar(top,font="Arial 14", selectmode='day',cursor="hand1", year=date.today().year, month=date.today().month, day=date.today().day) # The date-picker system.
cal.pack(fill="both", expand=True) # Packing it.
ttk.Button(top, text="Choose", command=print_sel).pack() # The pick date button.
def SaveToJson(): # Saving to the local json database.
global task
if addedTask == "":
messagebox.showinfo("Something bad happened :(", "Please enter your task first!") # So the user can't add an empty string to the list.
else:
with open('tasks.json', 'w') as tasks_dumped:
json.dump(task, tasks_dumped, indent=3, sort_keys=True) # This somehow fucking works.
messagebox.showinfo("Success!", "Saved to your list.") # Again, giving feedback to the user so they understand they can close the window safely.
def AddTask(): # Get the tasks name from the user.
global task
global addedTask
global entry
addedTask = (str(entry.get())) # This should have been the first function that I wrote but it wasn't so it's gonna stay here.
messagebox.showinfo("Success!", "Added the task! Don't forget to set the date for it!")
def ShowList(): # Showing the list.
i, last_list = 0, "" # I hate defining variables like this but it was necessary. Not for any functionality of course.
global task
for task in task["tasks"]: # Putting all the tasks in the list/dictionary in to a neat little string.
i += 1
last_list = last_list + "{}) Task name: ".format(str(i)) + task + "\n"
messagebox.showinfo("Your todo list", last_list) # Using pop-up windows literally everywhere because they are so easy to use and they just work.
root = tk.Tk() # The core of the tkinter interface system.
s = ttk.Style(root) # Some styling.
s.theme_use('clam') # Some more styling.
entry = ttk.Entry(root) # Getting the input from the user. This is the thing which adds the little input box.
entry.pack(padx=10, pady=10) # Packing it separately because it wouldn't stop giving errors.
ttk.Button(root, text="Set task", command=AddTask).pack(padx=10, pady=10) # Button for setting task.
ttk.Button(root, text='Choose date', command=PickDate).pack(padx=10, pady=10) # Button for choosing a date.
ttk.Button(root, text='Submit', command=SaveToJson).pack(padx=10, pady=10) # Button for submitting/saving to json.
ttk.Button(root, text='Show list', command=ShowList).pack(padx=10, pady=10) # Button for showing the list.
root.mainloop() # Finally initialize the program. And yes I spent about 10 minutes trying to get it to be exactly 69 lines :) |
5a0a7df22cc693f1378f5dcd56bd001456865165 | mogolola/Coding4Interviews | /剑指offer/032-把数组排成最小的数/myCode.py | 622 | 3.59375 | 4 | class Solution:
def isLess(self, n1, n2):
return int(str(n1)+str(n2)) < int(str(n2)+str(n1))
def merge(self, n1,n2):
j = 0;
for i in range(len(n1)):
while j<len(n2) and self.isLess(n2[j],n1[i]):
j+=1
n2.insert(j, n1[i])
j+=1
return n2;
def sort(self, numbers):
l = len(numbers)
if len(numbers)>=2:
mid = int(l / 2)
return self.merge(self.sort(numbers[:mid]), self.sort(numbers[mid:]))
else:
return numbers;
def PrintMinNumber(self, numbers):
return ''.join(list(map(lambda i:str(i) ,self.sort(numbers))))
solution = Solution()
print(solution.PrintMinNumber([3,32,321]))
|
473dc60e757a98e84920bf7fd5afe033c706eedb | diwash007/Python-projects | /quiz-game/quiz_brain.py | 782 | 3.765625 | 4 | class Brain:
def __init__(self, ques_list):
self.ques_num = 0
self.ques_list = ques_list
self.score = 0
def check_answer(self,uans, ans):
if uans.lower() == ans.lower():
print("You got it right!!")
self.score += 1
else:
print("Incorrect answer!!")
print(f"The answer was: {ans}")
print(f"Your score: {self.score}/{self.ques_num}\n")
def next_ques(self):
curr_question = self.ques_list[self.ques_num]
self.ques_num +=1
Uans = input(f"Q.{self.ques_num}. {curr_question.ques}\n(True or False?) : ")
self.check_answer(Uans, curr_question.ans)
def still_have_ques(self):
return self.ques_num < len(self.ques_list)
|
d347b7d6a8e1a12d32c095ae7399e1dd296310a1 | gazerhuang/PythonLearning | /08_OOP/gz_10_run+.py | 450 | 3.609375 | 4 | class Person:
def __init__(self, new_name, new_weight):
self.name = new_name
self.weight = new_weight
def __str__(self):
return "%s 体重 %.2f kg" % (self.name, self.weight)
def run(self):
self.weight -= 0.5
def eat(self):
self.weight += 1
ming = Person("Ming", 75)
ming.run()
ming.run()
ming.run()
ming.eat()
print(ming)
mei = Person("mei", 45)
mei.run()
mei.eat()
mei.eat()
print(mei)
|
5f2c0fe09c988068204ee1a81e2ce0fea8b2d111 | GroupD5Cov/D5VirtualRobotProject | /NewStartUpScreen/D5Asis.py | 20,679 | 3.625 | 4 | #importing in functions that we need for the program to work
import pygame as pg
import random
from textbox import TextBox
pg.init()
#setting up colour RGB values
white = (255,255,255)
red = (255,0,0)
blue = (0,0,255)
green = (0,255,0)
black = (0,0,0)
pink = (255,20,147)
bright_red = (200,0,0)
bright_green = (0,200,0)
bg = pg.image.load('startscreen.png')
clock = pg.time.Clock()
font = pg.font.Font(None, 25)
frame_count = 0
frame_rate = 60
start_time = 180
menuDisplay = pg.display.set_mode((1200,600))
gameDisplay = pg.display.set_mode((1200, 600))
display_width = 800
display_height = 600
gameExit = False
KEY_REPEAT_SETTING = (200,70)#textbox to appear in the same position after action
"""setting instruction colour and font"""
def instruction(i,Space,List):
intrs = List
font = pg.font.SysFont("Times", 25)
message = intrs[i]
rend = font.render(message, True, pg.Color("red"))
return (rend, rend.get_rect(topleft=(900,35+Space)))
"""setting font and colour of the name displayed at the start"""
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
"""quit game button function"""
def quit_game():
pg.quit()
quit()
"""start game button function"""
def start_game():
app = MainProgram()
app.main_loop()
#Right hand side title screen colour
def game_intro():
x=0
y=0
i = 0
intro = True
gameDisplay.fill(black)
while intro:
for event in pg.event.get():
if event.type == pg.QUIT: #quit function added
pg.quit()
quit()
#Now creating the start-up screen
gameDisplay.blit(bg,(x,y)) #displaying in starmenu bg being pygame, x and y being the position
largeText = pg.font.Font('freesansbold.ttf',80)#font and font size
TextSurf, TextRect = text_objects("Bargain Inspector", largeText)#Program name
TextRect.center = ((display_width/2),(display_height/2)) #text allignment
gameDisplay.blit(TextSurf, TextRect)
button("Start",80,450,120,85,white,bright_green,start_game) #Button which starts the program, position,size, colour and linked to the start game function
button("Quit Game",605,450,160,85,white,bright_red,quit_game) # Button which closes the program, position,size, colour and linked to the quit game function
intrs = ["INSTRUCTIONS:","Enter colour for car type", "Enter co-ordinates", "Enter value of car models", "Enter time for robot",]#Instruction displayed on the screen
space = int(150) #position of the instruction on the screen
while i != 5: #5 total strings
prompt = instruction(i,space,intrs)#i=number of instructions, space = position, intrs = intructions
gameDisplay.blit(*prompt)
space = space + 40 #how close to each other the instructions
pg.display.update() #for clock speed functuon
i = i+1
pg.display.update()
#limit the clock speed to 15 FPS (to prevent overflow)
clock.tick(15)
#buttons function defined, event driven action (for the Start game and Quit button)
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pg.mouse.get_pos()
click = pg.mouse.get_pressed()
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y: #when mouse button clicked outcome (1,0,0)
pg.draw.rect(gameDisplay, ac,(x,y,w,h))
if click[0] == 1 and action != None: #if mouse position (0,0,0 = no action, otherwise event driven action)
action()
else:
pg.draw.rect(gameDisplay, ic,(x,y,w,h))
smallText = pg.font.SysFont("Times",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
#Initialising the main program with class attribute
class MainProgram(object):
def __init__(self):
"""The initialisation function of key components of the main program"""
pg.init()
pg.display.set_caption("D5's Bargain Inspector")
bg = pg.image.load('mainScreen.png')
gameDisplay.blit(bg,(0,0))
self.red = []
self.blue = []
self.green = []
self.pink = []
self.colourA =[]
self.colour = ""
self.num_items = 0
self.finishedList =[]
self.time = 0
self.frame_count = 0
self.frame_rate = 60
self.start_time = 180
self.screen = menuDisplay
self.clock = pg.time.Clock()
self.robot_loc = []
self.fps = 60.0
self.done = False
self.input = TextBox((900,200,200,40),command=self.get_input, #setting the size and position of the text box
clear_on_enter=True,inactive_on_enter=False)
self.user_input = ""
self.color = white
self.prompt = self.make_prompt('Enter Red:BMW, Blue:Vauxhall, Green:Land Rover, Pink:Lexus')
pg.key.set_repeat(*KEY_REPEAT_SETTING) #textbox to appear in the same position after action
def make_prompt(self,Message):
""" Function to create the labels, called everytime a new input is entered """
pg.draw.rect(menuDisplay , white,(820,165,400,30)) #1 is left right position, 2 is up down, 3 is width, 4 is height
font = pg.font.SysFont("Times", 14)
message = Message
rend = font.render(message, True, pg.Color("black"))
return (rend, rend.get_rect(topleft=(820,165)))#position of the text in the screen
def event_loop(self):
""" A continuous FOR loop which allows an exit for our main program"""
for event in pg.event.get():
if event.type == pg.QUIT:
self.done = True
self.input.get_event(event)
def random_types(self):
"""Randomly generates colours into the screen and randomly gives them a price and a name eg. red-bmw,price """
names = ["BMW", "Vauxhall", "Land Rover", "Lexus"]
for i in range(50):
item = random.randint(1,3)
radx = random.randint(0,790)
rady = random.randint(0,590)
radp = random.randint(1,20)
radnum = random.randint(1,4) - 1
radn = names[radnum]
coords = [radx,rady,radp,radn]
if item == 1:
pg.draw.rect(menuDisplay , red,(radx,rady,10,10))
self.red.append(coords)
elif item == 2:
pg.draw.rect(menuDisplay , blue,(radx,rady,10,10))
self.blue.append(coords)
elif item == 3:
pg.draw.rect(menuDisplay, green,(radx,rady,10,10))
self.green.append(coords)
elif item == 4:
pg.draw.rect(menuDisplay, pink,(radx,rady,10,10))
self.pink.append(coords)
i = i +1
def get_input(self,id,input):
""" allows the user to search for cars by enterin a specific colour """
try:
input = input.lower()
self.user_input = input
self.colour = input
if self.user_input == "red" or self.user_input == "blue" or self.user_input == "green" or self.user_input == "pink":
self.prompt = self.make_prompt('Where do you want to start : e.g. NW')
self.input = TextBox((900,200,200,40),command=self.robot_start, # textbox position
clear_on_enter=True,inactive_on_enter=False)
if input == "red":
for coord in self.red:
x = coord[0]
y = coord[1]
pg.draw.rect(menuDisplay, red,(x,y,15,15))
self.colourA = self.red
elif input == "blue":
for coord in self.blue:
x = coord[0]
y = coord[1]
pg.draw.rect(menuDisplay, blue,(x,y,15,15))
self.colourA = self.blue
elif input == "green":
for coord in self.green:
x = coord[0]
y = coord[1]
pg.draw.rect(menuDisplay, green,(x,y,15,15))
self.colourA = self.green
elif input == "pink":
for coord in self.pink:
x = coord[0]
y = coord[1]
pg.draw.rect(menuDisplay, pink,(x,y,15,15))
self.colourA = self.pink
else:
self.prompt = self.make_prompt('Please enter the colour type given')
self.screen = menuDisplay
except ValueError:
print("ERROR")
def robot_start(self,id,input):
""" Allows the user to choose the starting position of the robot"""
input = input.upper()
self.robot_loc = input
if input == "N":
pg.draw.rect(menuDisplay, red,(400,0,20,30))
self.robot_loc = [400,0]
elif input == "E":
pg.draw.rect(menuDisplay, blue,(750,300,20,30))
self.robot_loc = [750,300]
elif input == "S":
pg.draw.rect(menuDisplay, pink,(400,550,20,30))
self.robot_loc = [400,550]
elif input == "W":
pg.draw.rect(menuDisplay, green,(10,300,20,30))
self.robot_loc = [10,300]
elif input == "NW":
pg.draw.rect(menuDisplay, bright_green,(10,10,20,30))
self.robot_loc = [10,10]
elif input == "NE":
pg.draw.rect(menuDisplay, bright_red,(750,10,20,30))
self.robot_loc = [750,10]
elif input == "SW":
pg.draw.rect(menuDisplay, red,(10,550,20,30))
self.robot_loc = [10,550]
elif input == "SE":
pg.draw.rect(menuDisplay, pink,(750,550,20,30))
self.robot_loc = [750,550]
else:
self.prompt = self.make_prompt('Please enter a valid co-cordinate for the robot to search')
if input == "N" or input == "E" or input == "S" or input == "W" or input == "NW" or input == "NE" or input == "SW" or input == "SE":
self.prompt = self.make_prompt('Please enter the number of car types you will like to find?')
self.input = TextBox((900,200,200,40),command=self.number_of_items, #textbox position
clear_on_enter=True,inactive_on_enter=False)
def number_of_items(self,id,input):
""" This will allow the user to enter the number of chosen car models they want to find"""
if input.isdigit() and (int(input) <= len(self.colourA)):
self.num_items = int(input)
self.prompt = self.make_prompt('Enter the minutes you want the robot to search for?')
self.input = TextBox((900,200,200,40),command=self.input_time, #textbox pisition
clear_on_enter=True,inactive_on_enter=False)
else:
self.prompt = self.make_prompt('Please enter how many chosen car models to find?')
def input_time(self,id,input):
""" Allows the user to enter the time for the robot to search for car types"""
if input.isdigit() and int(input) <= 15:
self.time = input
self.start_time = int(self.time) * 60
else:
self.prompt = self.make_prompt('Please enter a valid time, e.g 1 for 1 minute')
def collide(self,c1, p1, p2, p3,xORy):
""" Tests to see if the next pixals are not white"""
locations = [p1,p2,p3]
self.Collide = False
i = 0
if xORy == "X":
while i != 3:
colour = menuDisplay.get_at((c1,locations[i])) # gets the colour of the pixal at the coordinates
if (c1 >= self.nextX and c1 <= (self.nextX + 15)) and (p1 >= self.nextY and p1 <= (self.nextY + 15)):
i=i+1
continue
elif (colour[0] != 255 or colour[1] != 255 or colour[2] != 255):
self.Collide = True
break
else:
i=i+1
continue
elif xORy == "Y":
while i != 3:
colour = menuDisplay.get_at((locations[i],c1))
if (c1 >= self.nextY and c1 <= (self.nextY + 15)) and (p1 >= self.nextX and p1 <= (self.nextX + 1)):
i=i+1
continue
elif (colour[0] != 255 or colour[1] != 255 or colour[2] != 255):
self.Collide = True
break
else:
i=i+1
continue
def bubbleSort(self,colourL):
""" Used to sort the list in order of price, cheapest first"""
for passnum in range(len(colourL)-1,0,-1):
for i in range(passnum):
if colourL[i][2]>colourL[i+1][2]:
temp = colourL[i]
colourL[i] = colourL[i+1]
colourL[i+1] = temp
def binarySearch(self, alist, item):
"""Used to search a list for the search item and returns all infomation about that item"""
first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if alist[midpoint][0] == item:
return(alist[midpoint])
else:
if item < alist[midpoint][0]:
last = midpoint-1
else:
first = midpoint+1
return found
def quick_sort(self,items):
""" Used to sort a list in order by x coords for binary search"""
if len(items) > 1:
pivot_index = len(items) // 2
smaller_items = []
larger_items = []
for i, val in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
larger_items.append(val)
self.quick_sort(smaller_items)
self.quick_sort(larger_items)
items[:] = smaller_items + [items[pivot_index]] + larger_items
def robot_move(self):
"""Makes the robot move visually and makes a countdown timer that countdowns from the users input"""
i = 0
if self.colour == "red":
self.bubbleSort(self.red)
locations = self.red
elif self.colour == "blue":
self.bubbleSort(self.blue)
locations = self.blue
elif self.colour == "green":
self.bubbleSort(self.green)
locations = self.green
elif self.colour == "pink":
self.bubbleSort(self.pink)
locations = self.pink
#pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30))
print(locations)
while i != self.num_items : #Makes the robot move visually
self.event_loop()
nextX = locations[i][0]
nextY = locations[i][1]
if self.robot_loc[0] == nextX and self.robot_loc[1] == nextY:
pg.draw.rect(menuDisplay, black,(nextX,nextY ,15,15))
self.finishedList.append(locations[i][0])
i = i + 1
elif self.robot_loc[0] < nextX:
pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30))
self.robot_loc[0] = self.robot_loc[0] + 1
pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30))
self.input.draw(self.screen)
elif self.robot_loc[1] < nextY:
pg.draw.rect(menuDisplay,white,(self.robot_loc[0],self.robot_loc[1],20,30))
self.robot_loc[1] = self.robot_loc[1] + 1
pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30))
self.input.draw(self.screen)
elif self.robot_loc[0] > nextX:
pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30))
self.robot_loc[0] = self.robot_loc[0] - 1
pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30))
self.input.draw(self.screen)
elif self.robot_loc[1] > nextY:
pg.draw.rect(menuDisplay, white,(self.robot_loc[0],self.robot_loc[1],20,30))
self.robot_loc[1] = self.robot_loc[1] - 1
pg.draw.rect(menuDisplay, pink,(self.robot_loc[0],self.robot_loc[1],20,30))
self.input.draw(self.screen)
self.event_loop()
# Starts the timer countdown
pg.draw.rect(menuDisplay, green,(810,540,400, 60))
total_seconds = self.frame_count // self.frame_rate
total_seconds = self.start_time - (self.frame_count // self.frame_rate)
if total_seconds < 0:
total_seconds = 0
minutes = total_seconds // 60
seconds = total_seconds % 60
output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds)
text = font.render(output_string, True, black)
menuDisplay.blit(text, [810, 540])
if output_string == "Time left: 00:00":
self.done = True
self.frame_count += 1
clock.tick(frame_rate)
pg.display.flip()
self.input.draw(self.screen)
self.screen.blit(*self.prompt)
pg.display.update()
if self.colour == "red":
self.quick_sort(self.red)
elif self.colour == "blue":
self.quick_sort(self.blue)
elif self.colour == "green":
self.quick_sort(self.green)
elif self.colour == "pink":
self.quick_sort(self.pink)
self.clock.tick(self.fps)
if self.time != 0:
self.done = True
def output_lists(self,i,Space):
"""Displays the list of cheapest items picked up"""
if self.colour == "red":
output = self.binarySearch(self.red, self.finishedList[i])
elif self.colour == "blue":
output = self.binarySearch(self.blue, self.finishedList[i])
elif self.colour == "green":
output = self.binarySearch(self.green, self.finishedList[i])
elif self.colour == "pink":
output = self.binarySearch(self.pink, self.finishedList[i])
font = pg.font.SysFont("Times", 20)
message = str(output[3]) + " | " + str(output[2])
rend = font.render(message, True, pg.Color("black"))
return (rend, rend.get_rect(topleft=(820,35+Space)))
def main_loop(self):
""" Makes the program loops and call certain function only if an event has been met"""
i = 0
"""adds sound to the code"""
pg.mixer.music.load('programsound.wav')
pg.mixer.music.play(-1)
space = 0
self.random_types()
while not self.done:
self.event_loop()
self.input.update()
self.input.draw(self.screen)
self.screen.blit(*self.prompt)
pg.display.update()
self.clock.tick(self.fps)
if self.time != 0:
self.done = True
self.done = False
if self.time != 0:
self.robot_move()
pg.draw.rect(menuDisplay , green,(810,0,450,540))
pg.display.update()
while i != self.num_items:
self.prompt = self.output_lists(i,space)
self.screen.blit(*self.prompt)
space = space + 20
pg.display.update()
i = i+1
self.done = False
#self.main_program()
while not self.done:
self.event_loop()
#Sets up the start-up screen
menuDisplay.fill(white)
pg.draw.rect(menuDisplay , black,(800,0,10,600))
#Calls mainprogram function to start the game
game_intro()
pg.display.update()
pg.quit()
quit()
|
91f42c57a8c1aabba306469e7ecd8ce43cc58320 | ChenPeng03/leetcode | /Binary_Tree_Zigzag_Level_Order_Traversal/solution.py | 476 | 3.53125 | 4 | class Solution(object):
def zigzagLevelOrder(self, root):
goRight = 1
ans = []
queue = [root]
while queue:
next_queue = []
ans.append([node.val for node in queue[::goRight]])
for i in queue:
if i.left:
next_queue.append(i)
if i.right:
next_queue.append(i)
queue = next_queue
goRight *= -1
return ans
|
c2d3e85a587c11b9bae19348149545584de22a49 | Bower312/Tasks | /task4/4.py | 791 | 4.28125 | 4 | # 4) Напишите калькулятор с возможностью находить сумму, разницу, так
# же делить и умножать. (используйте функции).А так же добавьте
# проверку не собирается ли пользователь делить на ноль, если так, то
# укажите на ошибку.
def calc(a,b,z):
if z == "+":
print(a+b)
elif z == "-":
print(a-b)
elif z == "*": #например если ввели знак * то умножай))).
print(a*b)
elif z == '/':
print(a/b)
a=int(input("введите первое число: "))
b=int(input("введите второе число: "))
z=input("знак ")
calc(a,b,z)
|
9e4b1567f3356e10136026fa23a5adfa6546f9f3 | miguelzeph/Python_Git | /2019/01_Curso_Geek_basico_avancado/sec 10 - lambda e func integradas/aula4_reduce.py | 699 | 4.09375 | 4 | """
Apartir das versões 3+ não é mais built-in.. ou seja temos que importá-la agora
reduce(funcão,dado)
-Como funciona a reduce()...
exemplo:
x = [a1,a2,a3...]
OBS: A FUNÇÃO TEM Q PEGAR 2 ELEMENTOS
1passo - pega a1 e a2 e aplica a função, guarda o resultado res = f(a1,a2)
2passo - pega res e a3 e aplica função... e assim por diante.
"""
# Programa que multiplica todos os elementos de uma lista (Fatorial!!!!)
#importar
from functools import reduce
dados = range(1,5+1)
#precisamos de uma função que receba 2 parâmetros...
func = lambda x,y: x*y
res = reduce(func,dados)
print(res)
# Exemplo - Fatorial -----
calc = 1
for x in dados:
calc = calc * x
print(calc)
|
4ceb5d1ee154f8f4ae7f2bd298335d541ed94df1 | Mahay316/Python-Assignment | /Exercise/0304/string_format.py | 1,203 | 4.25 | 4 | # 测试多种拼接、格式化字符串的方式
# test code snippet #1
username = input('username: ')
password = input('password: ')
print(username, password)
# test code snippet #2.1
name = input("name: ")
age = input("age: ")
skill = input("skill: ")
salary = input("salary:")
info = ' --- info of ' + name + ' name: ' + name + ' age: ' + age + ' skill: ' + skill + ' salary: ' + salary + ' '
print(info)
# test code snippet #2.2
name = input("name: ")
age = input("age: ")
skill = input("skill: ")
salary = input("salary: ")
info1 = ' --- info of %s --- Name:%s Age:%s Skill:%s Salary:%s ' % (name, name, age, skill, salary)
print(info1)
# test code snippet #3
name = input("username:")
age = input("age:")
skill = input("skill:")
salary = input("salary:")
# 此处是赋值
info = ' --- info of {_name} Name:{_name} Age:{_age} Skill:{_skill} Salary:{_salary} '.format(_name=name, _age=age, _skill=skill, _salary=salary)
print(info)
# test code snippet #4
name = input("name:")
age = input("age:")
skill = input("skill:")
salary = input("salary:")
info = ' --- info of {0}--- Name:{0} Age:{1} Skill:{2} Salary:{3} '.format(name, age, skill, salary)
print(info) |
8fdbb9d30be32745bb3b75b4759005826299d0de | hartantosantoso7/Belajar-Python | /set.py | 256 | 3.625 | 4 | # belajar set
# list => [] => bisa memasukkan data yang sama
# tupple => () => bisa memasukkan data yang sama
# set => {} => datanya harus unik
nama = {"Eko", "Budi", "Budi"}
nama.add("andi")
for i in nama:
print(i)
nama.remove("Eko")
print(nama) |
359f56f2e1ff3f9cb2955071a131398ab0f15a08 | suraj13mj/Python-Practice-Programs | /23. Python 22-02-20 --- Inheritance/Marks.py | 716 | 3.625 | 4 | import Student
class Marks(Student):
def __init__(self,rollno=0,name=" ",marks1=0,marks2=0):
Student.__init__(self,rollno,name)
#OR
#super().__init__(rollno,name)
self.__marks1=marks1
self.__marks2=marks2
self.__total=self.__marks1+self.__marks2f
def readMarks(self):
Student.readStudent(self)
self.__marks1=int(input("Enter Marks1:"))
self.__marks2=int(input("Enter Marks2:"))
self.__total=self.__marks1+self.__marks2
def displayMarks(self):
Student.displayStudent(self)
print("Marks1:"+str(self.__marks1),"Marks2:"+str(self.__marks2),"Total:"+str(self.__total),sep="\n")
if __name__=="__main__":
print("Single Inheritance")
stud=Marks()
stud.readMarks()
stud.displayMarks() |
77b869f94bb0d221c22debbff11f03f23c71d2f5 | sangm1n/problem-solving | /CodeUp/[070~073] 기초-종합/072.py | 265 | 3.515625 | 4 | # 1,2,3... 계속 더해 그 합이 입력한 정수보다 같거나 작을 때까지 계속 더하는 프로그램
# 마지막에 더한 정수 출력
var = int(input())
sum = 0
for i in range(1, var+1):
sum+=i
if sum>=var:
print(i)
break
|
2de622a4b93200057be6a672f1398a9d49bc50e9 | swapnil2188/python-myrepo | /write_to_file.py | 889 | 4.4375 | 4 | #!/usr/bin/python
print "\n Create a new Empty file"
f = open("myfile.txt", "x")
#Create a new file if it does not exist
f = open("myfile.txt", "w")
#OPEN a file to WRITE to it
fout = open("foo.txt", "w")
fout.write("hello world")
fout.close()
#Append to an OPEN file
f = open("demofile.txt", "a")
f.write("Now the file has more content!")
f.close()
print "\n NOTE - You can only Open or append one at a time cant do both need to close/reopen file"
print "\n #open and read the file after the appending:"
f = open("demofile.txt")
print(f.read())
f.close()
#######Open the file "demofile3.txt" and overwrite the content ###
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
print "Remove the file demofile3.txt"
import os
os.remove("demofile.txt")
|
afbd545e0f47c67c1928149f254541e7f0c65f8e | gnsisec/learn-python-with-the-the-hard-way | /exercise/ex12.py | 270 | 3.921875 | 4 | # This is Python version 2.7
# Exercise 12: Prompting People
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = int(raw_input("How much do you weight? "))
print "So, you're %r old, %s tall and %d heavy" % (
age, height, weight)
|
76daf969cd0e34779a940e09e44a5a2bb8558c0e | ndjman7/Algorithm | /Leetcode/all-elements-in-two-binary-search-trees/source.py | 606 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
answer = []
def find_node(node):
if node is None:
return
if node.left:
find_node(node.left)
if node.right:
find_node(node.right)
answer.append(node.val)
find_node(root1)
find_node(root2)
return sorted(answer)
|
0bc567891c769605b57f5d1c5a8dc8dea1e02baf | nicovlad16/Babes-Bolyai-University-Projects | /Sem1/Fundamentals of Programming/hangman/game/domain/valid.py | 648 | 3.703125 | 4 | import re
class ValidException(Exception):
pass
class Valid():
def validate(self, sentence):
if sentence == "":
raise ValidException("invalid sentence")
match = re.match("(\s*[a-z]+\s*[a-z]*)*", sentence)
if match == None:
raise ValidException("invalid sentence")
else:
words = sentence.split(" ")
for word in words:
match = re.match("[a-z]+", word)
if match == None:
raise ValidException("invalid sentence")
if len(word) < 3:
raise ValidException("invalid sentence")
|
e8ada52c361df28e6c2f54462296adeba372259e | terrenceliu01/python1 | /src/languageBasics/dictionary.py | 1,853 | 4.3125 | 4 | """
Dictionaries are Python's implementation of a data structure
that is more generally known as an associative array.
A dictionary consists of a collection of key-value pairs.
It is unordered, iterable, mutable, and each paire seperated by commas,
surrounded by {}. The key-value pairs seperated by colon.
{'key1':1, 'key2':2}
"""
# Create a dictionary
d = {}
print(type(d))
print(len(d))
d1 = {
'1': "Monday",
'2': "Tuesday",
'3': "Wendsday",
'4': "Thursday",
'5': "Friday",
'6': "Saturday",
'7': "Sunday",
}
print(d1)
post = dict(
message="SS Cotopaxi", language="English"
) # use dict() to create dict instance
# dict is iterable
for i in d1: # only iterate key
print(i, d1[i])
print()
t1 = ((1,2),(3,4),(5,6)) # dict(iterable)
d2 = dict(t1)
print(d2)
l1 = [(1,2),(3,4),(5,6)]
d2 = dict(l1)
print(d2)
# get value by key
x = d1['4'] # use key get value
print(x)
x = d1.get('6')
print(x)
x = d1.get('8') # key does NOT exist
print(f"d1 does not contain key='8': {x}")
# dict slicing
# x = d1[1:4] # dict is unordered cannot be sliced
# modify a dictionay ==> CRUD (Create, Retrieve, Update, Delete)
print(post)
post["userId"] = 1211 # Create a new key-value pair
print(post)
x = post['userId'] # Retrieve value by key
print(x)
post['userId'] = 'U1-1211' # Update value by given key
print(post)
del post['userId'] # Delete key-value pair from dictionary
print(post)
if "location" in post: # check if the key='location' in post dict
print(post["location"])
else:
print(f"no 'location' key")
# nested dictionary
d1 = {'key1':'value1'}
d2 = {'key2':'value2'}
d1['key3'] = d2
print(d1)
# dict functions (items, keys,pop)
x = d1.items()
print("79:",x)
for key, value in d1.items():
print(key, value)
x = d1.keys()
print("85:", x)
for key in d1.keys():
print(key)
|
02458259e145310a418cf6136d802c09e5505167 | jgarte/aoc-2 | /aoc/app.py | 586 | 3.75 | 4 | import argparse
from aoc import year_2020
def parse_args(args):
"""Parse command line arguments from user"""
parser = argparse.ArgumentParser()
parser.add_argument("--year", "-y", help="Get solutions for year", default="2020")
parser.add_argument("--day", "-d", help="Get solutions for day")
return parser.parse_args(args)
def get_solutions(args):
"""Based on user input, get requested solutions"""
solutions = {"2020": year_2020.run}
try:
solutions[args.year](args.day)
except KeyError:
print(f"No solutions for {args.year!r}")
|
3615c8ee1d6f4ce2054cd6b02b53d74763e5e4dd | kanhaichun/ICS4U | /Assignments/AssignmentDetails/A8Jan25.py | 1,832 | 3.6875 | 4 | '''
Assignment 8 - Photo Processing
Coding convention:
(a) lower case file name
(b) Name, Date, Title, Purpose in multiline comment at the beginning
(c) mixedCase variable names
(1) Start with the BasicFilter.py program in the Vision Apps repository from GitHub.
(2) Convert the program to work with Python 3 and OpenCV
(3) Use the program to take two similar photos, process them and produce an image that highlights the difference between the photos.
'''
#Import Image Functionality
import pygame
import pygame.camera
import pygame.image
from pygame.locals import *
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
from PIL import Image
pic_X_size = 6
pic_Y_size = 4
target = (124,129,113)
tolerance = 50
def colour_diff(target, pixel, tolerance):
if abs(target[0]-pixel[0]) < tolerance and abs(target[1]-pixel[1]) <tolerance and abs(target[2]-pixel[2])<tolerance:
return True
else:
return False
a = []
for row in range(0, pic_Y_size):
for column in range(0, pic_X_size):
pixel = (row, column)
#Take a picture and save it
image1 = cam.get_image()
pygame.image.save(image1,'test1'+str(row)+str(column)+'.PNG')
im = Image.open("test1.PNG") #Can be many different formats.
pix = im.load()
pixelcolour = pix[row, column]
#Get the pixel colour
if colour_diff(target, pixelcolour, tolerance):
a.append(pixel)
print a
###############################################################################
import pygame
import pygame.camera
import pygame.image
from pygame.locals import *
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
image1 = cam.get_image()
pygame.image.save(image1,'test1.PNG')
#/usr/share/pyshared/pygame/examples/camera.py ?
|
cff65b2cadaf8bcaab64d609386e4ce69ea3dba0 | cesarFrias/dojoPetropolis | /agosto/28/FizzBuzz.py | 481 | 3.5 | 4 | # coding: utf-8
def fizzbuzz(entrada):
if entrada % 15 == 0:
return 'fizzbuzz'
elif entrada % 3 == 0:
return 'fizz'
elif entrada % 5 == 0:
return 'buzz'
else:
return entrada
'''if entrada == 1:
return 1
elif entrada == 2:
return 2
elif entrada == 4:
return 4
elif entrada == 5:
return 'buzz'
elif entrada == 7:
return 7
elif entrada == 8:
return 8
elif entrada == 10:
return 'buzz'
else:
return 'fizz'''
if __name__ == "__main__":
pass
|
3fedd35de1ee1bcf3551e948339cb24974876100 | handol/python_study | /sh_scripts/test.py | 241 | 3.828125 | 4 | a = [1,2,3]
for n in a:
print n
b = ['aa', 'bb', 'cc']
for w in b:
print w
c = ["aa", "bb", 'cc']
for w in c:
print w
d = ('aa','bb','cc')
for w in d:
print w
print d
print d*2
print '='*3+' '*5+'='*3
print '=','b'
print "==","bb"
|
53fbea64b0b353907bc3acc38a9eccbd963812b0 | GiovanniPasserello/StatsML | /statsml/decisionclassifier/purity.py | 1,280 | 3.5625 | 4 | import math
import numpy as np
class PurityFuncs:
@staticmethod
def entropy(labels):
""" Calculate label entropy
Arguments:
labels {np.ndarray} -- A single dimensional array that we wish to calculate the entropy of
Returns:
{int} -- The entropy of the labels
"""
total = len(labels)
unique_labels, counts = np.unique(labels, return_counts=True)
label_counts = dict(zip(unique_labels, counts))
entropy = 0
for label in unique_labels:
prob = label_counts[label] / total
entropy -= prob * math.log2(prob)
return entropy
@staticmethod
def gini(labels):
""" Calculates gini impurity of a given node's labels
Arguments:
labels {np.ndarray} -- A single dimensional array that we wish to calculate the entropy of
Returns:
{int} -- The gini impurity of the node
For J classes, an impurity of (J-1)/J indicates an even distribution
e.g. gini(['a','a','b','b','c','c') = 2 / 3 = 0.66667
"""
total = len(labels)
_, counts = np.unique(labels, return_counts=True)
return 1 - np.sum(list(map(lambda p: (p / total) ** 2, counts)))
|
4e7246030914aabfb3a5267a797a048952ab7e12 | tusharmike/Assignments | /Day 6/Dequeue_Op.py | 904 | 3.984375 | 4 | class Queue:
def __init__(self, size=None):
self.size = size
self.front = self.rear = -1
self.arr = []
def enqueue(self, element):
if len(self.arr) == self.size:
print("Overflow")
return
elif self.front == -1:
self.arr.append(element)
self.front = self.rear = 0
return
self.arr.append(element)
self.rear = len(self.arr) - 1
return
def dequeue(self):
if self.arr is None:
print("Underflow")
return
self.arr.pop(self.front)
return
def printQueue(self):
if self.arr is None:
print("Queue is Empty")
return
print(self.arr)
return
q = Queue(5)
q.enqueue("a")
q.enqueue("b")
q.enqueue("c")
q.dequeue()
q.dequeue()
q.printQueue()
|
bd6feda76e8155ffc9f5a3b2a162d201e5f18c07 | Andrewjjj/Kattis | /Python3/1.3/Planina/planina.py | 106 | 3.9375 | 4 | a=int(input())
def fib(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print(fib(a+3)**2)
|
367c259c69ce5853f1d5464ff8ffc85993ac9a87 | kongtaoxing/Freshman-Short_Semester-Python | /实验1源码/1.数字之和.py | 67 | 3.5 | 4 | a=int(input())#number a
b=int(input())#number b
print(a+b) #a+b
|
3177f850c65a22b613d117ab2d1d150ee3707189 | moskovets/numAlgorithm4sem | /approximation(mid2).py | 3,985 | 3.5625 | 4 | """
наилучшее среднеквадратичное приближениеи
"""
from math import sin, pi, factorial, cos, exp, log
from collections import namedtuple
Table = namedtuple('Table', ['x','y', 'w']) # w = вес функции
eps_const = 0.00001
eps_otn = 0.0001
def fi(x, k):
return x ** k
# Загрузка таблицы координат точек и их весов из файла
def get_table(filename):
infile = open(filename, 'r')
data = []
for line in infile:
if line:
a, b, c = map(float, line.split())
data.append(Table(a, b, c))
print(data)
infile.close()
return data
# Вывод графика аппроксимирующей функции и исходных точек
def print_result(table, A, n):
import numpy as np
import matplotlib.pyplot as plt
dx = 10
if len(table) > 1:
dx = (table[1].x - table[0].x)
# построение аппроксимирующей функции
x = np.linspace(table[0].x - dx, table[-1].x + dx, 100)
y = []
for i in x:
tmp = 0;
for j in range(0, n + 1):
tmp += fi(i, j) * A[j]
y.append(tmp)
plt.plot(x, y)
#построение исходной таблицы
x1 = [a.x for a in table]
y1 = [a.y for a in table]
plt.plot(x1, y1, 'kD', color = 'green', label = '$исходная таблица$')
plt.grid(True)
plt.legend(loc = 'best')
miny = min(min(y), min(y1))
maxy = max(max(y), max(y1))
dy = (maxy - miny) * 0.03
plt.axis([table[0].x - dx, table[-1].x + dx, miny - dy, maxy + dy])
plt.show()
return
# получение СЛАУ по исходным данным для заданной степени
# возвращает матрицу коэф. и столбец свободных членов
def get_slau_matrix(table, n):
N = len(table)
matrix = [[0 for i in range(0, n + 1)] for j in range (0, n + 1)]
col = [0 for i in range(0, n + 1)]
for m in range(0, n + 1):
for i in range(0, N):
tmp = table[i].w * fi(table[i].x, m)
for k in range(0, n + 1):
matrix[m][k] += tmp * fi(table[i].x, k)
col[m] += tmp * table[i].y
return matrix, col
# умножение столбца на матрицу
def mult(col, b):
n = len(col)
c = [0 for j in range(0, n)]
for j in range(0, n):
for k in range(0, n):
c[j] += col[k] * b[j][k]
return c
# поиск столбца обратной матрицы
def find_col(a_copy, i_col):
n = len(a_copy)
a = [[a_copy[i][j] for j in range(0, n)] for i in range (0, n)]
col = [0 for i in range(0, n)]
for i in range(0, n):
a[i].append(float(i == i_col))
for i in range(0, n):
if a[i][i] == 0:
for j in range(i + 1, n):
if a[j][j] != 0:
a[i], a[j] = a[j], a[i]
for j in range(i + 1, n):
d = - a[j][i] / a[i][i]
for k in range(0, n + 1):
a[j][k] += d * a[i][k]
for i in range(n - 1, -1, -1):
res = 0
for j in range(0, n):
res += a[i][j] * col[j]
col[i] = (a[i][n] - res) / a[i][i]
return col
# получение обратной матрицы
def get_inverse_matrix(a):
n = len(a)
res = [[0 for i in range(0, n)] for j in range (0, n)]
for i in range(0, n):
col = find_col(a, i)
for j in range(0, n):
res[j][i] = col[j];
return res;
# получение коэф. аппроксимирующей функции
def get_approx_coef(table, n):
m, z = get_slau_matrix(table, n)
inv = get_inverse_matrix(m)
a = mult(z, inv)
return a
table = get_table("table.txt")
n = int(input("Введите степень полинома n = "))
A = get_approx_coef(table, n)
print_result(table, A, n)
|
6d6c96e9bda4690864dd5202559a94bfdfbc7d6f | yudhinr/buku-python | /contoh/list.py | 270 | 4 | 4 | # contoh list di Python
daftar = [7, 1, 5, 3, 2, 4, 6, 8, 3, 5]
print(daftar)
print("list memiliki", len(daftar), "elemen")
# akses elemen yang pertama (dengan indeks 0)
print("daftar[0] =", daftar[0])
# menambahkan data ke list
daftar = daftar + [7, 9]
print(daftar)
|
db858c79926a87cb9eaffd5ca589bec51f40df5a | UzairIshfaq1234/python_programming_PF_OOP_GUI | /2class.py | 1,375 | 4.0625 | 4 | class login:
def __init__(self):
self.data={}
def add_data(self):
self.username=input("Enter your name :")
self.password=int(input("Enter your Password:"))
self.data.update({self.username:self.password})
print("___________________________DATA SUBMITTED!____________________________")
def login(self):
self.finduser=input("Enter your Username:")
self.findpass=int(input("Enter your password: "))
print("_________________________________________")
if self.finduser in self.data.keys():
if self.findpass in self.data.values():
print("\n")
print("_________________________________________")
print(f"DEAR {self.finduser} YOU HAVE ACCESSED!")
print("_________________________________________")
else:
print("\n")
print("Incorrect password!")
else:
print("\n")
print("Incorrect Username!")
person=login()
while True:
print("PRESS 1 TO ADD DATA!")
print("PRESS 2 TO LOGIN!")
print("______________")
choice=int(input(""))
print("______________")
if choice==1:
person.add_data()
elif choice==2:
person.login()
else:
print("You pressed incorrect key!")
|
6572b241b7b22f5fa8573e2aeb170c9929e9b7a4 | eichingertim/WhatsAppChatBot | /ChatBot.py | 5,625 | 3.53125 | 4 | # Simple WhatsApp-ChatBot
# Future Plan: integrating machine learning, so the bot can send messages by knowledge
# author: Tim Eichinger
from selenium import webdriver
from Calender import Calender
import time
driver = webdriver.Chrome()
driver.get('https://web.whatsapp.com/')
global length_before
global already_answered
# your fullname and firstname, the bot should detect and use
fullname = "<your fullname>"
firstname = "<your firstname>"
# bad or offensive words that the bot can detect
# e.g.: bad_words = ['asshole', 'shithead']
bad_words = []
# groups and persons, the bot should not answer
# e.g.: groups_without_authorization = ['Footballteam 2019', 'Franz Maier']
groups_without_authorization = []
# checks and returns your current event
def get_current_event():
return Calender.get_current_event()
# returns the answer the chat bot should print
def get_answer(texts, chat_name):
if "ChatBot (v1.0)" in str(texts[-1]):
print("ERROR: Last message was from Bot")
return ""
list_splitted_msg = str(texts[-1]).split()
return_string = ""
bad_words_already_in_string = False
if fullname in str(texts[-1]) or firstname in str(texts[-1]):
if chat_name in already_answered:
return_string += get_current_event()
else:
return_string += firstname + ' is currently not online. I take over! '
return_string += get_current_event()
already_answered.append(chat_name)
elif chat_name not in already_answered:
return_string += firstname + ' is currently not online. I take over! '
return_string += get_current_event()
already_answered.append(chat_name)
for item in list_splitted_msg:
if item in bad_words and not bad_words_already_in_string:
return_string += 'I discovered an insult (\"{}\")! I can not tolerate that!'.format(item)
bad_words_already_in_string = True
return return_string
# Checks, whether the bot can send a message to the specific chat and handles the following send process
def send_text(par_elements, par_msg_box):
go_to_infos = driver.find_element_by_class_name('_5SiUq')
go_to_infos.click()
time.sleep(2)
chat_name = driver.find_element_by_xpath('//div[@class = "{}"]'.format('_2S1VP copyable-text selectable-text')).text
if chat_name == "":
chat_name = driver.find_element_by_xpath('//span[@class = "{}"]'.format('iYPsH')).text
go_back = driver.find_element_by_xpath('//button[@class = "{}"]'.format('_1aTxu'))
go_back.click()
texts = []
for elem in par_elements:
texts.append(elem.text)
answer = get_answer(texts, chat_name)
print(f'CURRENT CHAT: {chat_name}')
if chat_name in groups_without_authorization:
print("ERROR: Bot has no authorization to send the message")
elif answer == "":
print("ERROR: No answer generated")
else:
par_msg_box.send_keys("*ChatBot (v1.0):* " + answer)
btn = driver.find_element_by_class_name('_35EW6')
btn.click()
print(f'MESSAGE SENT: {answer}')
# sets the length of the array from the last scanning of all messages
def set_length_before():
# gets all the text elements in a chat
span_class = 'selectable-text invisible-space copyable-text'
elements = driver.find_elements_by_xpath('//span[@class = "{}"]'.format(span_class))
return len(elements)
# checks for a new message in the current chat
def check_for_current_chat_new_message():
try:
# includes the message box where users can enter their message
msg_box = driver.find_element_by_class_name('_1Plpp')
# gets all the text elements in a chat
span_class = 'selectable-text invisible-space copyable-text'
elements = driver.find_elements_by_xpath('//span[@class = "{}"]'.format(span_class))
if len(elements) > length_before:
send_text(elements, msg_box)
except:
print('ERROR: No new message found in current Chat')
# checks, whether a new messages drops in other chats not in the current chat
def check_for_new_chat_new_message():
try:
user = driver.find_element_by_xpath('//span[@class = "{}"]'.format('OUeyt'))
user.click()
time.sleep(1)
# includes the message box where users can enter their message
msg_box = driver.find_element_by_class_name('_1Plpp')
# gets all the text elements in a chat
span_class = 'selectable-text invisible-space copyable-text'
elements = driver.find_elements_by_xpath('//span[@class = "{}"]'.format(span_class))
send_text(elements, msg_box)
return True
except:
print('ERROR: No new message found in all chats')
return False
# starts the bot
def start_bot():
if check_for_new_chat_new_message():
print('NEW MESSAGE FOUND IN ALL CHATS')
else:
check_for_current_chat_new_message()
if __name__ == '__main__':
start_bool = input("Start ChatBot [START]: ")
if start_bool == "START" or start_bool == "start":
print('\n*** ChatBot started ***\n')
length_before = 0
already_answered = []
while True:
start_bot()
print('CHAT LENGTH BEFORE ATTACHING: ' + str(length_before))
try:
length_before = set_length_before()
except:
print('ERROR: No data for length')
print('CHAT LENGTH BEFORE ATTACHING: ' + str(length_before))
print('------------------------------------------')
print('')
time.sleep(3)
|
d58f8619a091bed85dac1ba4823ff15b3ac82d6c | c940606/leetcode | /Length of Last Word.py | 444 | 3.96875 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
:type s: str
:rtype: int
"""
s = s.strip()
return len(s.split()[-1])
s = "Hello World"
a = Solution()
print(a.lengthOfLastWord(s))
|
b30d05c6d4c00fb19282904b71d727f911d89f7d | MichaelrMentele/katas | /HRSecondLowestStudentGrade.py | 1,166 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 9 06:48:11 2016
@author: michaelmentele
"""
def secondLowest(students):
''' Returns the second lowest grade in an [['name', grade]...n] array of arrays'''
students = sortStudents(students)
return students[1]
def swap(s1, s2):
temp = s1
s1 = s2
s2 = temp
return s1, s2
def sortStudents(students):
loop = len(students)
for i in range(loop-1):
for j in range(loop-1):
if students[j][1] > students[j+1][1]:
students[j][1], students[j+1][1] = swap(students[j][1], students[j+1][1])
return students
#==============================================================================
# students = [['john', 10.0], ['jacob', 6.0], ['jingle', 40.3], ['jam', 1.0]]
# print('This is the return: ' + str(sortStudents(students)))
#==============================================================================
n = int(input())
students = []
for i in range(n):
name = input()
grade = int(input())
student = [name,grade]
students.append(student)
print(secondLowest(students))
|
910a5c486f6563c44ffe91563b22060c8b33c7a6 | apugithub/Python_Self | /odd_even.py | 167 | 4.1875 | 4 | a = int(input("Enter the value: "))
def odd_even(n):
if (n%2==1):
print("The number is odd")
else:
print("The number is even")
odd_even(a)
|
327d89342b955e0d57290b37049c5a4d8cc30fbd | rastukis/curso-python-intermedio | /001_strings.py | 284 | 3.625 | 4 | my_string = ''' Este es un string que contiene
saltos de linea.'''
print(my_string)
# Concatenacion
num_1 = 1
message_1 = "Mensaje num: " + str(num_1)
message_2 = "Otro mensaje: %s" %num_1
message_3 = "Otra forma: {}".format(num_1)
message_4 = f"Otra forma {num_1}"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.