blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
85edd6b7d6c8490c09b40db79c6bb337c60a79d4 | iWonder118/atcoder | /python/ABC134/C.py | 192 | 3.578125 | 4 | n = int(input())
a = [int(input()) for _ in range(n)]
a_sort = sorted(a, reverse=True)
for i in range(n):
if a[i] == a_sort[0]:
print(a_sort[1])
else:
print(a_sort[0])
|
ec54b5db79357118b8829c13559817573b13930f | un4ckn0wl3z/ntp-scanner | /ntp-scanner.py | 1,905 | 3.546875 | 4 | #!/usr/bin/env python
#coding=utf8
"""NTP Scanner and 'monlist' checker
INSTALLATION: (debian)--
sudo apt-get install python-pip python-argparse ntp;
sudo pip install ntplib iptools;
Usage:
python ntp-scanner.py [ARGS]
-f, --file : specify input file
-t, --target : specify specific host or subnet(cidr)
--help : print help
"""
from ntplib import *
from time import ctime,sleep
import os
import argparse
import iptools
import sys
class c:
OKGREEN = '\033[92m'
FAIL = '\033[91m'
ENDC = '\033[0m'
ERROR = "[" + c.FAIL + " !! " +c.ENDC + "] "
OK = "[" + c.OKGREEN + " OK " + c.ENDC + "] "
arg = argparse.ArgumentParser()
arg.add_argument("-t", "--target", help="Scan NTP for a given host")
arg.add_argument("-f", "--file", help="Input file")
args = arg.parse_args()
addr = args.target
scan_file = args.file
def check_ntp(addr):
try:
n = NTPClient()
ans = n.request(addr, version=3)
print OK + "NTP is enabled on {}".format(addr)
print "\t" + ctime(ans.tx_time)
test_monlist = os.system("ntpdc -c monlist {}".format(addr))
if test_monlist is None:
print ERROR+"Unable to query monlist on {}\n".format(addr)
else:
print OK+"monlist query successful on {}\n".format(addr)
except KeyboardInterrupt:
print "Exiting on user interrupt.."
sys.exit()
except Exception, e:
print ERROR + "Error Connecting to {} \n {}\n".format(addr,str(e))
if __name__ == '__main__':
if not "/" in args.target:
print addr
check_ntp(addr)
elif "/" in args.target:
range = iptools.IpRange(addr)
for ip in range:
print ip
check_ntp(ip)
elif args.file:
with open(scan_file, 'r') as f:
for line in f:
check_ntp(line)
else:
print "You must supply a host to scan"
sys.exit(2)
|
e71f13030e7308a6871ae98ba0a4a5751acde156 | AnaelBourgneuf/imie | /maths/transpositionmatrice.py | 240 | 3.5 | 4 | def transposition(mat):
nmat=[];
lignes=len(mat)
colonnes=len(mat[0])
for i in range(0,colonnes):
nmat+=[[],]
for j in range(0,lignes):
nmat[i]+=[mat[j][i],]
return nmat
print(transposition([[1,0,4],[-3,2,5],[7,-3,6],[1,0,7]])) |
2386f31d0c47643f77be7030b3ec09d486b482e6 | sam1017/pythonstudy | /find_prime_number.py | 574 | 3.8125 | 4 | import time
from math import sqrt
prime_number_list = [2]
n = 10000
start = time.clock()
for i in range(3,n):
is_prime = False
sqrt_i = int(sqrt(i) + 1)
for j in prime_number_list:
if(j <= sqrt_i):
if i%j == 0:
is_prime = False
break
else:
is_prime = True
else:
break;
if is_prime == True:
prime_number_list.append(i)
t = time.clock() - start
#print(prime_number_list)
print("find prime number in range( 2, " + str(n) + ") using time ...")
print(t)
|
b0498c139793f93a1b2facf9bd7a665b87dfb78c | MrHamdulay/csc3-capstone | /examples/data/Assignment_1/bdlren001/question2.py | 475 | 4.21875 | 4 | # A program to check the validity of a time entered by the user as a set of three integers.
# BDLREN001
# Budeli Rendani
# 01 March 2014
def time():
hours = eval(input("Enter the hours:\n"))
minutes = eval(input("Enter the minutes:\n"))
seconds = eval(input("Enter the seconds:\n"))
if 0<=hours<=23 and 0<=minutes<=59 and 0<=seconds<=59:
print("Your time is valid.")
else:
print("Your time is invalid.")
time() |
150f73ab74236b7e9de7b19949f1020e1cae1d9c | thinkerston/curso-em-video-python3 | /mundo-01/exercicio-024.py | 226 | 3.875 | 4 | '''Crie um programa que leia o nome de uma cidade e diga se ala começa ou não com o nome SANTO'''
nomeCidade = str(input('Insira o nome de sua cidade: ')).lower()
santoExiste = bool('santo' in nomeCidade)
print(santoExiste) |
90575b86313a86d861d02833cc3ae5de1131ca6a | jwutt3/Python-Masterclass-Code | /Variables/varables.py | 999 | 4.1875 | 4 | # 5.4 Storing items invariables
# Variables can start with a letter (upper or lower) or an underscore
# Greeting = "'ello govner"
# greeting = "Hello"
# _myName = "Jamie"
#
# age = 24
# print(age)
#
# print(greeting + age)
# a = 12
# b = 3
# print(a + b)
# print(a-b)
# print(a*b)
# print(a/b)
# print(a // b)
# print(a % b)
#
# for i in range(1,(a//b)):
# print(i)
# print(a + b / 3 - 4 * 12)
# print((((a+b)/3)-4)*12)
# 5.5 More about variables and strings
# c = a+b
# d = c/3
# e = d-4
# print(e*12)
parrot = "Norwegian Blue"
print(parrot)
print(parrot[0])
print(parrot[3])
print(parrot[-1])
print(parrot[0:6])
print(parrot[:6])
print(parrot[6:])
print(parrot[0:6:2])
number = '9,223,372,063,854,775,807'
print(number[1::4])
numbers = "1, 2, 3, 4, 5, 6, 7, 8, 9"
print(numbers[0::3])
string1 = "he's "
string2 = "probably "
print(string1+string2)
print("he's " "probably " "pining")
print("Hello " *5)
today = "friday"
print("day" in today)
print("fri" in today)
print("thur" in today) |
4a255f928c8f9b38e14f4f69edb6726f07f72011 | qinyaoting/python3-study | /lxf/function_def_func.py | 1,005 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test module '
from multiprocessing import Process, Pool, Queue
import os, time, random
import math
__author__ = 'chin'
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
# 奇特: 原来返回值是一个tuple!但是,在语法上,返回一个tuple可以省略括号
return nx, ny
if __name__ == '__main__':
# 定义函数
print(my_abs(-11))
print(my_abs(11))
# 如果参数个数不对, 会抛出 TypeError: my_abs() takes 1 positional argument but 2 were given
#print(my_abs(11, 22))
# 如果参数类型不对 TypeError: '>=' not supported between instances of 'str' and 'int'
# print(my_abs('A'))
# 奇特: 返回多个值
x, y = move(100, 100, 60, math.pi/6)
print(x, y)
|
e31ca9bc31bc643656b4133028f22840011a8ae0 | futurice/PythonInBrowser | /examples/sessiona/010_print.py | 1,705 | 3.75 | 4 | ## Printtailu ja laskutoimitusharjoituksia
print u"Terve jälleen!"
print u"Nyt lasketaan: 77 + 89 = ", 77+89
## Python on ohjelmointikieli, jota voi tietenkin käyttää myös laskimena
#print 5+6
########################################################
## TEHTÄVÄ 1:
## Poista alla rivien aluista kommenttimerkit, eli nuo häshtägit (#).
## Miksi? Koska Python tulkki jättää huomiotta kaiken #:n jälkeen.
#print 1.0/2.0
#print 2.5/5
#print 5/3.0
########################################################
## TEHTÄVÄ 2:
## Keksitkö mikä matemaattinen operaatio on "**"?
## Vihje: Muuttele numeroita.
#print 3.0 ** 2.0
########################################################
## TEHTÄVÄ 3:
## Pythonin "math" -kirjasto
##
## Huom: import -komento on Pythonin perusteita.
import math # otetaan Pythonin matematiikka kirjasto käyttöön.
## Mutta mistä tietää mitä "math":in sisältä löytyy? -> KVG
#print "sin(0) = ", math.sin(0)
#print "sin(0) = ", math.sin(math.pi * 2)
#print "sin(pi) = ", math.sin(math.pi)
########################################################
## TEHTÄVÄ 4:
## Muuttujan käyttö
##
## Tutkitaan trigonometrian perusyhtälöä:
#print "sin(x)^2 + cos(x)^2 = ???"
## Tässä luodaan muuttuja, jolle annetaan arvo.
luku = 0.77
## Muuttujat helpottavat ohjelmointia.
## Osaatko selittää miksi?
##
## Nyt itse asiaan:
#print math.pow(math.sin(luku), 2) + math.pow(math.cos(luku), 2)
## Olisiko joku järkevämpi matemaattinen funktio,
## jonka arvoja tarkastella?
########################################################
## BONUS:
## Selvitä tämä: mikä matemaattinen operaatio on "%"?
## Vihje: Muuttele numeroita.
#print 4.0 % 3.0
|
574bf1cf0a182ef2730ccda313ae0f7da4aa4f6b | namichael/Grad_School_Coding | /Misc/recursive_step.py | 234 | 4.0625 | 4 | # Recursive Step Problem
def recurse_step(n):
if n and n - 1:
return recurse_step(n-1) + recurse_step(n-2)
else:
return 1
def main(n):
print recurse_step(n)
if __name__ == "__main__":
import sys
main(int(sys.argv[1]))
|
104714cc569c16259c8454ca10c587902e92a24b | hegde421201/python_programming | /arrays/TwoSum1.py | 1,620 | 4.125 | 4 | from typing import List
def twoSum(nums: List[int], target: int) -> List[int]:
# step 1 : define a hashmap with key as the element of the List and the corresponding value as the index in the List
hashmap = dict()
# step 2: We require both index and the actual number for the hashmap created in step 1 above.
# We use enumerate() method in python on the list
for index, num in enumerate(nums):
difference = target - num # check whether the difference is in the hashmap
if difference in hashmap:
return [index, hashmap[difference]] # return the indices pair of index and the dictionary element key
hashmap[num] = index
# time complexity O(n)
# space complexity O(n)
lists = [2, 7, 11, 15]
target = 9
print(twoSum(lists, target))
lists = [3, 4, 2]
target = 6
print(twoSum(lists, target))
lists = [3, 3]
target = 6
print(twoSum(lists, target))
'''
https://leetcode.com/problems/two-sum/
1.Two Sum
---------
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
Only one valid answer exists.
'''
|
06a15f23b1b553a94ddde85529412ee350602d61 | royqh1979/programming_with_python | /Chap04Functions/5-1-3.求某班平均分-高阶函数实现.py | 1,458 | 3.546875 | 4 | import csv
from easygraphics import dialog as dlg
from dataclasses import dataclass
@dataclass()
class Score:
id: str
name: str
clazz: str
math: int
literacy: int
english: int
def read_csv(filename):
"""
从csv文件中读取学生成绩信息
:param filename: 文件名
:return: 学生信息列表
"""
scores=[]
with open(filename,mode="r",encoding="GBK") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
id = row[0]
name = row[1]
clazz = row[2]
math = int(row[3])
literacy = int(row[4])
english = int(row[5])
score = Score(id,name,clazz,math,literacy,english)
scores.append(score)
return scores
def score_to_total(score):
return score.math+score.english+score.literacy
def generate_filter_by_class(clazz):
def filter(score):
return score.clazz == clazz
return filter
filename = dlg.get_open_file_name("请选择数据文件",dlg.FileFilter.CSVFiles)
if filename == "":
print("未选择文件")
exit(-1)
scores = read_csv(filename)
clazz = dlg.get_string("请输入班级名称")
filter_by_class = generate_filter_by_class(clazz)
lst1=filter(filter_by_class,scores)
lst2=list(map(score_to_total,lst1))
total = sum(lst2)
count = len(lst2)
average = total / count
print(f"{clazz}班{count}名同学三科平均分为{average:.2f}") |
a322a47eb4e0cdb5fd8313416ba4e2e327ef3de3 | Divij-berry14/Python-with-Data-Structures | /StringMatchingAlgos/NaivePatternSearching.py | 976 | 4.0625 | 4 | def NaivePatternSearching(txt,pat):
n=len(txt)
m=len(pat)
for i in range(n-m+1):
j=0
while(j<m):
if(txt[i+j]==pat[j]):
j=j+1
else:
break
if j==m:
print("Pattern found at index at position",i)
txt = "AABAACAADAABAAABAA"
pat = "AABA"
NaivePatternSearching(txt,pat)
#What is the best case?
# The best case occurs when the first character of the pattern is not present in text at all.
# txt[] = "AABCCAADDEE";
# pat[] = "FAA";
# The number of comparisons in best case is O(n).
# What is the worst case ?
# The worst case of Naive Pattern Searching occurs in following scenarios.
# 1) When all characters of the text and pattern are same.
# txt[] = "AAAAAAAAAAAAAAAAAA";
# pat[] = "AAAAA";
# 2) Worst case also occurs when only the last character is different.
# txt[] = "AAAAAAAAAAAAAAAAAB";
# pat[] = "AAAAB";
# The number of comparisons in the worst case is O(m*(n-m+1)) |
961d3d9f80c130f3f1fe0b5443b2f516bedd51f0 | eamaccready/STP_Exercises | /python_scripts/stack_reverse_list.py | 602 | 4 | 4 | class Stack():
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, new_item):
self.items.append(new_item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def reverse(list):
stack = Stack()
result = []
for item in list:
stack.push(item)
while not stack.is_empty():
result.append(stack.pop())
return result
to_reverse = [1, 2, 3, 4, 5]
print(reverse(to_reverse))
|
84195deb2246e90b6aae3413c6a10d48976f2e0f | chenyaoling/python-study2 | /day04/06-TCP服务端增强.py | 1,803 | 3.546875 | 4 | # 1、导入模块
import socket
# 2、创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 3、绑定端口和ip
tcp_server_socket.bind(("", 8081))
# 4、开启监听(设置套接字为被动模式)
# listen() 作用设置 tcp_server_socket 套接字为被动监听模式,不能在主动发送数据
# 128 允许接受的最大的连接数,在windows 128 有效,但是在linux 此数字无效
tcp_server_socket.listen(128)
# 5、等待客户端连接
# accept() 开始接受客户端连接,程序会默认进入阻塞状态(等待客户端连接),如果由客户端连接后,程序自动自动解除阻塞
# recv_data 数据含有两部分 1)返回了一个新的套接字socket 对象 2) 客户端的ip地址和端口号 元组
while True:
new_client_socket, client_ip_port = tcp_server_socket.accept()
print("新客户端来了:%s" % str(client_ip_port))
# 6、收发数据
while True:
# recv() 会让程序再次阻塞,收到信息后再接阻塞
recv_data = new_client_socket.recv(1024)
# 当接受到数据为 空 的时候,表示客户端已经断开连接了,服务端也要断开
# if len(recv_data)!= 0:
# b'xxxx'
# 如果recv_data 非空即为真,否则为假
if recv_data:
recv_text = recv_data.decode("GBK")
print("接收到[%s]的信息:%s" % (str(client_ip_port), recv_text))
else:
print("客户端已经断开连接!")
break
# new_client_socket.close() 表示不能再和当前的客户端通信了
new_client_socket.close()
# 7、关闭连接
# tcp_server_socket.close() 表示程序不再接受新的客户端连接,已经连接的可以继续服务
tcp_server_socket.close()
|
c573ec5425620fc5c6da572635c24f3cdd828e1e | sluisdejesus/Week_2_single_class_lab | /team_class/src/team.py | 769 | 3.890625 | 4 | class Team:
def __init__(self, input_name, input_players,input_coach):
self.name = input_name
self.players = input_players
self.coach = input_coach
self.points = 0
def team_has_name(self):
return self.name
def team_has_players(self):
return self.players
def team_has_coach(self):
return self.coach
def add_player(self, name):
self.players.append("name")
def has_player(self, player_to_find):
return self.players.count(player) > 0
# alternative way
# for player in self.players:
# if player == player_to_find:
# return True
# return False
def play_game(self, game_won):
if game_won:
self.points += 3 |
92e65cce9c70fcc506313b326855389ea90a309f | Mukilavan/python | /Even.py | 101 | 3.515625 | 4 | a,n=input().split()
a=int(a)
n=int(n)
for i in range(a,n):
if(i%2==0 and i!=a):
print(i,end=" ")
|
7e8feeb318bf16f3b0274e5bf3146fd369130314 | eklavaya2208/practice-ml-cp | /Machine Learning/Part 2 - Regression/Section 8 - Decision Tree Regression/selfcoded.py | 803 | 3.703125 | 4 | #importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2:3].values
#Fitting the decision tree regression to the dataset
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state = 0)
regressor.fit(X,y)
#Predicting a new result
y_pred = regressor.predict(6.5)
#Visualising the decision tree regression results in higher res
X_grid = np.arange(min(X),max(X),0.01)
X_grid = X_grid.reshape(len(X_grid),1)
plt.scatter(X,y,color='red')
plt.plot(X_grid,regressor.predict(X_grid),color='blue')
plt.title('Truth or Bluff(decision tree regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()
|
6b93c93a3afee03573c143e0d8110b887ac0e63c | HeyYou-dev/ninjaRepo | /Easy/TwoSumProblem/twoSUM_GreedyApproach.py | 1,066 | 3.625 | 4 | class Solution:
def twoSum (self,nums,target):
temp =[]
#Sort the arrary first
nums.sort()
#Getting forward and backward index
forward = 0
backward = len(nums)-1 #Last index of nums
while (forward<backward):
sum = nums[forward]+nums[backward]
if sum==target:
a=list([forward,backward])
temp.append(a)
print(a[1])
if (nums[a[0]]==nums[forward+1]):
print('for')
forward+=1
continue
elif (nums[a[1]]==nums[backward-1]):
print('back')
backward-=1
continue
else:
forward+=1
backward-=1
elif sum<target:
forward+=1
else:
backward-=1
return temp
nums = [0,0,1,2,3,3]
target = 3
solution = Solution()
print(solution.twoSum(nums,target))
|
9d1502c8c43336cdbea7b3f27bf7493edc05cb16 | apusty/pcl2_ex4 | /fun_with_strings.py | 1,453 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Programmiertechniken in der Computerlinguistik II
# Augabe 4
# Autor: Angelina Pustynskaia
from typing import Iterable
def longest_substrings(x: str, y: str) -> Iterable[str]:
# make both lower case
x = x.lower()
y = y.lower()
n = len(x)
m = len(y)
# build an empty matrix (from lecture slide 21)
d = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
# assign the value to each cell (+ 1 from the diagonal one if the two letters are the same)
for i in range(1, n + 1):
for j in range(1, m + 1):
if x[i - 1] == y[j - 1]:
d[i][j] = d[i - 1][j - 1] + 1
# take the maximal values from the matrix, and store the positions
max_len = 0
max_pos = []
# only go through one of the words (x) as the suffixes are the same
for i in range(n + 1):
if max(d[i]) > max_len:
max_len = max(d[i])
max_pos = [i]
elif max(d[i]) == max_len:
max_pos.append(i)
# if the maximal value found is 0, this means there is no common suffix
if max_len == 0:
return None
else:
return [x[pos-max_len:pos] for pos in max_pos]
if __name__ == '__main__':
print(longest_substrings('Tod', 'Leben'))
print(longest_substrings('Haus', 'Maus'))
print(longest_substrings('mozart','mozzarella'))
print(longest_substrings('keep the interface!', 'KeEp ThE iNtErFaCe!'))
|
dd592911102160de535df11665866d9d78b7e9f3 | radrajith/Artificial_Intelligence | /Search Algorithms - Proj 1/SearchAlgorithms/Node.py | 589 | 3.8125 | 4 | #implementation of the tree. Each node has 4 children.
class Node:
up = 0;
down = 1;
left = 2;
right = 3;
parent = -1;
def __init__(self, parent):
self.node = []
self.parent = parent
def addUp(self, child):
self.node[self.up] = [child, 'up']
def addDown(self, child):
self.node[self.down] = [child, 'down']
def addLeft(self, child):
self.node[self.left] = [child, 'left']
def addRight(self, child):
self.node[self.right] = [child, 'right']
def getParent(self, parent):
return self.parent
|
2d6ceb13782c1aa23f2f1c9dce160b7cb51cb5f3 | nguya580/python_fall20_anh | /week_02/week02_submission/week02_exercise_scrapbook.py | 2,398 | 4.15625 | 4 | # %% codecell
# Exercise 2
# Print the first 10 natural numbers using a loop
# Expected output:
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
x = 0
while x <= 10:
print(x)
x += 1
# %% codecell
# Exercise 3:
# Execute the loop in exercise 1 and print the message Done! after
# Expected output:
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# Done!
x = 0
while x <= 10:
print(x)
x += 1
if x > 10:
print("Done!")
# %% codecell
# Exercise 4:
# Print the numbers greater than 150 from the list
# list = [12, 15, 47, 63, 78, 101, 157, 178, 189]
# Expected output:
# 157
# 178
# 189
list = [12, 15, 47, 63, 78, 101, 157, 178, 189]
for number in list:
if number > 150:
print(number)
# %% codecell
# Exercise 5:
# Print the number that is even and less than 150
# list = [12, 15, 47, 63, 78, 101, 157, 178, 189]
# Expected output:
# 12
# 78
# Hint: if you find a number greater than 150, stop the loop with a break
list = [12, 15, 47, 63, 78, 101, 157, 178, 189]
for number in list:
if number < 150 and number % 2 == 0:
print(number)
# %% codecell
# Exercise 6:
# This will be a challenging!
# Write a while loop that flips a coin 10 times
# Hint: Look into the random library using:
# https://docs.python.org/3/library/random.html
# https://www.pythonforbeginners.com/random/how-to-use-the-random-module-in-python
import random
head_count = []
tail_count = []
def flip_coin():
"""this function generates random value 0-1 for coin
1 is head
0 is tail"""
coin = random.randrange(2)
if coin == 1:
print(f"You got a head. Value is {coin}")
head_count.append("head")
else:
print(f"You got a tail. Value is {coin}")
tail_count.append("tail")
def flip():
"""this function generate flipping coin 10 times"""
for x in range(10):
flip_coin()
print(f"\nYou flipped HEAD {len(head_count)} times, and TAIL {len(tail_count)} times.\n")
again()
def again():
"""ask user if they want to flip coint again."""
ask = input("Do you want to flip coint again? \nEnter 'y' to flip, or 'n' to exit.\n")
if ask == "y":
#clear lists output to remains list length within 10
del head_count[:]
del tail_count[:]
#run flipping coin again
flip()
elif ask == "n":
print("\nBye bye.")
#call function
flip()
|
c700c0f2155ae38d41684a83362f4d861b91003b | 5coho/Stock-Predictor | /src/stockPredictor.py | 4,189 | 3.5625 | 4 | """
--stock predictor file--
This file hold one class, stockPredictor which hold the function relating
to predicting a stock such as Linear Regression
"""
# Metadata
__author__ = "Scott Howes, Braeden Van Der Velde, Tyler Leary"
__credits__ = "Scott Howes, Braeden Van Der Velde, Tyler Leary"
__email__ = "showes@unbc.ca, velde@unbc.ca, leary@unbc.ca"
__python_version__ = "3.8.1"
# imports
import pandas as pd
pd.options.mode.chained_assignment = None
import datetime as dt
from sklearn.linear_model import LinearRegression
import numpy as np
#from keras.models import Sequential
#from sklearn.preprocessing import MinMaxScaler
#from dataFetch import dataFetch
class stockPredictor:
# do nothing constructor
def __init__(self):
pass
# def sequence_to_sequence(self, symbol, startDate, endDate):
# datafetch = dataFetch()
# df = datafetch.getData(symbol, startDate=startDate, endDate=endDate)
# df.reset_index(inplace=True)
# # dataframe creation
# series_data = df.sort_index(ascending=True, axis=0)
# processed_data = pd.DataFrame(index=range(0, len(df)), columns=['Date', 'Close'])
# length_of_data = len(series_data)
# for i in range(0, length_of_data):
# processed_data['Date'][i] = series_data['Date'][i]
# processed_data['Close'][i] = series_data['Close'][i]
# # setting the index again
# processed_data.index = processed_data.Date
# processed_data.drop('Date', axis=1, inplace=True)
# # creating train and test sets using all data in set
# myseriesdataset = processed_data.values
# to_train = myseriesdataset[0:255, :]
# to_valid = myseriesdataset[255:, :]
# # converting dataset into x_train and y_train
# scaler = MinMaxScaler(feature_range=(0, 1))
# scale_data = scaler.fit_transform(myseriesdataset)
# x_train, y_train = [], []
# length_of_totrain = len(to_train)
# for i in range(60, length_of_totrain):
# x_train.append(scale_data[i - 60:i, 0])
# y_train.append(scale_data[i, 0])
# x_train, y_train = np.array(x_train), np.array(y_train)
# x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
#
# # LSTM neural network
# lstm_model = Sequential()
# lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
# lstm_model.add(LSTM(units=50))
# lstm_model.add(Dense(1))
# lstm_model.compile(loss='mean_squared_error', optimizer='adadelta')
# lstm_model.fit(x_train, y_train, epochs=10, batch_size=1, verbose=2)
# # predicting next data stock price
# future_inputs = processed_data[len(processed_data) - (len(to_valid) + 1) - 60:].values
# future_inputs = future_inputs.reshape(-1, 1)
# future_inputs = scaler.transform(future_inputs)
# test_result = []
# for i in range(60, future_inputs.shape[0]):
# test_result.append(future_inputs[i - 60:i, 0])
# test_result = np.array(test_result)
# test_result = np.reshape(test_result,
# (test_result.shape[0], test_result.shape[1], 1))
# closing_price_result = lstm_model.predict(test_result)
# closing_price_result = scaler.inverse_transform(closing_price_result)
#
# return closing_price_result
def _dataPrediction(self, data_frame, to_pred):
x_axis = pd.DataFrame(data_frame.Date)
y_axis = pd.DataFrame(data_frame[to_pred])
forecast = x_axis[-1:]
lm = LinearRegression()
model = lm.fit(x_axis, y_axis)
prediction = lm.predict(forecast)
return prediction[0][0]
def linearRegression(self, data):
stock_info = data.copy()
stock_info.reset_index(inplace=True, drop=False)
stock_info["Date"] = stock_info["Date"].apply(lambda x: dt.datetime.strftime(x, '%y%m%d'))
open = self._dataPrediction(stock_info, "Open")
close = self._dataPrediction(stock_info, "Close")
high = self._dataPrediction(stock_info, "High")
low = self._dataPrediction(stock_info, "Low")
alltogether = [open, high, low, close]
return alltogether
|
f8aaa4edfb0fba58558f1a5d52f7cfc4076d57ca | zaincbs/PYTECH | /overlappingUsingForLoop.py | 606 | 4.21875 | 4 | #!/usr/bin/env python
"""
Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.
"""
def overlapping(l1,l2):
i = len(l1)-1
j = len(l2)-1
for x in range(i,-1,-1):
for y in range(j,-1,-1):
if l1[x] == l2[y]:
return True
return False
def main():
v=overlapping([1],[2,1,3])
print v
if __name__ == "__main__":
main()
|
da5fb9420b7f39929b0ab83d667ce02e4876ad4e | bjweiqm/Practice | /模块/re_demo.py | 417 | 3.765625 | 4 | #!/usr/bin/env python
# encoding:utf-8
"""
@software: PyCharm
@file: re_demo.py
@time: 2017/5/2 18:07
"""
import re
data = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
# 生成要匹配的正则对象
p = re.compile('\d+')
# 从头开始匹配
s = re.match('\d', data)
#
s = re.search('\d{3}', data)
if __name__ == '__main__':
if s:
print(s.group())
|
81d834dc83aa1502e586634c4fa0e84af582b247 | greenblues1190/Python-Algorithm | /LeetCode/12. 정렬/973-k-closest-points-to-origin.py | 656 | 3.5625 | 4 | # https://leetcode.com/problems/k-closest-points-to-origin/
# Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k,
# return the k closest points to the origin (0, 0).
# The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
# You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
from typing import List
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
points.sort(key=lambda x: x[0] ** 2 + x[1] ** 2)
return points[:k] |
6312d5bfbd34a8f4b26d1f9a5b2ec034a6f68479 | saltywalnut/CIT_SKP | /200627/branch.py | 150 | 3.71875 | 4 | Lamborghini = 200
money = 500
if (Lamborghini < money):
print ("I got a Lamborghini")
else :
print ("I can't afford it")
print ("FIN.")
|
94c3c36d4cc8564b78f975eec3852198c237de31 | ErickViz/Quiz09.py | /Problema3.py | 190 | 3.890625 | 4 | #Quiz09
#Problema3
def superpower(x,y):
c=0
a=1
while(c!=y):
a=x*a
c=c+1
return a
x=int(input("Dame un numero: "))
y=int(input("Dame su exponencial: "))
p=superpower(x,y)
print(p)
|
813014e3133428360132ec10acb9d7fa9a180367 | baconrider46/python-0 | /hi | 156 | 3.890625 | 4 | #!/usr/bin/env python3
import colors as c
print('Hi ' + c.blue + " what's your name" + c.reset)
name = input('>')
print("Hello " + c.blue + name)
|
9a73dfd2c11b671030edfc8167ae5bba218c9eb4 | AtteKarppinen/IrelandStudies | /Systems_Security/Lab 1/VigenereDecipher.py | 2,069 | 4.125 | 4 | # Vigenere Cipher
# Key: KISWAHILI
# Formula used in deciphering:
# Ti = Ci - Ki {mod m}
# Ti = plaintext character
# Ci = ciphertext character
# Ki = key character
# m = length of alphabet
import string
# Fetch alphabet from string library
alphabet = string.ascii_uppercase
def generate_key(ciphertext, key_word):
key = ""
# Key gets splitted so each individual letter can be processed more easily
key_splitted = list(key_word)
# list_value is needed to match key length to ciphertext's
list_value = 0
for symbol in ciphertext:
if symbol in alphabet:
key = key + key_splitted[list_value]
list_value += 1
if list_value >= len(key_word):
list_value = 0
else:
key = key + symbol
return key
def decipher_message(ciphertext, key):
plaintext = ""
# Key gets splitted so each individual letter can be processed more easily
key_splitted = list(key)
for index, symbol in enumerate(ciphertext):
if symbol in alphabet:
# Capital ASCII values range from 65 to 90
# +/-65 is required to count the deciphered letter's numerical value
# (Used formula is explained above the code)
letter_value = (ord(symbol) - 65) - (ord(key_splitted[index]) - 65)
if letter_value < 0:
letter_value += len(alphabet) + 65
plaintext_character = chr(letter_value)
else:
letter_value += 65
plaintext_character = chr(letter_value)
plaintext = plaintext + plaintext_character
else:
plaintext = plaintext + symbol
return plaintext
def main():
key_word = "KISWAHILI"
# Open text file and save it in string variable
with open("encodedVigenere.txt", "r") as input_file:
ciphertext = input_file.read()
key = generate_key(ciphertext, key_word)
print(decipher_message(ciphertext, key))
if __name__ == "__main__":
main() |
5e60ad7f07f63a0a3ab736e3df02aaf445d087a0 | ksrajiba/Testpygit | /trickdict5.py | 1,534 | 4.5625 | 5 | # new dict for iterating and dict comprehensions
# from typing import Tuple
a_dict = {'apple':'fruit','dog':'pets','car':'vehicle','twitter':'social network'}
# to know the methods whtever dictionary holds
print(dir(a_dict),end='--->')
# using for loop to access the keys
for key in a_dict:
print(key)
# simple trick to access keys and values --->with indexing oprator[]
for key in a_dict:
print(key,'---->' ,a_dict[key])
# iterating over .items() and it will return a tuple object
d_items = a_dict.items()
print(d_items) # here it will return view of items
# lets itreate
# items: Tuple[str, str]
for items in a_dict.items():
print(items)
# here we can know the view return by items() method
# its really a tuple object
for items in a_dict.items():
print(items)
print(type(items))
# once you know this then we will use tuple unpacking to iterate through keys and values
# lts take a look on tuple unpacking
for key,value in a_dict.items():
print(key, '--->', value)
# in this way we have more control in this dictionary
# here key will hold the keys and value will hold the values every time iteration
# iterating through .keys()
a_keys = a_dict.keys()
print(a_keys)
# lts iterate overs
for key in a_dict.keys():
print(key)
# iterating through .values()
d_value= a_dict.values()
print(d_value)
# iterate
for value in a_dict.values():
print(value)
# here we can also test member ships
print('----->*------>')
a = 'apple' in a_dict.values()
print(a)
f = 'fruit' in a_dict.values()
print(f)
|
5ca8ea5d09ad20f0588886bd937f4c8ee6be8788 | PacktPublishing/Modern-Python-Cookbook-Second-Edition | /Chapter_15/collector.py | 3,291 | 4.03125 | 4 | """Python Cookbook 2nd ed.
The Coupon Collector test for random arrival times.
"""
import random
from fractions import Fraction
from statistics import mean
from typing import Iterator, Iterable, Callable, cast
def arrival1(n: int = 8) -> Iterator[int]:
while True:
yield random.randrange(n)
test_arrival1 = """
>>> random.seed(1)
>>> for n, r in enumerate(arrival1()):
... if n == 8: break
... print(r)
2
1
4
1
7
7
7
6
"""
def arrival2(n: int = 8) -> Iterator[int]:
p = 0
while True:
step = random.choice([-1, 0, +1])
p += step
yield abs(p) % n
test_arrival2 = """
>>> random.seed(1)
>>> for n, r in enumerate(arrival2()):
... if n == 8: break
... print(r)
1
0
1
1
2
2
2
2
"""
def samples(limit: int, generator: Iterable[int]):
for n, value in enumerate(generator):
if n == limit:
break
yield value
test_samples = """
>>> random.seed(1)
>>> list(samples(10, arrival1()))
[2, 1, 4, 1, 7, 7, 7, 6, 3, 1]
>>> random.seed(1)
>>> for v in samples(8, arrival1()):
... print(v)
2
1
4
1
7
7
7
6
>>> random.seed(1)
>>> for v in samples(8, arrival2()):
... print(v)
1
0
1
1
2
2
2
2
"""
# Interesting quirk: sum() definition doesn't properly include Fraction
def expected(n: int = 8) -> Fraction:
return n * cast(Fraction, sum(Fraction(1, i + 1) for i in range(n)))
test_expected = """
>>> expected(6)
Fraction(147, 10)
>>> expected(8)
Fraction(761, 35)
>>> round(float(expected(8)), 1)
21.7
"""
def coupon_collector(n: int, data: Iterable[int]) -> Iterator[int]:
"""
>>> samples = [0, 1, 2, 3, 0, 0, 1, 1, 2, 2, 3, 3]
>>> list(coupon_collector(4, samples))
[4, 7]
"""
count, collection = 0, set()
for item in data:
count += 1
# collection = collection|{item}
collection.add(item)
if len(collection) == n:
yield count
count, collection = 0, set()
test_integration = """
>>> random.seed(42)
>>> size = 8
>>> data = samples(1_000, arrival1(8))
>>> wait_times = list(coupon_collector(8, data))
>>> round(mean(wait_times), 3)
21.933
"""
def summary(
n: int, limit: int, arrival_function: Callable[[int], Iterable[int]]
) -> None:
expected_time = float(expected(n))
data = samples(limit, arrival_function(n))
wait_times = list(coupon_collector(n, data))
average_time = mean(wait_times)
print(f"Coupon collection, n={n}")
print(f"Arrivals per {arrival_function.__name__!r}")
print(f"Expected = {expected_time:.2f}")
print(f"Actual {average_time:.2f}")
test_arrival1 = """
>>> random.seed(1)
>>> summary(8, 1000, arrival1)
Coupon collection, n=8
Arrivals per 'arrival1'
Expected = 21.74
Actual 20.81
"""
test_arrival2 = """
>>> random.seed(1)
>>> summary(8, 1000, arrival2)
Coupon collection, n=8
Arrivals per 'arrival2'
Expected = 21.74
Actual 39.68
"""
__test__ = {n: v for n, v in locals().items() if n.startswith("test_")}
if __name__ == "__main__":
random.seed(1)
summary(8, 1000, arrival1)
random.seed(1)
summary(8, 1000, arrival2)
|
bf09de6103d6341dd5244b6a6cc7b360bbd95553 | jiunwei/homework | /backend-01-tictactoe/tictactoe/game.py | 5,628 | 3.75 | 4 | # Zopim Take Home Exercise
# Jiun Wei Chia
# 2017-03-22
import sys
DEFAULT_MARKERS = ('X', 'O')
class TicTacToe:
"""
Represents state, logic and rendering for a Tic-Tac-Toe game.
:param n: immutable length for one side of Tic-Tac-Toe board
:param markers: 2-tuple of one-character strs that serve as markers for each player; used for rendering
"""
def __init__(self, n=3, markers=DEFAULT_MARKERS):
assert n > 0
self.n = n
self.digits = len(str(self.n * self.n))
self.markers = markers
self.board = [[None] * n for _ in range(n)]
def render_row(self, row):
""" Returns a str representation of the specified row of the board. """
assert row < self.n
start = row * self.n + 1
format_str = ' {:<' + str(self.digits) + '} '
row = self.board[row]
row = [
format_str.format(start + i if row[i] is None else self.markers[int(row[i])])
for i in range(self.n)
]
return '|'.join(row) + '\n'
def render_board(self):
""" Returns a str representation of the current board state. """
rows = [self.render_row(row) for row in range(self.n)]
divider = '-' * ((self.digits + 3) * self.n - 1) + '\n'
return divider.join(rows)
def make_move(self, player, index):
""" Places given player's marker on given box of the board. """
assert player < len(self.markers)
assert self.is_valid_move(index)
index -= 1
self.board[index // self.n][index % self.n] = player
def is_valid_move(self, index):
""" Returns whether placing a marker on given box is a valid move. """
if index < 1 or index > self.n * self.n:
return False
index -= 1
return self.board[index // self.n][index % self.n] is None
def is_stalemate(self):
""" Returns whether no valid moves are possible. """
def check(value):
return value is None
return not any(any(box is None for box in row) for row in self.board)
def get_winner(self):
""" Returns winner for current board state or None if there is no winner (yet). """
# Assume only one winner
for player in range(len(self.markers)):
def check(value):
return value == player
# Check diagonals
diagonal1 = [self.board[i][i] for i in range(self.n)]
diagonal2 = [self.board[i][self.n - i - 1] for i in range(self.n)]
if all(map(check, diagonal1)) or all(map(check, diagonal2)):
return player
for i in range(self.n):
# Check rows and columns
column = [self.board[row][i] for row in range(self.n)]
if all(map(check, self.board[i])) or all(map(check, column)):
return player
# Only reaches here if no matching lines were found, so no winner
return None
class Game:
"""
Represents an interactive tic-tac-toe game.
:param n: immutable length for one side of Tic-Tac-Toe board
:param markers: 2-tuple of one-character strs that serve as markers for each player
:param input_stream: BufferedIOBase object to receive input from; defaults to `sys.stdin`
:param output_stream: BufferedIOBase object for sending output; defaults to `sys.stdout`
"""
PROMPT = '>> '
def __init__(self, n=3, markers=DEFAULT_MARKERS, input_stream=sys.stdin, output_stream=sys.stdout):
self.ttt = TicTacToe(n, markers)
self.markers = markers
self.input = input_stream
self.output = output_stream
self.names = ['Player {}'.format(player + 1) for player in range(len(self.markers))]
self.current_player = 0
for player in range(len(self.markers)):
self.output.write('Enter name for {}:\n'.format(self.names[player]))
self.output.write(Game.PROMPT)
self.output.flush()
self.names[player] = self.input.readline().strip()
self.output.write('\n')
def run(self):
""" Runs game loop. """
self.current_player = 0
winner = None
while winner is None and not self.ttt.is_stalemate():
self.output.write(self.ttt.render_board())
self.output.write('\n')
message = '{}, choose a box to place an \'{}\' into:\n'.format(
self.names[self.current_player],
self.markers[self.current_player]
)
while True:
self.output.write(message)
self.output.write(Game.PROMPT)
self.output.flush()
move = self.input.readline().strip()
self.output.write('\n')
if move.isdigit() and self.ttt.is_valid_move(int(move)):
break
self.output.write('That is not a valid box.\n')
self.output.write('\n')
self.ttt.make_move(self.current_player, int(move))
self.current_player = (self.current_player + 1) % len(self.markers)
winner = self.ttt.get_winner()
self.output.write(self.ttt.render_board())
self.output.write('\n')
if winner is None:
self.output.write('It is a draw!\n')
else:
self.output.write('Congratulations {}! You have won.\n'.format(self.names[winner]))
def main(argv):
""" Main entry point. """
n = 3
if len(argv) > 0 and argv[0].isdigit():
n = int(argv[0])
Game(n=n).run()
|
e8fe7f4290d4439a57c02e06254f78f3bd9dba85 | ssaulrj/codes-python | /codeacademy-python3/strings/splitting_string_lastname.py | 476 | 4.09375 | 4 | authors = "Audre Lorde, William Carlos Williams, Gabriela Mistral, Jean Toomer, An Qi, Walt Whitman, Shel Silverstein, Carmen Boullosa, Kamala Suraiyya, Langston Hughes, Adrienne Rich, Nikki Giovanni"
author_names = authors.split(',')
def last_names(author_names):
listx = []
for i in author_names:
x = i.split()
listx.append(x[-1])
return listx
print(author_names)
#Create another list called author_last_names that only contains the last names of the poets in the provided string.
author_last_names = last_names(author_names)
print(author_last_names)
|
c316168ea5c67539b1f06efeeba80ac48d1d7fb4 | olaramoni/Zeller-s-Congruence | /Zeller_MonthInput.py | 565 | 4.40625 | 4 | def inputMonth()
monthValid = False
print(
"March=3, April=4, May=5, June=6, July=7, August=8, September=9, October=10, November=11, December=12, January=13, February=14")
while monthValid == False:
try:
month = input("Please enter the number corresponding to the month you want: ")
month = int(month)
if 2 < month < 15:
return month
else:
print("Please enter a number between 3 and 14")
except ValueError:
print("That was not a number") |
5f3a26cb949f722a82a8ca44fea0df82ea129a54 | imrahul22/placementProgram | /GCD&LCM.py | 837 | 3.8125 | 4 | #GCD & LCM of two number
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
i = 1
while(i <= num1 and i <= num2):
if(num1 % i == 0 and num2 % i == 0):
gcd = i
i = i + 1
print("GCD is", gcd)
lcm=(num1*num2)//gcd
print("LCM is",lcm)
#GCD of more than two no in a array
def findgcd(x, y):
while (y): #means{while(y!=0)}
x, y = y, x % y
return x
l = [22, 44, 66, 88, 99]
num1 = l[0]
num2 = l[1]
gcd = findgcd(num1, num2)
for i in range(2, len(l)):
gcd = findgcd(gcd, l[i])
print("gcd is: ", gcd)
#prog2
def findgcd(x, y):
if y == 0:
return x
else:
return findgcd(y, x % y)
l = [22, 44, 66, 88, 99]
num1 = l[0]
num2 = l[1]
gcd = findgcd(num1, num2)
for i in range(2, len(l)):
gcd = findgcd(gcd, l[i])
print("gcd is: ", gcd) |
a5490acef5ca106d6f41e57dc143196e9f2178d1 | ethanchu15/Deepcoder-SyGuS-Solver | /network.py | 3,136 | 4.09375 | 4 | '''
Code adapted from http://pytorch.org/tutorials/beginner/pytorch_with_examples.html
'''
import torch
from initializer import *
from torch.autograd import Variable
def normalize(y_pred):
# copied from https://discuss.pytorch.org/t/normalize-a-vector-to-0-1/14594
min_v = torch.min(y_pred)
range_v = torch.max(y_pred) - min_v
if range_v.data[0] > 0:
return (y_pred - min_v) / range_v.data[0]
else:
return torch.zeros(y_pred.size())
dtype = torch.FloatTensor
# dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 10, 30, 20, 11
# Create random Tensors to hold input and outputs, and wrap them in Variables.
# Setting requires_grad=False indicates that we do not need to compute gradients
# with respect to these Variables during the backward pass.
(x_python_list, y_python_list) = set_up_problem()
x = Variable(torch.FloatTensor(x_python_list), requires_grad=False)
y = Variable(torch.FloatTensor(y_python_list), requires_grad=False)
# Create random Tensors for weights, and wrap them in Variables.
# Setting requires_grad=True indicates that we want to compute gradients with
# respect to these Variables during the backward pass.
w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True)
w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True)
loss_fn = torch.nn.L1Loss()
learning_rate = 1e-6
for t in range(1000):
# Forward pass: compute predicted y using operations on Variables; these
# are exactly the same operations we used to compute the forward pass using
# Tensors, but we do not need to keep references to intermediate values since
# we are not implementing the backward pass by hand.
y_pred = x.mm(w1).clamp(min=0).mm(w2)
# Compute and print loss using operations on Variables.
# Now loss is a Variable of shape (1,) and loss.data is a Tensor of shape
# (1,); loss.data[0] is a scalar value holding the loss.
loss = (y_pred - y).pow(2).sum()
print(t, loss.data[0])
# Use autograd to compute the backward pass. This call will compute the
# gradient of loss with respect to all Variables with requires_grad=True.
# After this call w1.grad and w2.grad will be Variables holding the gradient
# of the loss with respect to w1 and w2 respectively.
loss.backward()
# Update weights using gradient descent; w1.data and w2.data are Tensors,
# w1.grad and w2.grad are Variables and w1.grad.data and w2.grad.data are
# Tensors.
w1.data -= learning_rate * w1.grad.data
w2.data -= learning_rate * w2.grad.data
# Manually zero the gradients after updating weights
w1.grad.data.zero_()
w2.grad.data.zero_()
(x_test, y_test) = set_up_test_case()
x = Variable(torch.FloatTensor(x_test), requires_grad=False)
y = Variable(torch.FloatTensor(y_test), requires_grad=False)
y_pred = normalize(x.mm(w1).clamp(min=0).mm(w2))
loss = (y_pred - y).pow(2).sum()
print("LOSS", loss.data[0])
print("PREDICTION")
print(y_pred[0])
print("ACTUAL")
print(y[0])
|
e95310601c68abf51195af94018f3a9673bce217 | likunhong01/PythonDesignPatterns | /复合模式/MVC模式/no01实现.py | 1,412 | 3.5 | 4 | # coding=utf-8
# Version:python3.7.0
# Tools:Pycharm 2019
# Author:LIKUNHONG
__date__ = ''
__author__ = 'lkh'
# 模型-视图-控制器模式
class Model:
services = {
'email':
{
'number': 1000,
'price': 2,
},
'sms':
{
'number': 1000,
'price': 10,
},
'voice':
{
'number': 1000,
'price': 15,
}
}
class View:
def list_services(self, services):
for svc in services:
print(svc, ' ')
def list_pricing(self, services):
for svc in services:
print(Model.services[svc]['number'],
'条',
svc,
'消息你应该支付',
Model.services[svc]['price'],
'元')
class Controller:
def __init__(self):
self.model = Model()
self.view = View()
def get_services(self):
services = self.model.services.keys()
return self.view.list_services(services)
def get_pricing(self):
services = self.model.services.keys()
return self.view.list_pricing(services)
def Client():
controller = Controller()
print('我们提供:')
controller.get_services()
print('他们的价格是:')
controller.get_pricing()
Client()
|
826de7aa45546b8fede372722f2d556072b486aa | haruming/python-exercises | /tensorflow_mnist_nn.py | 3,096 | 3.890625 | 4 | import tensorflow as tf
import numpy as np
# use the MNIST data set in tensorflow
from tensorflow.examples.tutorials.mnist import input_data
data_path = os.path.join('.', 'mnist_data')
# one-hot representation, here we use number 0-9 which means 10 entrances
mnist = input_data.read_data_sets(data_path, one_hot=True)
input_layer = 28 * 28 # input layer
hidden_layer_1 = 500 # hidden layer 1
hidden_layer_2 = 1000 # hidden layer 2
hidden_layer_3 = 300 # hideen layer 3
output_layer = 10 # output layer
# normally, linear --> 1 non-linear --> 2 super non-liear --> 3+
def neural_network(data):
# define the weights and biases of the first second third layers
layer_1_w_b = {'w_':tf.Variable(tf.random_normal([input_layer, hidden_layer_1])), 'b_':tf.Variable(tf.random_normal(hidden_layer_1))}
layer_2_w_b = {'w_':tf.Variable(tf.random_normal([hidden_layer_1, hidden_layer_2])), 'b_':tf.Variable(tf.random_normal(hidden_layer_2))}
layer_3_w_b = {'w_':tf.Variable(tf.random_normal([hidden_layer_2, hidden_layer_3])), 'b_':tf.Variable(tf.random_normal(hidden_layer_3))}
# define the weights and biases between the third and output layer
layer_output_w_b = {'w_':tf.Variable(tf.random_normal([hidden_layer_3, output_layer])), 'b_':tf.Variable(tf.random_normal(output_layer))}
# before neuron value = weight * input + bias
layer_1 = tf.add(tf.matmul(data, layer_1_w_b['w_']), layer_1_w_b['_b'])
# after neuron value, activation function, here we use ReLU
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, layer_2_w_b['w_']), layer_2_w_b['_b'])
layer_2 = tf.nn.relu(layer_2)
layer_3 = tf.add(tf.matmul(layer_2, layer_3_w_b['w_']), layer_3_w_b['_b'])
layer_3 = tf.nn.relu(layer_3)
# no need to activate the last layer
layer_output = tf.add(tf.matmul(layer_3, layer_output_w_b['w_']), layer_output_w_b['_b'])
return layer_output
# we use 100 records as a batch for each epoch
batch_size = 100
# the second parameter is the matrix size for two sizes
X = tf.placeholder('float', [None, 28*28]) # input
Y = tf.placeholder('float') # output
# use data to train the neural network
def train_neural_network(X, Y):
# get the predict value of after neural network
predict = neural_network(X)
# calculate the loss function with softmax and cross entropy
loss_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(predict, Y))
optimizer = tf.train.AdamOptimizer().minimize(loss_function) # learning rate = 0.001
# define the epochs
epochs = 13
with tf.Session() as session:
session.run(tf.initialize_all_variables())
epoch_loss = 0
for epoch in range(epochs):
for i in range(int(mnist.train.num_examples/batch_size)):
x, y = mnist.train.next_batch(batch_size)
_, c = session.run([optimizer, loss_function], feed_dict={X:x, Y:y})
epoch_loss += c
print(epoch, ' : ', epoch_loss)
correct = tf.equal(tf.argmax(predict, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('accuracy: ', accuracy.eval({X:mnist.test.images, Y:mnist.test.labels}))
train_neural_network(X,Y) |
e667268a98557ab678d3f5db6085d767e1800725 | anshulmttl/FaceDetctionUsingPythonAI | /FaceDetector.py | 2,042 | 3.703125 | 4 | import cv2
print ("FaceDetector.py")
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#Choose an image to detect the faces in.
# input image using openCV and not normal image read
#img = cv2.imread('RDJ.jpg')
webcam = cv2.VideoCapture(0) #0 => Goes to webcam
#iterate forever over frames
while True:
successful_frame_read,frame = webcam.read()
#Must convert to grayscale
grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#plugin face detection in video
face_coordinates = trained_face_data.detectMultiScale(grayscaled_frame)
#draw rectangles around faces
for(x,y,w,h) in face_coordinates:
cv2.rectangle(frame, (x,y), (x+w,y+h), (0, 255, 0), 2)
cv2.imshow("Grayscaled frame", frame)
key = cv2.waitKey(1)
if key == 81 or key == 113:
break;
webcam.release()
# How the algorithm is working
# Haar cascade - haar is person who invented algorithm. It goes down the funnel and
# keeps cascading. Chain of machine learning things that passes through
# HAAR features - Edge features, Line features, Four rectangle feaatures
#
#
#
#
#
#
#key = cv2.waitKey(1)
#Show the image
#cv2.imshow('Face detector', img)
#wait for key press before closing image.
#cv2.waitKey()
#Convert to grayscale because haar cascade algorithm only takes gray scale images
#grayscaled_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#plug the grayscale image to the trained algorithm
#face_coordinates = trained_face_data.detectMultiScale(grayscaled_img)
#print the face coordinates upper left, bottom down, bottom right, top right
#print(face_coordinates)
#(x,y,w,h) = face_coordinates[0]
#draw the green box around the face.
#draw the rectangle using a module in OpenCV
#cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
#cv2.imshow('Image with rectangle', img)
#cv2.waitKey()
#Detecting faces in a video
#Run the classifier code into every single frame of video
|
8faf9e0c0c995955cdf331e4b39b63fa516ab93a | daniel-reich/turbo-robot | /BHBXNfeMsA43d8Tys_2.py | 1,508 | 4.09375 | 4 | """
As far as we currently know, approximations for the mathematical constant
**pi** (π) in the history of mathematics started surfacing with Ancient
Babylonians, who found its correct truncation up to 1 decimal place. During
the 5th century, the Chinese mathematician Zu Chongzhi raised it to 7 decimal
places and from the 18th century onwards the number of correct pi decimal
places has seen steady growth.
Since the middle of the 20th century, the approximation of pi has been the
task of electronic digital computers. During the 2019 Pi Day on the 14th of
March, the Japanese computer scientist _Emma Haruka Iwao_ released the
currently most accurate value of pi with more than 31.4 trillion digits, using
170 Terabytes of data.
Your task is to create a function that takes a positive integer `n` as an
argument and returns the value of **pi** with its first `n` decimal digits.
Taylor series are usually used to get finer approximations. To make this
challenge approachable to anyone, the following formula is suggested:

### Examples
pi(1) ➞ "3.1"
pi(2) ➞ "3.14"
pi(30) ➞ "3.141592653589793238462643383279"
### Notes
N/A
"""
def pi(n):
def atand(d,n):
t=m=(10**n)//d
i=0
while m!=0:
i+=1
m//=-d*d
t+=m//(2*i+1)
return t
d=n+5
p=4*(4*atand(5,d)-atand(239,d))
s=str(p)[:n+1]
return s[0]+'.'+s[1:]
|
6963ad1538d038d446d85c9fa59ece1a2b73193d | adirz/sample-projects | /samle projects/school projects/intro to CS/ex8/sllist_utils.py | 10,724 | 4.25 | 4 | from sllist import List, Node
def merge_lists(first_list, second_list):
"""
Merges two sorted (in ascending order) lists into one new sorted list in
an ascending order. The resulting new list is created using new nodes
(copies of the nodes of the given lists). Assumes both lists are sorted in
ascending order. The original lists should not be modified.
"""
first_l_node = first_list.head
second_l_node = second_list.head
new_list = List()
while first_l_node != None or second_l_node != None:
if first_l_node == None:
new_list.add_first(second_l_node.get_data())
second_l_node = second_l_node.get_next()
elif second_l_node == None:
new_list.add_first(first_l_node.get_data())
first_l_node = first_l_node.get_next()
elif first_l_node.get_data() < second_l_node.get_data():
new_list.add_first(first_l_node.get_data())
first_l_node = first_l_node.get_next()
else:
new_list.add_first(second_l_node.get_data())
second_l_node = second_l_node.get_next()
reverse(new_list)
return new_list
def contains_cycle(sll):
"""
Checks if the given list contains a cycle.
A list contains a cycle if at some point a Node in the list points to
a Node that already appeared in the list. Note that the cycle does not
necessarily contain all the nodes in the list. The original list should
not be modified.
Returns true iff the list contains a cycle
"""
## I used my variation on Floyd's method of cycle detection
first_node = sll.head
if first_node == None:
return False
second_node = first_node.get_next()
if second_node == None:
return False
while first_node != second_node:
first_node = first_node.get_next()
second_node = second_node.get_next()
if second_node == None:
return False
else:
if first_node == second_node:
return True
second_node = second_node.get_next()
if second_node == None:
return False
return True
def reverse(sll):
"""
Reverses the given list (so the head becomes the last element, and every
element points to the element that was previously before it). Runs in O(n).
No new object is created.
"""
current_node = sll.head
if not current_node:
return None
last_node = current_node
current_node = current_node.get_next()
sll.head = last_node
sll.head.set_next(None)
while current_node:
last_node = current_node
current_node = current_node.get_next()
last_node.set_next(sll.head)
sll.head = last_node
def is_palindrome(sll):
"""
Checks if the given list is a palindrome. A list is a palindrome if
for j=0...n/2 (where n is the number of elements in the list) the
element in location j equals to the element in location n-j.
Note that you should compare the data stored in the nodes and
not the node objects themselves. The original list should not be modified.
Returns true iff the list is a palindrome
"""
## I'm not deleting it- I like it better than using O(1) space
##
## liset_length = 0
## compare_list = List()
## curr_node1 = sll.head
## while curr_node1:
## liset_length += 1
## compare_list.add_first(curr_node1.get_data())
## curr_node1=curr_node1.get_next()
## curr_node1 = sll.head
## curr_node2 = compare_list.head
## for node_num in range(liset_length//2):
## if curr_node1.get_data() != curr_node2.get_data():
## return False
## curr_node1=curr_node1.get_next()
## curr_node2=curr_node2.get_next()
## return True
list_length = 0
front_node = sll.head
if front_node == None:
return True
back_node = sll.head
while back_node.get_next() != None:
back_node = back_node.get_next()
list_length += 1
if back_node.get_data()[0] != front_node.get_data()[0]:
return False
for node_run in range(1,list_length//2+1):
back_node = front_node.get_next()
front_node = front_node.get_next()
for node_back_run in range(list_length - 2*node_run):
back_node = back_node.get_next()
if front_node.get_data()[0] != back_node.get_data()[0]:
return False
return True
def have_intersection(first_list, second_list):
"""
Checks if the two given lists intersect.
Two lists intersect if at some point they start to share nodes.
Once two lists intersect they become one list from that point on and
can no longer split apart. Assumes that both lists does not contain cycles.
Note that two lists might intersect even if their lengths are not equal.
No new object is created, and niether list is modified.
Returns true iff the lists intersect.
"""
## because they don't have cycles I can know that if they intersect they
##both reach the same point at their end
node_after = first_list.head
if not node_after:
return False
node_front = first_list.head.get_next()
while node_front:
node_front = node_front.get_next()
node_after = node_after.get_next()
node_front = second_list.head
while node_front:
if node_front == node_after:
return True
node_front = node_front.get_next()
return False
def get_item(sll, k):
"""
Returns the k'th element from of the list.
If k > list_size returns None, if k<0 returns the k element from the end.
"""
modified = False
if k<0:
reverse(sll)
k = -k -1
modified = True
node = sll.head
for node_num in range(k):
if not node:
break
node = node.get_next()
if modified:
reverse(sll)
if node != None:
return node.get_data()
return None
def next_by(node, howmuch):
'''
return the node which is "howmuch" times next
'''
next_node = node
for step in range(howmuch):
if next_node == None:
break
next_node = next_node.get_next()
return next_node
def slice(sll, start, stop = None, step = 1):
""" Returns a new list after slicing the given list from start to stop
with a step.
Imitates the behavior of slicing regular sequences in python.
"""
return List()
till_end = (stop == None)
def cut(sll, sliced_list, start, step, till_end):
head_node = next_by(sll.head,start-2)
node = head_node.get_next()
sliced_list.head = node
for stepping in range((stop-start)//step):
node.set_next(next_by(node, step))
node = node.get_next()
head_node.set_next(node.get_next())
node.set_next(None)
def cut_2(sll, sliced_list, start, step, till_end):
head_node = next_by(sll.head,start-2)
node = head_node.get_next()
sliced_list.head = node
while node != None:
node.set_next(next_by(node, step))
node = node.get_next()
head_node.set_next(node.get_next())
node.set_next(None)
sliced_list = List()
rev = False
if start >= 0:
if step > 0:
if stop != None:
if stop >= start:
cut(sll, sliced_list, start, step, till_end)
else:
return List()
else:
cut_2(sll, sliced_list, start, step, till_end)
else:
rev = True
reverse(sll)
step = -step
if stop != None:
if stop <= start:
cut(sll, sliced_list, -start, step, till_end)
else:
return List()
else:
cut_2(sll, sliced_list, start, step, till_end)
else:
rev = True
reverse(sll)
step = -step
def merge_sort(sll):
"""
Sorts the given list using the merge-sort algorithm.
Resulting list should be sorted in ascending order. Resulting list should
contain the same node objects it did originally, and should be stable,
i.e., nodes with equal data should be in the same order they were in in the
original list. You may create a constant number of new to help sorting.
"""
def merge(prev_node, head_node_1, head_node_2, last):
node = None
node_1 = head_node_1
node_2 = head_node_2
if node_2 != None:
if head_node_1.get_data() <= head_node_2.get_data():
node = node_1
node_1 = node_1.get_next()
else:
node = node_2
node_2 = node_2.get_next()
if prev_node == None:
sll.head = node
else:
prev_node.set_next(node)
while not (node_1 == head_node_2 and node_2 == last):
if node_1 == head_node_2:
node.set_next(node_2)
node = node.get_next()
node_2 = node_2.get_next()
elif node_2 == last:
node.set_next(node_1)
node = node.get_next()
node_1 = node_1.get_next()
elif node_1.get_data() <= node_2.get_data():
node.set_next(node_1)
node = node.get_next()
node_1 = node_1.get_next()
else:
node.set_next(node_2)
node = node.get_next()
node_2 = node_2.get_next()
prev_node = node
node.set_next(last)
return prev_node
length = 0
node = sll.head
while node != None:
length += 1
node = node.get_next()
node_num = 1
while node_num in range(length):
prev_node = None
node_1 = sll.head
node_2 = next_by(node_1, node_num)
node_2_last = next_by(node_2, node_num)
prev_node = merge(prev_node, node_1, node_2, node_2_last)
node_1 = node_2_last
node_2 = next_by(node_1, node_num)
node_2_last = next_by(node_2, node_num)
stop = False
while node_2 != None:
prev_node = merge(prev_node, node_1, node_2, node_2_last)
if stop:
break
if node_2_last == None:
stop = True
node_1 = node_2_last
node_2 = next_by(node_1, node_num)
node_2_last = next_by(node_2, node_num)
node_num = node_num*2
|
59393fd8565d54335034d4c35ff3fee3da49ffbb | Adjeju/Laboratorni-Python | /Laboratorna7/lab7_3.py | 290 | 3.625 | 4 | import random
row = int(input('row= '))
cols = int(input('cols= '))
num = int(input('number= '))
a = []
for i in range(row):
row = []
for j in range(cols):
elem = random.randint(1,9)
row.append(elem * num)
a.append(row)
for i in range(len(a)):
print(a[i]) |
49447dc605d8297a9fc137c76beba9f1434cb675 | nshahm/learning | /python/listopr.py | 1,122 | 3.6875 | 4 | listt = [1,2,3,4,5,6,7,8,9,0]
l = listt * 2;
print (l) # concantenate two times
print (l[-2]) # Index from reverse
tuplee = (1, 's')
listFromTuple = list(tuplee);
print (listFromTuple)
print (len(listt))
print (max(listt))
print (min(listt))
del listt[2];
print (listt)
# Compare lists
def cmp(a, b): # Not in python3 so defining one
return (a > b) - (a < b)
list1, list2 = [123, 'xyz'], [456, 'abc']
print (cmp(list1, list2))
print (cmp(list2, list1))
list3 = list2 + [786];
print (cmp(list2, list3))
list.append(obj)
# List related methods available
# Appends object obj to list
# 2
# list.count(obj)
# Returns count of how many times obj occurs in list
# 3
# list.extend(seq)
# Appends the contents of seq to list
# 4
# list.index(obj)
# Returns the lowest index in list that obj appears
# 5
# list.insert(index, obj)
# Inserts object obj into list at offset index
# 6
# list.pop(obj=list[-1])
# Removes and returns last object or obj from list
# 7
# list.remove(obj)
# Removes object obj from list
# 8
# list.reverse()
# Reverses objects of list in place
# 9
# list.sort([func])
|
c37866834aaf8ad7dac284c2939bd310b7c13193 | Keftcha/codingame | /training/hard/the-greatest-number/python3.py | 524 | 3.515625 | 4 | n = int(input())
nb = input().split()
digits = [d for d in nb if d.isdigit()]
# make the number
if all([d == "0" for d in digits]): # only 0
digits = ["0"]
elif "-" in nb: # negative number
digits.sort()
if "." in nb:
digits.insert(1, ".")
digits.insert(0, "-")
else: # psitive number
digits.sort(reverse=True)
if "." in nb:
# remove useless 0
if digits[-1] == "0":
del digits[-1]
else:
digits.insert(-1, ".")
print("".join(digits))
|
ba703ddd37af2d62d7e94fc2d33502a24a02e80d | jyssh/codility | /rotate.py | 901 | 3.671875 | 4 | ## List Number -> List
## Given a list and an integer n, produce a list by rotating the given list n times
def rotate(l, k):
if not l or k == 0:
return l
r = k % len(l)
return l[-r:] + l[0:-r]
if __name__ == '__main__':
# n=k
## n=k=0
assert rotate([], 0) == []
## n=k>0
assert rotate([1, 2, 3, 4], 4) == [1, 2, 3, 4]
# n<k
## n=0, k>0
assert rotate([], 5) == []
## n>0, k>0
assert rotate([-5, -4, -3, -2, -1, 0], 8) == [-1, 0, -5, -4, -3, -2]
## failed test iterations for k>=n => n<=k: got [1, 1, 2, 3, 5] expected [3, 5, 1, 1, 2]
## try a k>n*2
assert rotate([3, 5, 1, 1, 2], 14) == [5, 1, 1, 2, 3]
# n>k
## n>0, k=0
assert rotate([1, 2, 3], 0) == [1, 2, 3]
# n>0, k>0
assert rotate([3, 8, 9, 7, 6], 3) == [9, 7, 6, 3, 8]
# same elements in n
assert rotate([0, 0, 0], 4) == [0, 0, 0]
|
5d749deda4852cb4483d559df6d53b05c8f6f835 | hoque-nazmul/python-cheat-sheet | /Program/loop-exception.py | 737 | 4.40625 | 4 | # When the loop iteration is completed, then the 'StopIteration Exception' & 'else' execute.
for item in range(1,4):
print(item)
else:
print('Item Finished!')
# Output: 1 2 3
# Item Finished!
# If the loop iteration isn't completed, 'StopIteration Exception' & 'else' won't execute.
for i in range(1, 5):
if i > 3:
break
print(i)
else:
print('Iteration Complete!')
# Output: 1 2 3
# Implementing Loop Exception logic, We can create efficient program. Such as:
def check_prime(num):
for i in range(2, num):
if num % i == 0:
print(False)
break
else:
print(True)
# print(check_prime(17)) # True
# print(check_prime(13)) # True
# print(check_prime(10)) # False
|
096499b900a9a3c86fae63cc6fda5c91b3840f92 | stden/geometry | /coord.py | 3,667 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# Операции в однородных координатах
from fractions import *
print(gcd(10, 5))
class Point: # Класс "Точка" (вектор) с однородными координатами
x, y, w = 0, 0, 1
# Конструктор
def __init__(self, x=0, y=0):
self.x, self.y, self.w = x, y, 1
# Строка для вывода
def __repr__(x):
return "(" + str(x.x / float(x.w)) + \
"," + str(x.y / float(x.w)) + ")"
# Сложение векторов
def __add__(A, B):
R = Point()
R.w = B.w * A.w
R.x = A.x * B.w + B.x * A.w
R.y = A.y * B.w + B.y * A.w
# Если вычисление идёт в целых числах,
# то можно дроби сократить на НОД
# Сокращаем дроби чтобы работать с целыми числами в меньшем диапазоне
# Проверяем что числа целые.
# Если изначально даны координаты в целых числах, то они и будут оставаться
# целыми до момента вывода или до операции с результатом
# в действительных числах, например, извлечения корня
if (type(R.x) is int) and (type(R.y) is int) and (type(R.w) is int):
common_gcd = gcd(gcd(R.x, R.y), R.w) # Общий НОД
R.x /= common_gcd # Делим x на НОД
R.y /= common_gcd # Делим y на НОД
R.w /= common_gcd # Делим Вес на НОД
return R
# Вычитание векторов
def __sub__(A, B):
res = Point()
res.w = B.w * A.w
res.x = A.x * B.w - B.x * A.w
res.y = A.y * B.w - B.y * A.w
return res
# Разделить вектор на число (масштабирование)
def __div__(A, x):
res = Point()
res.x = A.x
res.y = A.y
res.w = A.w * x
return res
# Заведём 2 точки
A = Point(2, 10)
print(A)
B = Point(3, 5)
print(B)
AB = B - A
print(AB)
AB2 = AB / 3
print(AB2.x, AB2.y, AB2.w)
v = Point(3, 2)
AB2 = AB2 - v
print(AB2.x, AB2.y, AB2.w)
print(AB2)
# Скалярное произведение в однородных координатах
def scalar(A, B):
# A.x * B.x + A.y * B.y
return (A.x * B.x + A.y * B.y) / float(A.w * B.w)
v1 = Point(5, 5)
v2 = Point(-5, 5)
print("Скалярное произведение: %d" % scalar(v1, v2))
def solve(a1, b1, c1,
a2, b2, c2):
"""
Общение решение системы линейных уравнений по методу Крамера
Для получения решения в однородных координатах
"""
d = a1 * b2 - b1 * a2
x = c1 * b2 - b1 * c2
y = a1 * c2 - c1 * a2
if d == 0:
if x == 0 and y == 0:
return "Любое решение"
else:
return "Нет решений"
assert a1 * x + b1 * y == c1 * d
assert a2 * x + b2 * y == c2 * d
return x, y, d
class Line: # Класс "Прямая" (тоже в однородных коодинатах)
a, b, c = 0, 0, 0
def __init__(x, a, b, c):
x.a, x.b, x.c = a, b, c
l1 = Line(1, 0, 0)
l2 = Line(a=0, b=1, c=-1)
print(solve(l1.a, l1.b, l1.c,
l2.a, l2.b, l2.c))
x, y, w = 2, 3, 3
print(x, y, w)
x, y = x / float(w), y / float(w)
print(x, y)
|
1d5b226a199ead8df4ff78f1a4db313916480521 | nmmarzano/daily-coding-problem | /2020-01-22/in_place_list_reversal.py | 1,216 | 3.75 | 4 | class Node:
def __init__(self, val='', child=None):
self.val = val
self.child = child
def get_child(self):
return self.child
def set_child(self, node):
self.child = node
def __repr__(self):
return f'{{val: {self.val}, child:{type(self.child)}}}'
def reverse_list(ll):
cur = ll
nxt = cur.get_child()
aux = nxt.get_child() if nxt is not None else None
cur.set_child(None)
while True:
if nxt is not None:
nxt.set_child(cur)
else:
break
cur = nxt
nxt = aux
if nxt is not None:
aux = nxt.get_child()
return cur
def print_list(ll):
cur = ll
while cur is not None:
print(cur)
cur = cur.get_child()
def create_list(length):
head = Node(1)
cur = head
for i in range(2, length + 1):
aux = Node(i)
cur.set_child(aux)
cur = aux
return head
if __name__ == '__main__':
length = int(input('Enter length of list: ').strip())
ll = create_list(length)
print('\nList: ')
print_list(ll)
print('\nReversed: ')
ll = reverse_list(ll)
print_list(ll)
|
4c4a2eab409f3a3c677a6aec239ae0bf3cee1f0f | reneenie/python_for_evy | /m2w6.py | 2,011 | 4.25 | 4 | # Tuple data structure
# 1. immutable: cannot be modified
# things not to do with tuple
######### will return traceback!!!
# tuple.sort()
# tuple.append()
# tuple.reverse()
# assign values to tuple
(x,y) = ('Amy', 4)
print((x,y))
# compare tuple
# compare the first one first.
# if the first ones are equal, goes to the second one and so on
print((0,1,2) < (5,0,1))
print((0,0,1) < (0,2,1))
print(('B','a','A') < ('a','a','A')) # uppercase always < lowercase, and posterior letters > prior letters
### key difference between tuples and lists
# it doesn't have to build these structures to be changeable,
# and so they're just more efficient and more performant than lists.
# for Lists, you have to actually allocate extra memory and stuff like that to let them be changed
# quiz
# x , y = 3, 4
# print('y:',y)
# sorting dictionary using key order
# ! keys in dictionary have to be unique
# ! dictionary doesn't record order
a = dict()
a['Amy']=1
a['Eason']=2
a['Bob']=1
print(a)
# 1. sort tuples by key orders
a_sortbyKey = sorted(a.items())
for k, v in a_sortbyKey:
print('sort tuples by key orders',k,v)
# 2. sort tuples by value orders
tmp = []
for k,v in sorted(a.items()):
tmp.append((v,k))
a_sortbyValue = sorted(tmp,reverse=True)
for v,k in a_sortbyValue:
print('sort tuples by value orders',k,v)
########## List comprehension
# format: [ expression for item in list if conditional ]
# equivalent to
# for item in list:
# if conditional:
# expression
print(sorted([(v,k) for k,v in a.items()],reverse = True))
########## Assignment ###############
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hour_dict = dict()
for line in handle:
parts = line.split()
if line.startswith('From') == False or len(parts) < 6:
continue
timestamp = parts[5]
print(timestamp)
time = timestamp.split(':')
hour_dict[time[0]] = hour_dict.get(time[0],0)+1
for k,v in sorted(hour_dict.items()):
print(k,v)
|
00f8be711cd8a2a4a5d1014999cc080625e21992 | jameszhan/notes-ml | /06-programing-languages/01-pythons/03-just-for-fun/02-algorithms/20_dijkstra.py | 1,697 | 3.65625 | 4 | # -*- coding: utf8 -*-
"""
def dijkstra():
OPEN = []
CLOSE = []
CLOSE.append((0, 0))
for i in range(len(m[0])):
if m[0][i] < N:
OPEN.append((m[0][i], i))
while True:
curr, index = min(OPEN)
CLOSE.append((curr, index))
for i in range(index, len(m[index])):
if m[index][i] < N:
OPEN.append((m[index][i], i))
break
return CLOSE
print(dijkstra())
"""
import sys
"""
B
/ | \
8 9 29
/ | \
A--16----C---15------F
\ /
\ /
7 18
\ /
D---10---E
struct [权值, 节点编号]
"""
N = 65536
M = [
[N, 8, 16, 7, N, N],
[N, N, 9, N, N, 29],
[N, N, N, N, N, 15],
[N, N, N, N, 10, N],
[N, N, N, N, N, 18],
[N, N, N, N, N, N],
]
def to_s(v):
if v >= 65536:
return 'N'
else:
return str(v)
def show(mat):
m = len(mat)
for i in range(m):
n = len(mat[i])
for j in range(n):
sys.stdout.write(to_s(mat[i][j]) + '\t')
sys.stdout.write('\n')
def dijkstra(mat):
o = []
c = []
for i in range(len(mat[0])):
if mat[0][i] < N:
o.append((mat[0][i], i))
c.append((0, 0))
while len(o) != 0:
w, id = o.pop(0)
for i in range(len(mat[id])):
if mat[id][i] < N:
o.append((mat[id][i] + w, i))
if max(c)[0] <= w:
c.append((w, id))
else:
c.append((w, id))
if id == len(mat[0]) - 1:
break
return c
show(M)
print('Path => {0}'.format(dijkstra(M)))
|
9de76437629d0b7b35c037681f16d71904919a4b | MOHAMMAD-FATHA/Python_Programs | /Data Structures/Dictionary/UniqueValueDic.py | 459 | 3.765625 | 4 | """
* @Author: Mohammad Fatha
* @Date: 2021-09-24 15:50
* @Last Modified by: Mohammad Fatha
* @Last Modified time: 2021-09-15 01:52
* @Title: :Python program to print all unique values in a dictionary
"""
L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
print(type(L))
print("Original List: ",L)
uni_value = set( val for a in L for val in a.values())
print(type(uni_value))
print("Unique Values: ",uni_value)
|
afde6e73d28bffffad3ed33cf51f73da3aa57284 | Shakirsadiq6/Basic-Python-Programs | /Basics_upto_loops/More examples/palindrome.py | 388 | 3.796875 | 4 | '''Print palindrome numbers upto 1 million'''
__author__ = "Shakir Sadiq"
MAXIMUM = 1000000
print("Palindrome Numbers upto 1 million")
for num in range(1, MAXIMUM + 1):
temp = num
reverse = 0
while(temp > 0):
reminder = temp % 10
reverse = (reverse * 10) + reminder
temp = temp //10
if(num == reverse):
print(num, end ="")
print()
|
523586d535d2908bcf5038f9c802f3e926bd9cce | MTGTsunami/LeetPython | /src/leetcode/tree/199. Binary Tree Right Side View.py | 1,055 | 4.1875 | 4 | """
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class MySolution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []
queue = deque([(root, 0)])
res, prev = [], (None, 0)
while queue:
node, val = queue.popleft()
if prev[1] != val:
res.append(prev[0].val)
if node.left:
queue.append((node.left, val + 1))
if node.right:
queue.append((node.right, val + 1))
prev = (node, val)
res.append(node.val)
return res
|
7f1fccaa8ef9ed927a3382be87a4f105224b07d4 | yubit/python_ders1 | /8-hesap_makinesi.py | 685 | 4.0625 | 4 | sayi1 = int(input("Lütfen 1.sayıyı girin : "))
sayi2 = int(input("Lütfen 2 sayıyı girin : "))
print('Toplam: {} \nÇıkarma: {}\nBölüm: {}\nÇarpım: {}'.format('+', '-', '/', '*'))
operator = input("İşlem girin: ")
if operator == "+":
sonuc = sayi1 + sayi2
print('{} + {} = {}'.format(sayi1, sayi2, sonuc))
elif operator == "-":
sonuc = sayi1 - sayi2
print('{} - {} = {}'.format(sayi1, sayi2, sonuc))
elif operator == "/":
sonuc = sayi1 / sayi2
print('{} / {} = {}'.format(sayi1, sayi2, sonuc))
elif operator == "*":
sonuc = sayi1 * sayi2
print('{} * {} = {}'.format(sayi1, sayi2, sonuc))
else:
print("Lütfen Geçerli Bi İşlem yap")
|
464058d30f8f40c6076675e770f12985ffced719 | YugoNishio/python_study | /day_2/class_1.py | 1,344 | 3.9375 | 4 | #classについて
"""用語
クラス:オブジェクトを定義する(どんなオブジェクトなのかの説明)
メソッド:クラス内にある関数
オブジェクト:全ての物、事柄を指す
オブジェクトの生成:クラスからオブジェクトを作ること、インスタンス生成とも呼ぶ(class_2.py)
"""
class Planet: #オブジェクトの定義 普通クラス名の先頭は大文字
def earth(self): #メソッド 最低1つ引数が必要な為、第一引数はself(慣例)
print("地球は過ごしやすい") #earthメソッドの実行内容
self.mars('寒すぎる') #marsメソッドの呼び出し 同じオブジェクト(planet)内なのでself(第一引数の利用)
def mars(self, message): #メソッド
print('火星は' + message) #引数を出力 ""でも''でも文字列と認識されるようです
def venus(self): #venusは呼び出されていないので実行されない.試しに呼び出してみましょう
print("金星は暑すぎる")
planet = Planet() #オブジェクトの生成(今回のオブジェクトはspace) オブジェクト名 = クラス名()
planet.earth() #earthメソッドの呼び出し(実行) オブジェクト名.メソッド名()
#コンストラクタ関数について(class_2.pyに続く…) |
e409c8b61d0757e66b5da0c9b207cfd04d3990f4 | tyagihimansh/search_list | /withoutforloop.py | 164 | 3.953125 | 4 | Simple code to search list for 2**5
"""
L=list(map(lambda x:2**x,range(7)))
X=5
if 2**X in L:
print('at index',L.index(2**X))
else:
print(X,"not found")
|
06b455ec7fde722159cccbe18f6eebcdf48f0b53 | baolibin/leetcode | /腾讯/链表/两数相加.py | 2,497 | 4.03125 | 4 | '''
两数相加
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 方法一:将链表的值转换成整数,整数相加,然后再进行逆序创建一个新的链表
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sum_1 = ''
while l1:
sum_1 += str(l1.val)
l1 = l1.next
sum_2 = ''
while l2:
sum_2 += str(l2.val)
l2 = l2.next
int_1 = int(sum_1[::-1])
int_2 = int(sum_2[::-1])
int_3 = int_1 + int_2
sum_3 = str(int_3)[::-1]
l3 = ListNode(sum_3[0])
cur = l3
for i in range(1, len(sum_3)):
linshi = ListNode(sum_3[i])
cur.next = linshi
cur = cur.next
return l3
# 方法二:进位进行相加
'''
同时遍历两个链表
同步创建结果链表
'''
class Solution:
def addTwoNumbers(self, l1, l2):
dummyHead = ListNode(0) # 结果链表的dummy节点
cur = dummyHead
carry = 0
while l1 or l2: # 只要有一个链表未结束,继续遍历
valL1 = l1.val if l1 else 0 # 结束的链表赋值0
valL2 = l2.val if l2 else 0
total = valL1 + valL2 + carry
carry = total // 10 # 进位处理
cur.next = ListNode(total % 10)
cur = cur.next # 结果链表创建
if l1: # 只遍历未结束的链表,结束的上面直接赋值0
l1 = l1.next
if l2:
l2 = l2.next
if carry > 0: # 不要忘记最后退出循环后,进位的处理
cur.next = ListNode(carry)
return dummyHead.next
|
2b7b1621239406a0ec82d84f3ef03c2d13342044 | AgFeather/StudyNote | /models/ML_Algorithm/PLA algorithm/PLA_pairing.py | 755 | 3.609375 | 4 | #使用python3实现对偶形式的感知机算法
def PLA():
dataset = np.array([[3,3],[4,3],[1,1]])
label = [1,1,-1]
n = np.zeros([len(dataset)])
learning_rate = 1
b = 0
temp = []
for i in range(0,len(dataset)):
for j in range(0,len(dataset)):
temp.append(np.dot(dataset[i],dataset[j].T))
gram_matrix = np.array(temp).reshape([len(dataset),len(dataset)])
i = 0
while i<len(dataset):
tempNum = 0
for j in range(0,len(dataset)):
tempNum += n[j]*label[j]*gram_matrix[j][i]
y = label[i]*(tempNum + b)
if y<=0:
n[i]+=1
b = b+label[i]*learning_rate
i = 0
continue
i+=1
w = np.zeros([len(dataset[0])])
for i in range(len(dataset)):
print(i,dataset[i],label[i])
w = w + n[i]*dataset[i]*label[i]
return w, b
|
c741b82ff1f6375445b80fe097a27eee3499816d | alexnro/Codewars-Katas | /Python/8kyu/invertListValues.py | 215 | 3.828125 | 4 | def invert(lst):
return [-x for x in lst]
if __name__ == "__main__":
assert invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
assert invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
assert invert([]) == [] |
4729195d0ca6ad5afd6934e0e28500cee891ac45 | ZoranPandovski/al-go-rithms | /data_structures/check_bipartite/python/bipartite.py | 2,323 | 4.03125 | 4 | from __future__ import print_function
# Python program to find out whether a
# given graph is Bipartite or not
class Graph():
def __init__(self, V):
self.V = V
self.graph = [[0 for column in range(V)]
for row in range(V)]
# This function returns true if graph G[V][V]
# is Bipartite, else false
def isBipartite(self, src):
# Create a color array to store colors
# assigned to all veritces. Vertex
# number is used as index in this array.
# The value '-1' of colorArr[i] is used to
# indicate that no color is assigned to
# vertex 'i'. The value 1 is used to indicate
# first color is assigned and value 0
# indicates second color is assigned.
colorArr = [-1] * self.V
# Assign first color to source
colorArr[src] = 1
# Create a queue (FIFO) of vertex numbers and
# enqueue source vertex for BFS traversal
queue = []
queue.append(src)
# Run while there are vertices in queue
# (Similar to BFS)
while queue:
u = queue.pop()
# Return false if there is a self-loop
if self.graph[u][u] == 1:
return False;
for v in range(self.V):
# An edge from u to v exists and destination
# v is not colored
if self.graph[u][v] == 1 and colorArr[v] == -1:
# Assign alternate color to this
# adjacent v of u
colorArr[v] = 1 - colorArr[u]
queue.append(v)
# An edge from u to v exists and destination
# v is colored with same color as u
elif self.graph[u][v] == 1 and colorArr[v] == colorArr[u]:
return False
# If we reach here, then all adjacent
# vertices can be colored with alternate
# color
return True
# Driver program to test above function
g = Graph(4)
g.graph = [[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0]
]
print("Yes" if g.isBipartite(0) else "No")
|
15537d8b7d99516f46226683c188bd268bc4c28f | xomay/NSI | /Thonny/rando.py | 2,359 | 3.609375 | 4 | import csv
import matplotlib.pyplot as plt
def lecture_fichier(donne: str) -> list:
"""
fonction qui récupère un fichier et qui renvoie une liste avec les entetes et une liste avec les données
:param donne: fichier de données
:return: liste d'entetes et liste de données
"""
with open(donne, "r") as fichier:
table=csv.reader(fichier)
tab=[]
for ligne in table:
tab.append(ligne)
liste_entetes=[]
for i in range(2):
liste_entetes.append(tab[0][i])
parcours=[]
for i in range(1,len(tab)):
parcours.append((tab[i]))
return liste_entetes, parcours
def separation_donnees(parcours: list) -> list:
altitudes=[]
distances=[]
for i in range(len(parcours)):
altitudes.append(int(parcours[i][0]))
distances.append(float(parcours[i][1]))
return altitudes, distances
def denivele(altitudes: list) -> float:
deniv_positif=0
deniv_negatif=0
for i in range(0,len(altitudes)-1):
if altitudes[i+1]-altitudes[i]>0:
deniv_positif += altitudes[i+1]-altitudes[i]
elif altitudes[i+1]-altitudes[i]<0:
deniv_negatif += altitudes[i+1]-altitudes[i]
return deniv_positif, deniv_negatif
def cumul_distance(distances: list) -> list:
metre=0
distance_parcourue=[]
for i in range(len(distances)):
metre+=distances[i]
distance_parcourue.append(round(metre,2))
return distance_parcourue, metre
def visualisation_denivele(altitudes: list, distance_parcourue: float, entetes: list):
plt.clf()
plt.plot(distance_parcourue, altitudes, 'k,-', linewidth=1, label='y = f(x)')
plt.xlabel(entetes[1])
plt.ylabel(entetes[0])
plt.title('Altitude et topographie')
plt.grid()
plt.show()
fich1, fich2 = lecture_fichier("rando.csv")
altitudes, distances=separation_donnees(fich2)
deniv_positif, deniv_negatif=denivele(altitudes)
distance_parcourue, metre=cumul_distance(distances)
print(distance_parcourue, metre)
print("le dénivelé positif est de : ",deniv_positif,", et le négatif de : ",deniv_negatif)
print("la distance totale de la rando est {:.2f} mètres".format(metre))
visualisation_denivele(altitudes, distance_parcourue, fich1)
|
6778bff91f32c5882b413f2e066c044cc48e2836 | playandlearntocode/main | /mlp/basic/src/mlp.py | 2,239 | 4.15625 | 4 | '''
Simple Multilayer Perceptron example in Python
Author: Goran Trlin
Find more tutorials and code samples on:
https://playandlearntocode.com
'''
import numpy
from PIL import Image
from classes.mlp.mlp import MLP
from classes.csv.csv_data_loader import CsvDataLoader
from classes.extraction.image_feature_extractor import ImageFeatureExtractor
print('MLP program starting...')
#Load training data from CSV files:
csv_data_loader = CsvDataLoader()
data_circle = csv_data_loader.get_training_data('./../csv/correct_outputs_circle.txt')
data_line = csv_data_loader.get_training_data('./../csv/correct_outputs_line.txt')
mlps = [MLP(data_circle), MLP(data_line)]
# mlps[0] - circle detector
# mlps[1] - line detector
# TRAINING PHASE:
# BACKPROPAGATION SETTINGS:
TRAIN_ITERATIONS = 100
TARGET_ACCURACY = 2
for i in range(0, len(mlps)):
total_loss = 99999
total_delta = 9999
train_count = 0
while train_count < TRAIN_ITERATIONS and total_loss > TARGET_ACCURACY:
mlps[i].train_network()
(total_delta, total_loss) = mlps[i].calculate_total_error_on_dataset(mlps[i].learning_examples_array)
print('TOTAL LOSS AT ITERATION (' + str(i) + '):')
print(total_loss)
train_count += 1
print ('Training stopped at step #' + str(train_count) + ' for i=' + str(i))
# TESTING PHASE:
test_file_name = ''
print('Enter file name to classify:')
test_file_name = input('enter the filename:')
test_file_path = './../test_images/' + test_file_name
image = Image.open(test_file_path)
image.show()
img_extractor = ImageFeatureExtractor()
(im_test_image, test_image_pixels) = img_extractor.load_image(test_file_path)
(test_image_f1, test_image_f2, test_image_f3) = img_extractor.extract_features(im_test_image, test_image_pixels)
test_image_row = [test_file_name, test_image_f1, test_image_f2, test_image_f3, 99999]
output_from_circle = mlps[0].predict(test_image_row)
output_from_line = mlps[1].predict(test_image_row)
print('output from circle detector:')
print(output_from_circle)
print('output from line detector:')
print(output_from_line)
if(output_from_circle>output_from_line):
print('This image is a CIRCLE')
else:
print('This image is a LINE')
print('MLP program completed.') |
71b87520ab10e18dca97f30f729df7b9b2efc8d7 | JMCalizario/chatbot | /JuntandoStrings.py | 417 | 4.0625 | 4 | # Capitulo 1
# chat bot em ingles
print('Learning Inglish Names ')
print('-' * 40)
print('hi !!! i am a robot, nice to meet you :) ')
char1 = (input('what is your first name ?'))
char2 = (input('ok, so what is your middle name ?'))
print('Nice :) !!!')
char3 = input('what is your last name ?')
print('Thanks !!! ')
full_name = char1 + char2 + char3
print('Your full name is : ', full_name.rstrip())
|
b74a6752bee666996abaed1c55f192b62213ad1b | fredcomby/IUTPyhton | /pendu.py | 2,837 | 3.578125 | 4 | # -*- coding: UTF-8 -*-
"""
pendu.py
"""
# Import
import tools_chaines
import random
# Constantes
COUPS_MAX = 10
# fonctions
def choix_mot():
dico = tools_chaines.liste_mots_francais()
mot = random.choice(dico)
return mot
def affiche_mot_un_caractere(mot, caractere):
chaine_masquee = ""
# parcours sur tous les caractères de chaine :
for car in mot:
if car == caractere:
chaine_masquee += caractere
else:
chaine_masquee += "-"
print(chaine_masquee)
def affiche_mot(mot, propositions):
chaine_masquee = ""
# parcours sur tous les caractères de chaine :
for car in mot:
if propositions.find(car) != -1:
chaine_masquee += car
else:
chaine_masquee += "-"
print(chaine_masquee)
def est_trouve(mot, lettres):
for car in mot:
if lettres.find(car) == -1:
return False
return True
def saisie(propositions):
erreur = True
while erreur:
print("saisissez une lettre :")
car = input()
if len(car) == 1:
if propositions.find(car) == -1:
erreur = False
car = car.lower()
return car
def main():
# Programme principal
print(">>> Jeu du pendu <<<")
mot = choix_mot() # Choix du mot au hasard par l'ordinateur
print("Mot à deviner pour debuggage :", mot)
# Initialisations des variables de la boucle
coup = 0 # nombre de coups joués par le joueur
coup_perdant = 0 # nombre de coups perdant du joueur
propositions = "" # leta
# tres proposées par le joueur
partie_finie = False # la partie est-elle finie ?
# Boucle de jeu
while not partie_finie:
print("Coup n°{} (reste {} coups perdants possibles) :".format(coup, COUPS_MAX - coup_perdant))
affiche_mot(mot, propositions) # Affichage du mot masqué pour le joueur
lettre = saisie(propositions) # Choix d'une lettre
propositions += lettre # Ajout de la lettre au proposition
print("lettres proposées {}".format(propositions))
# Analyse de la lettre et conséquences sur les coups perdants
# ...
if mot.find(lettre) == -1:
coup_perdant += 1
if coup_perdant == COUPS_MAX:
partie_finie = True
# La partie est-elle finie ?
if est_trouve(mot, propositions):
partie_finie = True
else:
coup = coup + 1
# Fin de la boucle de jeu
# Analyse du jeu ? Le joueur a-t-il gagné
if est_trouve(mot, propositions):
print("Gagné : le mot est :", mot)
else:
print("Perdu : le mot était :", mot)
if __name__ == "__main__":
main()
|
097982aa7bb970002dcdc6194392283cba83ecb7 | lcxidian/soga | /5th/5th code 17.py | 2,964 | 4.1875 | 4 | 1、tuple————类似于pair类型
tuple操作:
tuple<T1,T2,...Tn> t; #未初始化的tuple对象
tuple<T1,T2,...Tn> t(v1,v2,...vn); #初始化的tuple对象
make_tuple(v1,v2,...vn); #生成一个匿名tuple对象
t1 == t2;
t1 != t2;
t1 relop t2;
get<i>(t) #tuple对象的第i个引用
tuple_size<TupleType>::value #特定的类模板tuple_size来获取 tuple的成员个数
tuple_element<i,TupleType>::type #特定的类模板tuple_element来获取 tuple对象的第i个成员的类型
应用:
#生成tuple对象
tuple<size_t,size_t, size_t> threeD;
tuple<string, vector<double>, int, list<int>> someVal("constants", {3.14, 2.718}, 42, {0,1,2,3,4,5});
tuple<size_t, size_t, size_t> threeD{1,2,3}; // ok
tuple<size_t, size_t, size_t> threeD = {1,2,3}; // 错误,tuple构造函数是explicit的
#生成匿名的tuple对象
auto item = make_tuple("0-999-78345-X", 3, 20.00);
#获取tuple对象的第i个成员的值
auto book = get<0>(item); // returns the first member of item
auto cnt = get<1>(item); // returns the second member of item
auto price = get<2>(item)/cnt; // returns the last member of item
get<2>(item) *= 0.8;
#获取tuple对象的成员个数,或某个成员的数据类型
typedef decltype(item) trans; // trans is the type of item
size_t sz = tuple_size<trans>::value; // returns 3
tuple_element<1, trans>::type cnt = get<1>(item); // cnt is an int
#关系运算符
tuple<string, string> duo("1", "2");
tuple<size_t, size_t> twoD(1, 2);
bool b = (duo == twoD); // error: can't compare a size_t and a string
tuple<size_t, size_t, size_t> threeD(1, 2, 3);
b = (twoD < threeD); // error: differing number of members
tuple<size_t, size_t> origin(0, 0);
b = (origin < twoD); // ok: b is true
typedef tuple<vector<Sales_data>::size_type,
vector<Sales_data>::const_iterator,
vector<Sales_data>::const_iterator> matches;
2、bitset————处理二进制集合的类
bitset操作:
bitset<n> b;
bitset<n> b(u);
bitset<n> b(str,pos,len,zero,one);#zero,one表示str中字符必须是zero或one,否则编译器报错
bitset<n> b(c,pos,len,zero,one);
b.any()
b.all()
b.none()
b.count()
b.size()
b.test(pos)
b.set(pos,v)
b.set()
b.reset(pos)
b.reset()
b.flip(pos)
b.flip()
b[pos]
b.to_ulong()
b.to_ullong()
b.to_string(zero,one)
os<<b
is>>b
3、正则表达式
两步:熟悉正则表达式和会使用以下操作
regex #regex类
regex_match #将字符串与正则式进行匹配
regex_search #寻找第一个与正则式匹配的子序列
regex_replace #用指定的字符串去替换与正则式匹配的子串
sregex_iterator #用来遍历regex_search匹配的所有子串
smatch #容器类,存放搜索结果
ssub_match #string中匹配的子表达式的结果
4、随机数
随机数引擎类default_random_engine
分布类模板uniform_int_distribution<T>
|
f26eb32d5d508362213c61631c7e83195146fc49 | tienduy-nguyen/coderust | /2.linked-list/single-linked-list/swap-node/test.py | 952 | 3.90625 | 4 | class ListNode:
def __init__(self, val, next= None):
self.val = val
self.next = next
class Linkedlist:
def __init__(self, head = None):
self.head =head
def swap_with_head(self, head, n):
headVal = head.val
current=head
count = 0
while(current and current.next):
count += 1
if count == n:
head.val = current.val
current.val = headVal
current = current.next
return head
def printNode(self, head):
result = []
current = head
while(current and current.next):
result.append(current.val)
current = current.next
print(result)
def shift(self, val):
new_node = ListNode(val)
new_node.next = self.head
self.head = new_node
if __name__ == '__main__':
print('start')
lk = Linkedlist()
lk.shift(5)
lk.shift(4)
lk.shift(3)
lk.shift(2)
lk.shift(1)
lk.printNode(lk.head)
res = lk.swap_with_head(lk.head,3)
lk.printNode(res)
|
409ecf1cd7736dfe2d5c5e1bafa83a57f6ee47b1 | lulubeanana17/Project_Euler | /6.py | 199 | 3.5 | 4 | b = 0
# the sum of from 1 to 100
a = [a**2 for a in range(1,101)]
# list of a**2 from 1 to 100
for i in range(1, 101):
b += i
# add from 1 to 100 to b
print(f'the answer is {b**2 - sum(a)}') |
5f2d1a029e92d37fa7d09e4e78483d21ac100656 | ayushupneja/2020-sensor-miniproject | /src/sp_iotsim/client.py | 2,310 | 3.53125 | 4 | """
WebSockets client
This program receives simulated data for multiple rooms, with multiple sensors per room.
The default behavior is to only access the computer itself by parameter "localhost"
so that no firewall edits are needed.
The port number is arbitrary, as long as the server and client are on the same port all is well.
Naturally, the server must be started before this client attempts to connect.
"""
import websockets
import zlib
from pathlib import Path
import argparse
import asyncio
async def main(port: int, addr: str, max_packets: int, log_file: Path = None):
"""
Parameters
----------
port: int
the network port to use (arbitrary, must match server)
addr: str
the address of the server (localhost if on same computer)
max_packets: int
to avoid using all the hard drive if the client is left running,
we set a maximum number of packets before shutting the client down
log_file: pathlib.Path
where to store the data received (student must add code for this)
"""
if log_file:
log_file = Path(log_file).expanduser()
uri = f"ws://{addr}:{port}"
async with websockets.connect(uri) as websocket:
qb = await websocket.recv()
if isinstance(qb, bytes):
print(zlib.decompress(qb).decode("utf8"))
else:
print(qb)
f = open('output.txt','w')
for i in range(max_packets):
data = await websocket.recv()
if i % 5 == 0:
pass
# print(f"{i} total messages received")
f.write(data)
f.write("\n")
print(data)
f.close()
def cli():
p = argparse.ArgumentParser(description="WebSocket client")
p.add_argument("-l", "--log", help="file to log JSON data")
p.add_argument("-host", help="Host address", default="localhost")
p.add_argument("-port", help="network port", type=int, default=8765)
p.add_argument(
"-max_packets",
help="shut down program after total packages received",
type=int,
default=100000,
)
P = p.parse_args()
try:
asyncio.run(main(P.port, P.host, P.max_packets, P.log))
except KeyboardInterrupt:
print(P.log)
if __name__ == "__main__":
cli()
|
3ee7438f6c04ab1bbf28988e6f0f3a8c750ba200 | Prabukumaradoss/Python | /Day 2 - Conditional/Pin Number.py | 120 | 4 | 4 | n=int(input("Enter the PIN NUMBER"))
if n==12345:
print("Heloooo")
else:
print("Enter correct PIN NUMBER")
|
eca863c83b7f0d4d2419842e034a125e79006345 | dnmanveet/Joy-Of-Computing-In-Python-Nptel-Course-Python-Programs | /binary_search_recursion.py | 821 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 11:44:40 2018
@author: manveet
"""
l=[1,2,3,4,5]
def binary_search(l,x,start,end):
#Base case is one element in the list
if start==end:
if l[start]==x:
return start
else:
return -1
else:
mid=int((start+end)/2)
if(x==l[mid]):
return mid
else:
if(x>l[mid]):
return binary_search(l,x,mid+1,end)
elif(x<l[mid]):
return binary_search(l,x,start,mid-1)
x=int(input("eneter searh key : "))
index=binary_search(l,x,0,len(l)-1)
if(index == x):
print(x,' Element not found ')
else:
print(x, ' is found at position ', str(index+1))
|
5a2c04658cfdd60d4a479b07879092a034ed5f69 | rashmiranganath/list-programs-python- | /matrices.py | 322 | 3.859375 | 4 | def matrices(a,b):
i=0
while i<len(list1):
j=0
while j<len(list1):
if list1[i]==list2[i]:
result="matrices are identical"
else:
result="matrices are not identical"
j=j+1
i=i+1
print result
list1=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
list2=[[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
matrices(list1,list2)
|
ce533c024651a9d863c7acf6f4dff80c0f6f1314 | eujonas/Python | /Aula 02/questao2.py | 341 | 4.15625 | 4 | """2-Escreva uma função que receba dois números como argumento e retorne o produto do dobro do primeiro pelo triplo do segundo """
num1 = int(input("Primeiro valor:"))
num2 = int(input("Segundo valor:"))
def result(num1, num2):
return (2 * num1) *(3 * num2)
a = result(num1, num2) # retornar
print(a) # função imprimir o valor
|
09925281ad41f4ded886c9ab6e4b4cb5dba9c86c | blhwong/algos_py | /leet/valid_parenthesis/main.py | 456 | 3.78125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
opposite = {
'(': ')',
'[': ']',
'{': '}'
}
i = 0
while i < len(s):
l = s[i]
if l in opposite:
stack.append(opposite[l])
else:
if not stack or stack.pop() != l:
return False
i += 1
return len(stack) == 0
|
332dc044a55f2ebca7b48339d505f81b22a22ae1 | Effiongoto/Devcamp-Technical-Task | /Task_4.py | 937 | 4 | 4 | # Python function to check the strength of a password
def passwordValidation(input_string):
# declaring variables
n = len(input_string)
hasString = False
hasDigit = False
specialChar = False
normalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "
# validation code
for i in range(n):
if input_string[i] in normalChars:
hasString = True
if input_string[i].isdigit():
hasDigit = True
if input_string[i] not in normalChars:
specialChar = True
# strings only
if (hasString):
score = 0
# numbers only
elif (hasDigit):
score = 1
# strings and numbers
elif (hasString and hasDigit):
score = 2
# strings, numbers and special characters
elif (hasString and hasDigit and specialChar):
score = 3
return score
|
713cef434fdb56f5658fe14f51d5be9b17591738 | zeguil/python-exercicios | /exercicio_else.py | 312 | 3.828125 | 4 | print('E necessario ter informaçoes para entrar no exercito\n')
peso=input('Digite seu peso: ')
idade=input('\nDigite sua idade: ')
altura=input('\nDigite sua altura: ')
if peso >= '70' and idade >= '18' and altura >= '1.70':
print('\nvoce esta APROVADO')
else:
print('\nvoce esta REPROVADO') |
da4c43a23cbffe76666dfc9dfbaa45bc9c0f1ac7 | larileonso23/exercicio-groger_bank | /exercicio/groger.bank.py | 152 | 3.640625 | 4 | nome = input('Digite o seu nome: ')
idade = input('Digite sua idade: ')
saldo = input('(Simulação de saldo) - Digite a simulação de saldo: ')
if
|
b9a6a764a38da3205ece0b4f1ebf4e42653f375f | unclebob2008/stepik_py | /stars.py | 78 | 3.578125 | 4 | s = 0
n = int(input())
while n != 0:
s += n
n = int(input())
print(s)
|
488009397276beea5f96c60d00104302abf39e39 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day17/demo02.py | 2,154 | 4.21875 | 4 | '''
迭代器 ---> yield
练习:exercise04.py
目标:让自定义类所创建的对象,可以参与for.
iter价值:可以被for
next价值:返回数据/抛出异常
class 自定义类的迭代器:
def __next__(self):
pass
class 自定义类:
def __iter__(self):
pass
for item in 自定义类():
pass
'''
class SkillIterator:
def __init__(self, data):
self.__target = data
self.__index = -1
def __next__(self):
# 如果没有数据则抛出异常
if self.__index >= len(self.__target) - 1:
raise StopIteration
# 返回数据
self.__index += 1
return self.__target[self.__index]
class SkillManager:
'''
技能管理器 可迭代对象
'''
def __init__(self):
self.__skills = []
def add_skill(self, str_skill):
self.__skills.append(str_skill)
def __iter__(self):
# return SkillIterator(self.__skills)
# 执行过程:
# 1. 调用__iter__()不执行
# 2. 调用__next__()才执行当前代码
# 3. 执行到yield语句暂时离开
# 4. 再次调用__next__()继续执行
# ....
# yield作用: 标记着下列代码会自动转换为迭代器代码。
# 转换大致过程:
# 1. 将yield关键字以前的代码,放到next方法中
# 2. 将yield关键字后面的数据,作为next返回值
# print('准备数据:')
# yield '降龙十八掌'
#
# print('准备数据:')
# yield '黑虎掏心'
#
# print('准备数据:')
# yield '六脉神剑'
for item in self.__skills:
yield item
manager = SkillManager()
manager.add_skill('降龙十八掌')
manager.add_skill('黑虎掏心')
manager.add_skill('六脉神剑')
# 错误:manager必须是可迭代对象__iter__()
for item in manager:
print(item)
iterator = manager.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
|
7f2549f72200761c1ad22d6c2d1f4f74f583f219 | IsaacNewLee/SimpleFactory | /simple_factory.py | 1,309 | 3.5 | 4 | # _*_ coding=utf-8 _*_
from abc import ABCMeta, abstractmethod
"""
不直接向客户端暴露对象创建的实现细节,而是通过一个工厂类来负责创建产品的实例
优点:1隐藏对象创建的实现细节
2客户端不需要修改代码
缺点:1违反了单一职责原则,将创建逻辑集中到一个工厂类
2违反开闭原则,当添加新产品时,需要修改工厂类代码
"""
class Payment(metaclass=ABCMeta):
"""抽象产品角色"""
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
"""具体产品角色"""
def __init__(self, hb=False):
self.hb = hb
def pay(self, money):
print("支付宝支付%s元" % money)
class WechatPay(Payment):
"""具体产品角色"""
def pay(self, money):
print("微信支付%s元" % money)
class SimpleFactory:
"""工厂角色"""
def create_payment(self, method):
if method == "alipay":
return Alipay()
elif method == "wechat":
return WechatPay()
elif method == "hb":
return Alipay(hb=True)
else:
raise TypeError("No such payment named %s" % method)
# client 调用代码层
pf = SimpleFactory()
p = pf.create_payment('alipay')
p.pay(100)
|
59bee163613d39b5a7cd923440fda5be5a4f32e5 | huybv1999/PythonSolution | /ch4/bai4.10.py | 338 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 22:03:57 2020
@author: huybv1998
"""
def convert():
gio = int(input("nhập số giờ: ")) * 3600
phut = int(input("nhập số phút: ")) * 60
giay = int(input("nhập số giây: "))
time = (gio + phut + giay)/86400
return time
print(convert())
|
89efb5ea99cc15960cbe6fae337e8c22b948dcaa | YarnYang/jianzhi-offer | /code/058-对称的二叉树.py | 1,504 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
@题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
@解题思路
一颗对称的二叉树:
5
/ \
4 4
/ \ / \
3 2 2 3
显然,root结点的左右子树应该相等,且左右子树应该成镜像关系,即左子树的左节点应该等于右子树的右节点。
'''
class Solution:
def helper(self, left, right):
if left == None or right == None:
if left == None and right == None:
return True
else:
return False
# 首先判断左右子树的父节点是否相等
if left.val != right.val:
return False
# 然后判断左右子树是否对称是判断左节点是否等于右节点
else:
return self.helper(left.left, right.right) and self.helper(left.right, right.left)
def isSymmetrical(self, pRoot):
# write code here
if pRoot == None:
return True
# 只要有一个为None,就进入判断条件,两个都为None则返回True。否则返回False
if pRoot.left == None or pRoot.right == None:
if pRoot.left == pRoot.right:
return True
else:
return False
# 只有左右结点相等,才继续判断左右子树是否对称
if pRoot.left.val == pRoot.right.val:
return self.helper(pRoot.left, pRoot.right)
else:
return False |
48b3d657455b4adc53b29feb087257685e9330a1 | khiner/Barcodes | /CodeMaker.py | 7,474 | 3.921875 | 4 | """This script generates a simulated code-11 barcode reading
The process is as follows:
1. get a string representation of the code
2. remove invalid characters from the code string
3. append the C check value to the code string
4. append the K check value to the code string
5. convert the code to a bit string where:
0= narrow bar
1= wide bar
code character substrings are separated by a 0
6. Compute a random wide bar width in [1,200] and the corresponding narrow bar width
7. convert the bit string to a list of integer widths where each width is fudged by up to +/- 5%
8. randomly reverse the integer list or not"""
import sys,re,random,string
from subprocess import call
from argparse import ArgumentParser
# mapping from code char -> bit String
bitStrs={"0":"00001","1":"10001","2":"01001","3":"11000","4":"00101", \
"5":"10100","6":"01100","7":"00011","8":"10010","9":"10000", \
"-":"00100", "Start":"00110", "Stop":"00110"}
def w(char): #function to return character weight
try:
return int(char) # try making the char an int weight
except Exception, e: # must not be an integer character
if char == '-': # make sure it's a hyphen
return 10 # return hyphen weight
else:
raise e # bad character
def C(code): # function to generate C check value
c = 0 # set c to zero
n = len(code) # get length of code string
for i in range(1,n+1): # loop over code string length, perform summation
c += (((n-i)%10) + 1) * w(code[i-1]) # compute this step of sum
c %= 11
if c == 10:
# we want one character for c, 10 is two characters
c = '-'
return c # return summation mod 11, C value
def K(code): # function to generate K check value
k = 0 # set k to zero
n = len(code) # get length of code string
for i in range(1,n+1): # loop over code string length, summation
k += (((n-i)%9) +1) * w(code[i-1]) # compute this step of sum, using (n-i) not (n-i +1) because n redefined to include C
k %= 11
if k == 10:
# we want one character for k, 10 is two characters
k = '-'
return k # return summation mod 11, K value
def randCode(maxLength):
length = random.randint(1, maxLength)
return ''.join(random.choice(string.digits + '-') for i in xrange(length))
def code(length):
return ''.join(random.choice(string.digits + '-') for i in xrange(length))
def getCodeCK(dirtyCode, badC=False, badK=False):
code = re.sub(r"[^0-9\-]","",dirtyCode) # remove invalid characters from input
chars = string.digits + '-'
#compute and append C to code string
c = str(C(code))
if badC:
c = random.choice(chars.replace(c, ''))
codeC = code + c
#compute and append K to code string
k = str(K(codeC))
if badK:
k = random.choice(chars.replace(k, ''))
return codeC + k
def genBadC(dirtyCode):
codeCK = getCodeCK(dirtyCode, badC=True)
return genValues(codeCK)
def genBadK(dirtyCode):
codeCK = getCodeCK(dirtyCode, badK=True)
return genValues(codeCK)
def genGood(dirtyCode):
codeCK = getCodeCK(dirtyCode)
return genValues(codeCK)
def genValues(codeCK):
#compute the bitstring for this code
codeCKBitStr = bitStrs["Start"] + "0" # begin with start char and spacer
for char in codeCK: # loop over all chars in code
codeCKBitStr += bitStrs[char] + "0" # append bitstring for this char and spacer
codeCKBitStr += bitStrs["Stop"] # append stop character
fudge = lambda val: val+int(val*(-0.05+0.1*random.random())) # function to apply random error to a value, +/- 5%
# get some value for narrow width
# max is 95, since 92*2 = 190, and max(fudge(190)) == 200 (199.5 rounded up)
narrow = random.randint(1,95)
wide = narrow*2 # compute wide width
width = {"0":narrow,"1":wide} # mapping bit character -> bar width
values = [] # list to hold integer values for final representation
for b in codeCKBitStr: #loop over bits characters in code bit string
values.append(fudge(width[b])) #get width for this bit, fudge it, then append to the list
if random.random() > 0.50: #the code could be backwards, reverse it half the time
values.reverse()
return values
parser = ArgumentParser()
parser.add_argument('-r', '--numRand', type=int, default=0, help='if you want randomly generated cases, specify the number of cases.')
parser.add_argument('-c', '--code', nargs='+', help='specific codes you would like to test. If random cases are also generated, these will be the first cases.')
parser.add_argument('-m', '--maxLength', type=int, help="maximum length of the test strings. \
default is 21 for max input length of 150 (150/6 = 25, sub 4 for start/stop/c/k).", default=21)
parser.add_argument('-f', '--file', default='testInput', help="file name to write test input to. default is 'testInput'")
parser.add_argument('-t', '--testFile', help='optionally print the expected java output to a the specified file')
parser.add_argument('-v', '--verbose', action='store_true', help='print the values to command line')
args = parser.parse_args()
if not args.code and args.numRand == 0:
args.numRand = 1 # send at least one output
allValues = []
allCodes = []
if args.code: # get input code from command line arg
for code in args.code:
allCodes.append(code)
values = genGood(code)
values.insert(0,len(values)) # first number is length of input
allValues.append(values)
# generate the desired number of random cases.
# if the random arg was not set, numRand will be 0
for i in xrange(args.numRand):
code = randCode(args.maxLength)
rand = random.random()
if rand < 0.33:
allCodes.append(code)
values = genGood(code)
elif rand < 0.66:
allCodes.append('badC')
values = genBadC(code)
else:
allCodes.append('badK')
values = genBadK(code)
values.insert(0, len(values)) # first number is length of input
allValues.append(values)
# output to file and run BarCodes
f = open(args.file, 'w')
for values in allValues:
f.write(str(values[0]) + '\n')
for v in values[1:]:
f.write(str(v) + " ")
f.write('\n')
f.write('0\n')
f.close()
# run BarCodes using the file
cmd = ["java", "BarCodes2", args.file]
call(cmd)
# print to command line as well if verbose option is set
if args.verbose:
for line in open(args.file, 'r').readlines():
print line
if args.testFile:
f = open(args.testFile, 'w')
# write expected output of each case to the file
for i in xrange(len(allCodes)):
if allCodes[i] == 'badC':
f.write('Case ' + str(i + 1) + ': bad C\n')
elif allCodes[i] == 'badK':
f.write('Case ' + str(i + 1) + ': bad K\n')
else:
f.write('Case ' + str(i + 1) + ': ' + allCodes[i] + '\n')
f.close()
|
1959628b24c122a9e2c8e4072960ad389cfbdb57 | neequole/my-python-programming-exercises | /unsorted_solutions/question91.py | 337 | 3.796875 | 4 | """ Question 91:
With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155],
write a program to make a list whose elements are intersection of the above given lists.
Hints:
Use set() and "&=" to do set intersection operation.
"""
a = set([1, 3, 6, 78, 35, 55])
b = set([12, 24, 35, 24, 88, 120, 155])
print(a.intersection(b))
|
62a58f56dcef75eb07ef6b821758b0bc499d0009 | Nahidjc/python_problem_solving | /PRACTICE-2 SOLUTION.py | 106 | 3.71875 | 4 | n=int(input("Enter a Number: "))
sp= " "
st="*"
for i in range(1,n+1,1):
print(sp*(n-i)+(st*(i*2-1)))
|
f5dcaeaf7358d88450e5e9f5e857deed29b786bd | sharkEater18/Space-Invader-using-Python- | /prev versions/spaceinvd.py | 5,536 | 3.5 | 4 | # Those who came before me
# Lived through their vocations
# From the past until completion
# They'll turn away no ....
# Importing Libraries
import turtle
from os import *
import random
import time
delay = 0.1
# Window/ Screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invader V_12.08")
wn.setup(655, 655)
wn.bgpic("bg3.gif")
# Border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("pink")
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pensize(3)
border_pen.down()
for side in range(4):
border_pen.fd(600)
border_pen.left(90)
border_pen.hideturtle()
# Scoring
score = 0
score_panel = turtle.Turtle()
score_panel.speed(0)
score_panel.color("white")
score_panel.penup()
score_panel.setposition(-290, 280)
scorestring = "Score: %s" % score
score_panel.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
# score_panel.hideturtle()
# Spaceship / Player
spaceship = turtle.Turtle()
spaceship.color("blue")
spaceship.shape("triangle")
spaceship.penup()
spaceship.speed(0)
spaceship.goto(0, -250)
spaceship.left(90) # player.setheading(90)
sapceship_speed = 20
spaceship_speed = 20
spaceship.direction = "stop"
# Invader(s)
number_of_invaders = 4
invaders = []
# Create a list of invaders of turtle
for i in range(number_of_invaders):
invaders.append(turtle.Turtle())
for enemy in invaders:
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
x = random.randint(-200, 200)
y = random.randint(180, 250)
enemy.goto(x, y)
invaders_speed = 2
# Weapon(s) / Missile
missile = turtle.Turtle()
missile.color("yellow")
missile.shape("triangle")
missile.penup()
missile.speed(0)
missile.left(90)
missile.shapesize(0.5, 0.5)
missile.hideturtle()
# missile.goto(-150, 250) // For testing purpose only
missile_speed = 40
# Missile State
# ready - ready to fire
# fire - on firing
missile_state = "ready"
# Functions
# Movements
def go_left():
spaceship.direction = "left"
def go_right():
spaceship.direction = "right"
def move():
x = spaceship.xcor()
if spaceship.direction == "left":
if x < -270:
x = -280
spaceship.setx(x)
else:
spaceship.setx(x - spaceship_speed)
if spaceship.direction == "right":
if x > 270:
x = 280
spaceship.setx(x)
else:
spaceship.setx(x + spaceship_speed)
# For Dynamic/Automatic movement just comment this
# spaceship.direction = 'stop'
# For Missile
def fire_missile():
# Decalring missile state as a global
global missile_state
# Missile border check
if missile.ycor() > 270:
missile_state = "ready"
if missile_state == "ready":
missile_state = "fire"
# Move the missile to just above the player
x = spaceship.xcor()
y = spaceship.ycor()
missile.setx(x)
missile.sety(y + 10) # missile.setpos(x, y + 10)
missile.showturtle()
# Keybinding
wn.listen()
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
wn.onkeypress(fire_missile, "space")
# turtle.listen()
# turtle.onkey(go_left, "Left")
# turtle.onkey(go_right, "Right")
# turtle.onkey(fire_missile, "space")
#:::::::::::::::::::::::::OR::::::::::::::::::::::::::::::
# # Functions
# def move_left():
# player.setx(player.xcor() - 20)
# def move_right():
# player.setx(player.xcor() + 20)
# # Keybinding
# wn.listen()
# wn.onkeypress(move_left, 'a')
# wn.onkeypress(move_right, 'd')
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::
# Main
while True:
wn.update()
move()
# Invaders for loop
for enemy in invaders: # NOTE: enemy is a single invader
x = enemy.xcor()
y = enemy.ycor()
enemy.setx(x + invaders_speed)
# Reverse enemy's direction / Invader-window collision
if x > 280:
enemy.setx(280)
# Reverse the enemy
invaders_speed *= -1
# Move all the invaders down
for i in invaders:
y = i.ycor()
y -= 40
i.sety(y)
if x < -280:
enemy.setx(-280)
# Reverse the enemy
invaders_speed *= -1
# Move all the invaders down
for i in invaders:
y = i.ycor()
y -= 40
i.sety(y)
# Missile-Invader Collision Detection
if missile.distance(enemy) < 20:
x = random.randint(-250, 250)
y = random.randint(180, 250)
# enemy.goto(x, y)
missile.hideturtle()
missile_state = "ready"
missile.goto(0, -500)
enemy.setposition(x, y)
# Increment the score
score += 10
scorestring = "Score: %s" % score
score_panel.clear()
score_panel.write(
scorestring, False, align="left", font=("Arial", 14, "normal")
)
# Game Over OR invader-spaceship collision
if enemy.distance(spaceship) < 25:
enemy.hideturtle()
spaceship.hideturtle()
missile.hideturtle()
break
# Missile fire
if missile_state == "fire":
ym = missile.ycor()
missile.sety(ym + missile_speed)
# Missile reset (out of bounds)
if missile.ycor() > 275:
missile.hideturtle()
missilestate = "ready"
delay = raw_input("Press enter to finsh.")
wn.mainloop()
|
84f815564f143b76183fd3f7c5a5875d19fa03c5 | acharyas121/tourism | /hangmangame.py | 802 | 4.125 | 4 | import random
# creating a list of words for the game
list = ["dictionary","books","popular","mouse","conversation"]
# choice() chooses one of the elements from the list
a = random.choice(list)
name = input("Enter your name")
print("Hello {} \n Welcome to Hangman game!".format(name))
print("A random word will be chosen by the computer. The player will have to guess all the letters of the word and 10 chances are given")
guess = input("Enter your first guess for the letters of the word")
length1 = len(a)
count = 10
while count !=0:
for z in range(0,length1):
if guess == a[z]:
print("\t{}".format(a[z]))
count=count+1
else:
print("\t_")
count=count-1
guess =input("Enter your guess for the letters of the word")
|
880a246caac68b54f74b78a985a1e4d0ea59d98f | pjm8707/Python_Beginning | /py_basic_functions.py | 1,127 | 3.875 | 4 | from __future__ import division
import sys
# from __future__ import division
temp_value_1 = 5/2;
temp_value_2 = 5//2;
print("temp_value_1(", type(temp_value_1), "):", temp_value_1)
print("temp_value_2(", type(temp_value_2), "):", temp_value_2)
# function
def Double(x):
""" ex
this function is to output two times x.
"""
return x*2
print ("\ndouble(8):", Double(8))
def ApplyToEight(func):
"""call the function func has input parameter 8 """
return func(8)
MyDouble = Double
print("apply_to_eight(double):", ApplyToEight(MyDouble))
#lambda function
print("call the lambda function:", ApplyToEight(lambda x: x+5))
#a better way than lambda func
def AnotherDouble(x): return 2*x
print("another_double:", AnotherDouble(7))
#default parameter
def MyPrint(msg="my default message"):
return msg
print("\nMyPrint():", MyPrint())
print("MyPrint():", MyPrint("Hello JM!!!"))
def Subtract(a=0, b=0):
return a-b
print("\nSubTract(10,5):", Subtract(10,5))
print("SubTract(0,5):", Subtract(0,5))
print("SubTract(b=5):", Subtract(b=5))
|
29ed56ffae6863259f383e437d61b79a63968e57 | hampgoodwin/automated-software-testing-with-python | /section2/classes_objects.py | 890 | 3.53125 | 4 | # lottery_player_dict = {
# 'name': 'Rolf',
# 'numbers': (5, 9, 12, 3, 1, 21)
# }
# class LotterPlayer:
# def __init__(self, name):
# self.name = name
# self.numbers = (5, 9, 12, 3, 1, 21)
# def total(self):
# return sum(self.numbers)
# player_one = LotterPlayer("Rolf")
# player_one.numbers = (1,2,3,6,7,8)
# player_two = LotterPlayer("John")
# print(player_one.numbers == player_two.numbers)
##
class Students:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@staticmethod
def go_to_school():
print("I'm going to school.")
anna = Students("Anna", "MIT")
rolf = Students("Rolf", "Oxford")
anna.marks.append(56)
anna.marks.append(71)
print(anna.average())
Students.go_to_school()
|
1b685ead833c90b45ed65c0ee242abe7a1738c53 | ghffadel/Atividade-008 | /department.py | 366 | 3.671875 | 4 | class Department:
def __init__(self, name, teacher_list):
self.name = name
self.teacher_list = teacher_list
def insert_teachers(self, teacher):
self.teacher_list.add(teacher)
def __str__(self):
return "%s [%s]" % (
self.name,
", ".join([teacher.name for teacher in self.teacher_list]),
)
|
6a332d2e824c2090e886847b898b486b9cf6bc49 | Romny468/FHICT | /palindrome_checker/palindrome_checker_v1.py | 435 | 4.1875 | 4 | #This is a palindrome checker
def palindromeCheck():
string = input("enter a word: ")
for i in range(0, int(len(string)/2)):
if string[i] != string[len(string)-i-1]:
return False
return True
#program beginning
print("i am a programmed to check if a word is a palindrome")
ans = palindromeCheck()
if ans: print("your input is a palindrome!")
else: print("your input is not a palindrome")
|
d9598290d39dcbd35dd6b9bc527f82508b9fa7cd | Keviwevii/Python-Crash-Course | /If Statements/stages_of_life.py | 335 | 4.125 | 4 | #Determining age
age = 65
if age < 2:
message = 'You are a baby!'
elif age < 4:
message = 'You are a toddler!'
elif age < 13:
message = 'You are a kid!'
elif age < 20:
message= 'You are a teenager!'
elif age < 65:
message = 'You are an adult!'
elif age >= 65:
message = 'You are an elder!'
print(message) |
728dc30452dd8f94c46cfe8e30175eb79d88c855 | PickertJoe/python_problems | /binary_converter.py | 3,165 | 4.28125 | 4 | # A program to convert any user-provided decimal value into binary form and vice versa
class Stack:
"""A class to simulate the stack data structure"""
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def main():
"""A function to serve as the main menu"""
while True:
print("\n~~~Welcome to the Python Binary Digit Converter~~~")
print("Please select an option from the menu below: ")
choice = input("1) Decimal -> Binary \n2) Binary -> Decimal \n3) Exit program\n:")
if choice == '1':
dec_to_bin()
continue
elif choice == '2':
bin_to_dec()
continue
elif choice == '3':
print("Exiting program...")
break
else:
print("Invalid input. Returning to main...")
continue
def dec_to_bin():
"""A function to convert a decimal value into its binary representation"""
value = grab_input('a')
original = value
bin_stack = Stack()
while value > 0:
remainder = value % 2
bin_stack.push(remainder)
value = value // 2
result = ''
while bin_stack.size() > 0:
result = result + str(bin_stack.pop())
show_results(original, result, 'a')
def bin_to_dec():
"""A function to convert a binary value into its decimal representation"""
original = grab_input('b')
value = [int(x) for x in str(original)]
print(value)
positional = [2**i for i in range(0, len(value))]
print(positional)
product = []
for i in range(0, len(value)):
product.append(positional[-(1 + i)] * value[i])
final = sum(product)
show_results(original, final, 'b')
def grab_input(conversion):
"""A function to grab the value input from the user"""
if conversion == 'a':
while True:
value = input("Please enter the decimal number you'd like to convert: ")
try:
int(value)
except ValueError:
print("Invalid input. Please try again.")
continue
else:
value = int(value)
break
return value
else:
while True:
value = input("Please enter the binary number you'd like to convert: ")
try:
int(value)
except ValueError:
print("Invalid input. Please try again.")
continue
else:
value = int(value)
break
return value
def show_results(original, value, conversion):
"""A function to share the results of the conversion with the user"""
if conversion == 'a':
print("The binary representation of " + str(original) + " is : " + value)
else:
print("The decimal representation of " + str(original) + " is: " + str(value))
main()
|
1a66581bc108933db0657eeb04c97c65d3e8222e | sgbm0592/python_class | /ej_operador.py | 439 | 3.796875 | 4 | #operador incremental +=
#suma a variable de izq lo de la derecha
#operador decremental -=
numero = 15
numero -= 10
print(numero)
#operador incrimental *=
numero = 5
numero *= 3
print(numero)
#operador incrimental /=
#operador incrimental //= valor entero
numero = 25
numero //= 4
print(numero)
#operador incrimental %= modulo
numero = 10
numero %= 2
print(numero)
#operador incrimental %= exp
numero = 4
numero **= 2
print(numero) |
e3611ce016fec6872fc67ae0272a7f5518e4e791 | Carayav/HackerRank-Contests | /2014-04-21-Weekly/MaxXor/mx.accepted.py | 228 | 3.5625 | 4 | #!/bin/python
# Complete the function below.
def maxXor(l, r):
return max([a ^ b for a in range(l, r + 1) for b in range(a, r + 1)])
_l = int(raw_input());
_r = int(raw_input());
res = maxXor(_l, _r);
print(res)
|
fda676be2e72001b38707317df6bf8484f22fefe | SR-Razavi/python_level_2 | /OOP_project.py | 4,053 | 4.25 | 4 | """
* OOP is a fundemental to becoming a good python programmer,
so let's get some extra practice by bulding a game!
* we will use OOP to create a cart game war!
"""
from random import shuffle
# to useful variables for creating cards
SUITE = 'H D S C'.split()
RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
# mycards = [(s,r) for s in SUITE for r in RANKS]
# mycards = []
# for r in RANKS:
# for s in SUITE:
# mycards.append((s,r))
class Deck:
"""
this is the Deck class. this object will create a deck of cards ti initiate play.
tou can then use this deck list of cards to splite in half and give to the players.
it will use SUITE and RUNKS to create the deck.
it should also have a method for splitting/cutting the deck in hulf and shuffling the deck.
"""
def __init(self):
print("creating new ordered deck!")
self.allcards = [(s,r) for s in SUITE for r in RANKS]
def shuffle(self):
print('shuffling the deck')
shuffle(self.allcards)
def split_in_half(self):
return (self.allcards[:26], self.allcards[26:])
class Hand():
"""
this is the Hand class, each player has a hand, and can add or remove cards from that hand.
ther should be an add and remove card method here.
"""
def __init__(self, cards):
self.cards = cards
def __str__(self):
return 'contains {} cards'.format(len(self.cards))
def add(self, added_cards):
self.cards.extend(added_cards)
def remove_card(self):
return self.cards.pop()
class Player():
"""
this is the Player class, wich takes in a name and an instance of a Hand class object.
the player can then play cards and check if they still have cards.
"""
def __init__(self, name, hand):
self.name = name
self.hand = hand
def play_card(self):
drawn_card = self.hand.remove_card()
print('{} has plased: {}'.format(self.name, drawn_card))
print('\n')
return drawn_card
def remove_war_cards(self):
war_cards = []
if len(self.hand.cards) < 3:
return self.hand.cards
else:
for x in range(3):
war_cards.append(self.hand.remove_card())
return war_cards
def still_has_cards(self):
"""
return true if player still has cards left
"""
return len(self.hand.cards) != 0
######################
##### GAME PLAY ######
######################
print("welcome to war, let's begin...")
# create new deck and split in half:
d = Deck()
d.shuffle()
half1,half2 = d.split_in_half()
# create both player
comp = Player('computer', Hand(half1))
name = input('wath is you name?')
user = Player(name, Hand(half2))
total_rounds = 0
war_count = 0
while user.still_has_cards and comp.still_has_cards():
total_rounds += 1
print('Time for a new round!')
print('here are the carent standing')
print(user.name + 'hase the count: ' + str(len(user.hand.cards)))
print(comp.name + 'hase the count: ' + str(len(comp.hand.cards)))
print('play a card! \n')
table_cards = []
c_card = comp.play_card()
p_card = user.play_card()
table_cards.append(c_card)
table_cards.append(p_card)
if c_card[1] == p_card[1]:
war_count += 1
print('war!')
table_cards.extend(user.remove_war_cards())
table_cards.extend(comp.remove_war_cards())
if RANKS.index(c_card[1]) < RANKS.index(p_card[1]):
user.hand.add(table_cards)
else:
comp.hand.add(table_cards)
else:
if RANKS.index(c_card[1]) < RANKS.index(p_card[1]):
user.hand.add(table_cards)
else:
comp.hand.add(table_cards)
print("game over, number of rounds: " + str(total_rounds))
print('a war happend ' + str(war_count) + ' times')
print('does the computer still have cards? ')
print(str(comp.still_has_cards()))
print('does the human still have cards? ')
print(str(user.still_has_cards())) |
28fb082aae22056f2068b6eebd05c23a4d6453e9 | fd-developer/papybot-fd | /pappyapp/clean_query.py | 1,301 | 4.03125 | 4 | #! /usr/bin/env python
# coding: utf-8
import json
import unicodedata
class CleanQuery:
""" CleanQuery is used to remove from a string accents, uppercase, and a
list of words belonging to a list of bad words called STOP WORDS """
wordlist = []
def __init__(self, query):
self.strquery = query
""" stopwords.json is the list of bad words
You can add new words if you want """
with open('pappyapp/static/files/stopwords.json') as json_data:
self.wordlist = json.load(json_data)
def strip_accents(self, s):
""" This method removes accents from a string """
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def clean(self):
""" This method is used to
strip accents of a string
put a string in lower caracteres
take off words of a string found in a stop words list
return a string without words found in stop words
"""
self.strquery = self.strip_accents(self.strquery)
self.query = self.strquery.lower().split()
queryCleaned = []
for e in self.query:
if e not in self.wordlist:
queryCleaned.append(e)
return " ".join(queryCleaned)
|
ba3d81204c8df85090c441e0c2c37def39d0c402 | wh122714892/-2018 | /tanxin_version3.py | 21,444 | 3.96875 | 4 | import math
#写的比骄乱,也没整理,整体思路就是按找对应服务器的比例进行放置。
def knapsack_version3(Vm_list,input_lines,cpu_memory_choose):
# cpu = int(input_lines[0].split( )[0])
# mem = int(input_lines[0].split( )[1])
# input_list = []
# input_list.append(cpu)
# input_list.append(mem)
# cpu_memory_choose = 0
# if input_lines[-4].strip() = 'MEM':
# cpu_memory_choose = 1
#cpu_memory_choose 1 for memory optimizer ,else is cpu optimition
full_cpu1 = input_lines[0] #every servel has the number of cpu
full_memory1 = input_lines[1] #every servel has the number of memory
cpu_chanege11=[] # the type of vmware memory/cpu =1:1
memory_change11=[]
cpu_chanege21=[] # the type of vmware memory/cpu =2:1
memory_change21=[]
cpu_chanege41=[] # the type of vmware memory/cpu =4:1
memory_change41=[]
servel=[]
####### for birth the 1:1 and 2:1 and 4:1 list
for i in range(0,len(Vm_list),3):
for j in range(Vm_list[i]):
cpu_chanege11.append(int(math.pow(2,i/3)))
memory_change11.append(int(math.pow(2,i/3)))
for i in range(1,len(Vm_list),3):
for j in range(Vm_list[i]):
cpu_chanege21.append(int(math.pow(2,(i-1)/3)))
memory_change21.append(int(2*math.pow(2,(i-1)/3)))
for i in range(2,len(Vm_list),3):
for j in range(Vm_list[i]):
cpu_chanege41.append(int(math.pow(2,(i-2)/3)))
memory_change41.append(int(4*math.pow(2,(i-2)/3)))
cpu_chanege11.reverse()
memory_change11.reverse()
cpu_chanege21.reverse()
memory_change21.reverse()
cpu_chanege41.reverse()
memory_change41.reverse()
# print(cpu_chanege11)
# print(memory_change11)
# print(cpu_chanege21)
# print(memory_change21)
# print(cpu_chanege41)
# print(memory_change41)
flavor=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
full_computer=0
full_cpu=full_cpu1
full_memory=full_memory1
nowpos=0
nowpos21=0
nowpos41=0
flag=0
flag1=0
while (len(cpu_chanege11)+len(cpu_chanege21)+len(cpu_chanege41))>0:
while (nowpos+nowpos21+nowpos41) < (len(cpu_chanege11)+len(cpu_chanege21)+len(cpu_chanege41)): # nowpos present the now location
print("------------")
print("cpu_chanege11=")
print(len(cpu_chanege11))
print("cpu_change21=")
print(len(cpu_chanege21))
print("cpu_change41=")
print(len(cpu_chanege41))
print("------------")
print("cpu=%d",full_cpu)
print("memory=%d",full_memory)
if full_cpu==0 or full_memory==0:
break
else:
if full_memory/(full_cpu*1.0)<1.5: # use 1:1 then 2:1 then 4:1
print("111")
#decide weather the n can put into servel
if len(cpu_chanege11)>0 and nowpos<len(cpu_chanege11) and 0<=(full_cpu - cpu_chanege11[nowpos]) and 0<=(full_memory-memory_change11[nowpos]):
full_cpu-=cpu_chanege11[nowpos]
full_memory-=memory_change11[nowpos]
if cpu_chanege11[nowpos] ==1 and memory_change11[nowpos]==1:
flavor[0]+=1;
if cpu_chanege11[nowpos] ==2 and memory_change11[nowpos]==2:
flavor[3]+=1;
if cpu_chanege11[nowpos] ==4 and memory_change11[nowpos]==4:
flavor[6]+=1;
if cpu_chanege11[nowpos] ==8 and memory_change11[nowpos]==8:
flavor[9]+=1;
if cpu_chanege11[nowpos] ==16 and memory_change11[nowpos]==16:
flavor[12]+=1;
del cpu_chanege11[nowpos]
del memory_change11[nowpos]
else:
nowpos = nowpos +1 ;
if nowpos>=len(cpu_chanege11) and len(cpu_chanege21)>0 and nowpos21<len(cpu_chanege21) and 0<=(full_cpu - cpu_chanege21[nowpos21]) and 0<=(full_memory-memory_change21[nowpos21]):
full_cpu-=cpu_chanege21[nowpos21]
full_memory-=memory_change21[nowpos21]
if cpu_chanege21[nowpos21] ==1 and memory_change21[nowpos21]==2:
flavor[1]+=1;
if cpu_chanege21[nowpos21] ==2 and memory_change21[nowpos21]==4:
flavor[4]+=1;
if cpu_chanege21[nowpos21] ==4 and memory_change21[nowpos21]==8:
flavor[7]+=1;
if cpu_chanege21[nowpos21] ==8 and memory_change21[nowpos21]==16:
flavor[10]+=1;
if cpu_chanege21[nowpos21] ==16 and memory_change21[nowpos21]==32:
flavor[13]+=1;
del cpu_chanege21[nowpos21]
del memory_change21[nowpos21]
else:
nowpos21 = nowpos21 + 1
if nowpos>=len(cpu_chanege11) and nowpos21 >= len(cpu_chanege21) and len(cpu_chanege41)>0 and nowpos41<len(cpu_chanege41) and 0<=(full_cpu - cpu_chanege41[nowpos41]) and 0<=(full_memory-memory_change41[nowpos41]):
full_cpu-=cpu_chanege41[nowpos41]
full_memory-=memory_change41[nowpos41]
if cpu_chanege41[nowpos41] ==1 and memory_change41[nowpos41]==4:
flavor[2]+=1;
if cpu_chanege41[nowpos41] ==2 and memory_change41[nowpos41]==8:
flavor[5]+=1;
if cpu_chanege41[nowpos41] ==4 and memory_change41[nowpos41]==16:
flavor[8]+=1;
if cpu_chanege41[nowpos41] ==8 and memory_change41[nowpos41]==32:
flavor[11]+=1;
if cpu_chanege41[nowpos41] ==16 and memory_change41[nowpos41]==64:
flavor[14]+=1;
del cpu_chanege41[nowpos41]
del memory_change41[nowpos41]
else:
nowpos41 = nowpos41 +1 ; #turn to the next position
#########use 2:1 first ,then 1:1, then 4:1
elif full_memory/(full_cpu*1.0)<2 and full_memory/(full_cpu*1.0)>=1.5:
print("222")
#decide weather the n can put into servel
if len(cpu_chanege21)>0 and nowpos21<len(cpu_chanege21) and 0<=(full_cpu - cpu_chanege21[nowpos21]) and 0<=(full_memory-memory_change21[nowpos21]):
full_cpu-=cpu_chanege21[nowpos21]
full_memory-=memory_change21[nowpos21]
if cpu_chanege21[nowpos21] ==1 and memory_change21[nowpos21]==2:
flavor[1]+=1;
if cpu_chanege21[nowpos21] ==2 and memory_change21[nowpos21]==4:
flavor[4]+=1;
if cpu_chanege21[nowpos21] ==4 and memory_change21[nowpos21]==8:
flavor[7]+=1;
if cpu_chanege21[nowpos21] ==8 and memory_change21[nowpos21]==16:
flavor[10]+=1;
if cpu_chanege21[nowpos21] ==16 and memory_change21[nowpos21]==32:
flavor[13]+=1;
del cpu_chanege21[nowpos21]
del memory_change21[nowpos21]
else:
nowpos21 = nowpos21 +1
if nowpos21>=len(cpu_chanege21) and len(cpu_chanege11)>0 and nowpos<len(cpu_chanege11) and 0<=(full_cpu - cpu_chanege11[nowpos-len(cpu_chanege21)]) and 0<=(full_memory-memory_change11[nowpos-len(cpu_chanege21)]):
full_cpu-=cpu_chanege11[nowpos-len(cpu_chanege21)]
full_memory-=memory_change11[nowpos-len(cpu_chanege21)]
if cpu_chanege11[nowpos-len(cpu_chanege21)] ==1 and memory_change11[nowpos-len(cpu_chanege21)]==1:
flavor[0]+=1;
if cpu_chanege11[nowpos-len(cpu_chanege21)] ==2 and memory_change11[nowpos-len(cpu_chanege21)]==2:
flavor[3]+=1;
if cpu_chanege11[nowpos-len(cpu_chanege21)] ==4 and memory_change11[nowpos-len(cpu_chanege21)]==4:
flavor[6]+=1;
if cpu_chanege11[nowpos-len(cpu_chanege21)] ==8 and memory_change11[nowpos-len(cpu_chanege21)]==8:
flavor[9]+=1;
if cpu_chanege11[nowpos-len(cpu_chanege21)] ==16 and memory_change11[nowpos-len(cpu_chanege21)]==16:
flavor[12]+=1;
del cpu_chanege11[nowpos-len(cpu_chanege21)]
del memory_change11[nowpos-len(cpu_chanege21)]
else:
nowpos+=1
if nowpos>=len(cpu_chanege11) and nowpos21>=len(cpu_chanege21) and len(cpu_chanege41)>0 and nowpos41<len(cpu_chanege41) and 0<=(full_cpu - cpu_chanege41[nowpos41]) and 0<=(full_memory-memory_change41[nowpos41]):
full_cpu-=cpu_chanege41[nowpos41]
full_memory-=memory_change41[nowpos41]
if cpu_chanege41[nowpos41] ==1 and memory_change41[nowpos41]==4:
flavor[2]+=1;
if cpu_chanege41[nowpos41] ==2 and memory_change41[nowpos41]==8:
flavor[5]+=1;
if cpu_chanege41[nowpos41] ==4 and memory_change41[nowpos41]==16:
flavor[8]+=1;
if cpu_chanege41[nowpos41] ==8 and memory_change41[nowpos41]==32:
flavor[11]+=1;
if cpu_chanege41[nowpos41] ==16 and memory_change41[nowpos41]==64:
flavor[14]+=1;
del cpu_chanege41[nowpos41]
del memory_change41[nowpos41]
else:
nowpos41 = nowpos41 +1 ; #turn to the next position
#########use 2:1 first ,then 4:1, then 1:1
elif full_memory/(full_cpu*1.0)<3 and full_memory/(full_cpu*1.0)>=2:
print("333")
#decide weather the n can put into servel
# print("------cpu_changeddddddd")
# print(cpu_chanege21)
# print("-------cpu_changeddddddd")
if len(cpu_chanege21)>0 and nowpos21<len(cpu_chanege21) and 0<=(full_cpu - cpu_chanege21[nowpos21]) and 0<=(full_memory-memory_change21[nowpos21]):
full_cpu-=cpu_chanege21[nowpos21]
full_memory-=memory_change21[nowpos21]
if cpu_chanege21[nowpos21] ==1 and memory_change21[nowpos21]==2:
flavor[1]+=1;
if cpu_chanege21[nowpos21] ==2 and memory_change21[nowpos21]==4:
flavor[4]+=1;
if cpu_chanege21[nowpos21] ==4 and memory_change21[nowpos21]==8:
flavor[7]+=1;
if cpu_chanege21[nowpos21] ==8 and memory_change21[nowpos21]==16:
flavor[10]+=1;
if cpu_chanege21[nowpos21] ==16 and memory_change21[nowpos21]==32:
flavor[13]+=1;
del cpu_chanege21[nowpos21]
del memory_change21[nowpos21]
else:
nowpos21+=1
if nowpos21 >=len(cpu_chanege21) and len(cpu_chanege41)>0 and nowpos41<len(cpu_chanege41) and 0<=(full_cpu - cpu_chanege41[nowpos41]) and 0<=(full_memory-memory_change41[nowpos41]):
full_cpu-=cpu_chanege41[nowpos41]
full_memory-=memory_change41[nowpos41]
if cpu_chanege41[nowpos41] ==1 and memory_change41[nowpos41]==4:
flavor[2]+=1;
if cpu_chanege41[nowpos41] ==2 and memory_change41[nowpos41]==8:
flavor[5]+=1;
if cpu_chanege41[nowpos41] ==4 and memory_change41[nowpos41]==16:
flavor[8]+=1;
if cpu_chanege41[nowpos41] ==8 and memory_change41[nowpos41]==32:
flavor[11]+=1;
if cpu_chanege41[nowpos41] ==16 and memory_change41[nowpos41]==64:
flavor[14]+=1;
del cpu_chanege41[nowpos41]
del memory_change41[nowpos41]
else:
nowpos41+=1
if nowpos21>=len(cpu_chanege21) and nowpos41>=len(cpu_chanege41) and len(cpu_chanege11)>0 and nowpos<len(cpu_chanege11) and 0<=(full_cpu - cpu_chanege11[nowpos]) and 0<=(full_memory-memory_change11[nowpos]):
full_cpu-=cpu_chanege11[nowpos-len(cpu_chanege41)-len(cpu_chanege21)]
full_memory-=memory_change11[nowpos-len(cpu_chanege41)-len(cpu_chanege21)]
if cpu_chanege11[nowpos] ==1 and memory_change11[nowpos]==1:
flavor[0]+=1;
if cpu_chanege11[nowpos] ==2 and memory_change11[nowpos]==2:
flavor[3]+=1;
if cpu_chanege11[nowpos] ==4 and memory_change11[nowpos]==4:
flavor[6]+=1;
if cpu_chanege11[nowpos] ==8 and memory_change11[nowpos]==8:
flavor[9]+=1;
if cpu_chanege11[nowpos] ==16 and memory_change11[nowpos]==16:
flavor[12]+=1;
del cpu_chanege11[nowpos]
del memory_change11[nowpos]
else:
nowpos = nowpos +1 ; #turn to the next position
#########use 4:1 first ,then 2:1, then 1:1
elif full_memory/(full_cpu*1.0)>=3 :
print("444")
#decide weather the n can put into servel
if len(cpu_chanege41)>0 and nowpos41<len(cpu_chanege41) and 0<=(full_cpu - cpu_chanege41[nowpos41]) and 0<=(full_memory-memory_change41[nowpos41]):
full_cpu-=cpu_chanege41[nowpos41]
full_memory-=memory_change41[nowpos41]
if cpu_chanege41[nowpos41] ==1 and memory_change41[nowpos41]==4:
flavor[2]+=1;
if cpu_chanege41[nowpos41] ==2 and memory_change41[nowpos41]==8:
flavor[5]+=1;
if cpu_chanege41[nowpos41] ==4 and memory_change41[nowpos41]==16:
flavor[8]+=1;
if cpu_chanege41[nowpos41] ==8 and memory_change41[nowpos41]==32:
flavor[11]+=1;
if cpu_chanege41[nowpos41] ==16 and memory_change41[nowpos41]==64:
flavor[14]+=1;
del cpu_chanege41[nowpos41]
del memory_change41[nowpos41]
else:
nowpos41+=1
if nowpos41>=len(cpu_chanege41) and len(cpu_chanege21)>0 and nowpos21<len(cpu_chanege21) and 0<=(full_cpu - cpu_chanege21[nowpos21]) and 0<=(full_memory-memory_change21[nowpos21]):
full_cpu-=cpu_chanege21[nowpos21]
full_memory-=memory_change21[nowpos21]
if cpu_chanege21[nowpos21] ==1 and memory_change21[nowpos21]==2:
flavor[1]+=1;
if cpu_chanege21[nowpos21] ==2 and memory_change21[nowpos21]==4:
flavor[4]+=1;
if cpu_chanege21[nowpos21] ==4 and memory_change21[nowpos21]==8:
flavor[7]+=1;
if cpu_chanege21[nowpos21] ==8 and memory_change21[nowpos21]==16:
flavor[10]+=1;
if cpu_chanege21[nowpos21] ==16 and memory_change21[nowpos21]==32:
flavor[13]+=1;
del cpu_chanege21[nowpos21]
del memory_change21[nowpos21]
else:
nowpos+=1
if nowpos21>=len(cpu_chanege21) and nowpos41>=len(cpu_chanege41) and len(cpu_chanege11)>0 and nowpos<len(cpu_chanege11) and 0<=(full_cpu - cpu_chanege11[nowpos]) and 0<=(full_memory-memory_change11[nowpos]):
full_cpu-=cpu_chanege11[nowpo]
full_memory-=memory_change11[nowpos]
if cpu_chanege11[nowpos] ==1 and memory_change11[nowpos]==1:
flavor[0]+=1;
if cpu_chanege11[nowpos] ==2 and memory_change11[nowpos]==2:
flavor[3]+=1;
if cpu_chanege11[nowpos] ==4 and memory_change11[nowpos]==4:
flavor[6]+=1;
if cpu_chanege11[nowpos] ==8 and memory_change11[nowpos]==8:
flavor[9]+=1;
if cpu_chanege11[nowpos] ==16 and memory_change11[nowpos]==16:
flavor[12]+=1;
del cpu_chanege11[nowpos]
del memory_change11[nowpos]
else:
nowpos = nowpos +1 ; #turn to the next position
else:
break
servel.append(flavor)
full_computer=full_computer+1
print("第几台数")
print(full_computer)
print(servel) #one computer is over
flavor=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
full_cpu = full_cpu1
full_memory = full_memory1
nowpos = 0
nowpos21 = 0
nowpos41 = 0
print(full_computer)
return servel
a=knapsack_version3([10,10,10,10,10,0,10,0,0,0,10,0,0,0,10],[56,128],1)
print(a)
|
bb3020a779d42ef4c6481c5f6d505268a89bb3ad | EmlynLXR/Python | /str2float.py | 652 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
DIGITS={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def char2num(sss):
return DIGITS[sss]
def fun(x,y):
return x*10+y
def count(s):
i=0
while s[i]!='.':
i=i+1
return len(s)-i-1
def str2float(s):
s1 = s.replace('.','')
ss=reduce(fun,map(char2num,s1))
i=0
j=count(s)
num=1
while i<j:
num=num*10
i=i+1
ss=ss/num
return ss
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!') |
7dfa539769a7dbae44f573a0906c9d544a1d4b68 | ja123oconnor/ProjectsByJanine | /chatbot.py | 1,119 | 4.1875 | 4 | print("Hi, my name is Robin the Robot. I love to talk to new people.")
name = input("What is your name? ")
print("Hello",name,"it is very nice to meet you!")
year = input("I'm terrible with remembering the date, what year are we in please? ")
print("Yes, I think you are right, thanks!")
myage = input("Can you guess my age? ")
print("Yes that is right! I am", myage, "years old. I was born in", int(year)-int(myage),".")
age = input("How old are you? ")
if age > myage:
print("You are older than me, great!")
else:
print("You are younger than me, great!")
food = input("My favourite food is Jamaican food. What is your favourite food? ")
print("Yummy! I love",food,"too.")
animal = input("What is your favourite animal? ")
print("Cool! I wonder if a",animal,"eats Jamaican food and",food,"too! lol")
feeling = input("How are you feeling today? ")
print("Why are you feeling",feeling,"? ")
reason = input("Please share: ")
print("I understand. Thanks for sharing.")
print("I am feeling a bit tired, I think it is time for my nap.")
print("It was nice talking to you, I'll talk to you tomorrow.")
print("Bye", name,".")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.