blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9702aa5c42159a682572f88aee7dc4594e7cae94 | meoclark/Data-Science-DropBox | /Build Chatbots/Search&Find.py | 456 | 4.15625 | 4 | import re
# import L. Frank Baum's The Wonderful Wizard of Oz
oz_text = open("the_wizard_of_oz_text.txt",encoding='utf-8').read().lower()
# search oz_text for an occurrence of 'wizard' here
found_wizard = re.search("wizard",oz_text)
print(found_wizard)
# find all the occurrences of 'lion' in oz_text here
all_lions =... |
acb53bfe77024fe322a74f220475f7ec3a397637 | Flexime/Python | /test.py | 245 | 3.671875 | 4 | import random as rand
rows, cols = (5, 5)
arr=[]
for i in range(rows):
col = []
for j in range(cols):
col.append(rand.randrange(7)) # 0 если надо 2д масс из нулей
arr.append(col)
print(arr)
print(arr[1:]) |
0c7427837a4994839f2e95fbab138c83d3bf6889 | sleevewind/practice | /day02/operator.py | 1,177 | 4.3125 | 4 | # 在python3里,整数除法的结果是浮点数
# 在python2里,整数除法的结果是整数
print(6 / 2) # 3.0
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 整除运算,向下取整 3
# 幂运算
print(3 ** 3)
print(81 ** 0.5)
a = b = c = d = 10
print(a, b, c, d)
o, *p, q = 1, 2, 3, 4, 5, 6 # *p 代表可变长度
print(o, p, q) # 1 [2, 3, 4, 5] 6
# 比较运算符在字符串里的使用
# 根据各个字符的编码值逐位比较
... |
c244d4afcf121047a50b8b2c9ed1cbd7f982396e | MatthewKosloski/starting-out-with-python | /chapters/06/12.py | 447 | 3.859375 | 4 | # Program 6-12
# Reads the values in video_times.txt
# file and calculates their totals.
def main():
video_file = open('video_times.txt', 'r')
total = 0.0
count = 0
print('Here are the running times for each video:')
for line in video_file:
run_time = float(line)
count += 1
print('Video #', count, ':... |
ef661218988bbcbbe410015bb700b768661a1cc4 | kapilbhudhia/python | /PGP-AI/SavingsAccount.py | 611 | 3.53125 | 4 | from Account import Account
class SavingsAccount(Account):
def __init__(self, minimumBalance, **accountArgs):
self.MinimumBalance = minimumBalance
super().__init__(**accountArgs)
def AccountInfo(self):
accountInfo = super().AccountInfo()
savingsInfo = "\tMinimum Balance: %s" ... |
ee5a4f30b98a31942e0a61d16899cbbcdc9960e8 | lucasportella/learning-python | /python-codes/m2_curso_em_video_estruturas_de_controle/ex060.2.py | 130 | 3.875 | 4 | from math import factorial
num = int(input('Diga o valor p/ saber o fatorial: '))
print('Calculando... {}'.format(factorial(num))) |
6d979408158136f2c86686d3c4288ff7d8ebde73 | bopopescu/TelPractice1 | /22_BreakContinuePass.py | 336 | 3.859375 | 4 | x=int(input("How many candies you want"))
available=10
i=1
while i<=x:
if i>available:
print("Out of stock")
break
print("candy",i)
i+=1
for k in range(1,101):
if k%3==0 or k%5==0:
continue
print(k)
print("Bye")
for j in range(1,101):
if j%2==0:
pass
else:
... |
8b7c0dbbdbae4f3f7ad833921d82e7c6af360f58 | nikolaouyiannis/Python-School-App | /moduleCourses.py | 2,555 | 4.4375 | 4 | class Courses:
"""This class represents a language course"""
coursesInfo = []
dummyCoursesInfo = []
#these lists will be filled with class objects
def __init__(self, c_title, c_language, c_description, c_type):
self.c_title = c_title
self.c_language = c_language
self.... |
2b818acf8faf1f3e04aaa449a14fb31c8d25ba9d | lucas-ferreira1/PythonExercises | /POO/biblioteca.py | 2,377 | 4 | 4 | from livros_class import livros_class #import the class that was created
#Book's definition
livro_0 = livros_class("Scott Pilgrim")
livro_1 = livros_class ("Maus")
livro_2 = livros_class("Pilulas Azuis")
livro_3 = livros_class("Tintin no mundo sovietico")
livro_4 = livros_class("Alice no pais das maravilhas")
livro_5 ... |
4326e8da1c32e07197cf7cec167b52b6aab5e706 | Koemyy/Projetos-Python | /PYTHON/Python Exercícios/2 lista de exercicios/ex45.py | 88 | 3.828125 | 4 | n=2
c = int(input())
while(n<=c):
z=n**2
print(f"{n}^{2} = {z}")
n+=2 |
f27b5127b91e176f5b411b00886bff6f3aac0246 | blhelias/dataStructure | /Heap/Heap.py | 3,267 | 4.28125 | 4 | import math
class Heap:
""" Tas complexite moyennne d'une opération: O(log(n))
complexité dans le pire cas: O(n) -> a cause
du dictionnaire.
"""
def __init__(self, items) -> None:
self.n = 0
self.heap = [] # index 0 will be ignored
# len(self.heap) = 1... |
f66d8af86c8eda29800b419718de0930c972e39d | Armanchik74/practicum-1 | /38.py | 1,053 | 4.09375 | 4 | """
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: Задание 38.py
Автор: 2020 © А.С. Манукян, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 17/12/2020
Дата последней модификации: 17/12/2020
Описание: Решение задачи № 38
#версия Pyth... |
f9edbe2de92f58ae039b2e14a485e67531d3b872 | robin-qu/Movie-Recommender | /dataOverview/frequent_appeared_genres_of_high_rated_movies.py | 927 | 3.8125 | 4 | """
Movie Recommender Project
Hongbin Qu
This program uses SQL query statement to find out
the top 20 frequent appeared genres in high rated movies(>4)
"""
import sqlite3
connection = sqlite3.connect("/Users/haofang/Desktop/546project/546Data.db")
cursor = connection.cursor()
cursor.execute("select count(a.movieId) a... |
a596ff0fa9f307fbeca97892f3bee348a7f5a8a1 | lakshyatyagi24/daily-coding-problems | /python/163.py | 1,479 | 4.40625 | 4 | # -------------------------
# Author: Tuan Nguyen
# Date created: 20191023
#!163.py
# -------------------------
"""
Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.
The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should return 5 + 3 = 8.
Fo... |
12a67445b769e5bbc41350ba855df7a4a2fdf6dd | panghanwu/matplotlib_demo | /17_animation.py | 618 | 3.703125 | 4 | from matplotlib import animation
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x)) # suffix "," means tuple
def action(t):
# update values of y at t
line.set_ydata(np.sin(x+t/50))
return line,
def init():
# upda... |
b2dbb97b25e680d2d75a15d031671a813da14ab8 | ToWorkit/Python_base | /深度学习/one_day/BUG解决.py | 369 | 3.765625 | 4 | import numpy as np
# 随机5个高斯变量
# 秩为1 的数组
a = np.random.randn(5)
print(a)
# 矩阵的长度
print(a.shape)
# 转置
print(a.T)
print(np.dot(a, a.T))
# 1 * 5 的矩阵
a = np.random.randn(5, 1)
print(a)
# 注意看区别
print(a.T)
# 矩阵的乘积
print(np.dot(a, a.T))
# 与上面对比,写时不要省略 1
a = np.random.randn(1, 5)
print(a)
|
fa638f7a7978c213255b6c934c6adffc54a55cf8 | Amiao-miao/all-codes | /month01/day13/exercise01.py | 1,201 | 4.15625 | 4 | """
创建图形管理器
1. 记录多种图形(圆形、矩形....)
2. 提供计算总面积的方法.
满足:
开闭原则
测试:
创建图形管理器,存储多个图形对象。
通过图形管理器,调用计算总面积方法.
"""
class FigureManager:
def __init__(self):
self.__all_figure=[]
def add_figure(self,figure):
if isinstance(figure,Figure):
self.__all_figure.app... |
4b844d1054c79e33866630e87c73e13228c02eef | ChristianR21/CS-490-Deep-Learning | /Lab 1 Q5.py | 3,062 | 4.28125 | 4 | #Chrisitan Rodas
#490-0003
#Question 5
#This is a management program that utililizes class
#The base class is the AMS and that sets basic information that can be inherited by other classes
#The Employee class sets the hourly wage and job position of an employee.
#The Passenger class uses the information from the ... |
4f33310e0bf526d108bf516c1036c8ac76f54b5c | mmoore410/holbertonschool-higher_level_programming | /divide_and_rule/h_reverse_str.py | 598 | 3.8125 | 4 | import threading
class ReverseStrThread(threading.Thread):
sentence = ""
total_count = 0
current_count = 0
def __init__(self, word):
threading.Thread.__init__(self)
self.__order = ReverseStrThread.total_count
ReverseStrThread.total_count += 1
if type(word) != str:
... |
7c0d5151345f9fdc4b313cbc3b52ab9032655826 | s-surineni/atice | /hacker_rank/greedy/max_min.py | 935 | 3.640625 | 4 | # https://www.hackerrank.com/challenges/angry-children/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=greedy-algorithms
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxMin function below.
def maxMin(k, arr):
arr.sort(... |
8f4b0565637f5c7ee21fd407d5e05a4af868631c | lyh-git/bookshop | /charrobot/DEMO01/CS1/client.py | 1,149 | 3.515625 | 4 | import socket # 导入 socket 模块
# 客户端
def client():
s = socket.socket() # 创建 socket 对象
s.connect(('127.0.0.1', 8715))
print("成功连接服务端,请选择服务")
while True:
print("1,聊天机器人,2.中文分词,3.情感分析,4.退出")
target=input()
if target=="4":
return
if target=="1":
whil... |
178ad67e5678523a3be649cd8a4058456b140569 | Pratyaksh7/Dynamic-Programming | /Longest Common Subsequence/Problem5.py | 767 | 3.703125 | 4 | # 5. Program to find Minimum number of Insertions and deletions to convert 1st string to 2nd string
def lcs(X, Y, n, m):
for i in range(n+1):
for j in range(m+1):
if i==0 or j==0:
t[i][j] = 0
for i in range(1, n+1):
for j in range(1, m+1):
if X[i-1] == Y... |
e927a66967ae894e84226717a0048e66ffb844a8 | tsukumonasu/PythonLambda | /LambdaTest.py | 312 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)
for i in range(1,11):
print "fibo引数%d=%d" % (i, fib(i))
# 読みやすく
for i in range(1,31):
print "FizzBuzz引数%d=%s" % (i, (lambda g:g(3,'Fizz') + g(5,'Buzz') or i)(lambda j,s:''if i%j else s)) |
35794755b5d481aabcdbffb23ed925484db07b28 | narru888/PythonWork-py37- | /進階/演算法/排序/Quick_Sort(快速排序).py | 1,113 | 4.09375 | 4 | def quick_sort(collection):
"""
快速排序法:
- 時間複雜度:Ο(n log n)
- 穩定性:不穩定
- 介紹:
是先在序列中找出一個元素作為支點(pivot),然後想辦法將比支點的元素移動到支點元素的左邊,比支點大的元素移動到支點元素的右邊,
接著再用同樣的方法繼續對支點的左邊子陣列和右邊子陣列進行排序。
"""
length = len(collection)
if length <= 1:
return collection
else:... |
ec9de5a5538ccf1e2b2bac07bdad9346237470ee | whoiswentz/numerical-analysis | /numericalanalysis/vector.py | 596 | 3.546875 | 4 | class Vector:
def __init__(self, vector):
self._vector = vector
self._len = len(vector)
@property
def shape(self):
return self._shape
@property
def vector(self):
return self._vector
def __repr__(self):
return str(self._vector)
def __str__(self):
... |
12506e99de996782851437c2d397af32ed7df569 | sfcpeters/CTI110 | /M4T1_SalesPrediction_PetersM.py | 469 | 3.75 | 4 | #CTI 110
#M4T1-Sales Prediction
#Michael Peters
#13 November 2017
#projected annual profit
totalSales=float(input('Enter Projected Sales: '))
#projected annual profit is 23%
annualProfit = totalSales * .23
#projected profit is rounded to the second decimal place
print("Projected Annual Profit is:" ... |
efb31c48ccc34b75ea02215922e32184dc3658f1 | lucas54neves/urionlinejudge | /src/1006.py | 200 | 3.96875 | 4 | # -*- coding: utf-8 -*-
A = float(input())
B = float(input())
C = float(input())
P1 = 2.0
P2 = 3.0
P3 = 5.0
MEDIA = (A * P1 + B * P2 + C * P3) / (P1 + P2 + P3)
print("MEDIA = {:.1f}".format(MEDIA))
|
afdf4a630ffbba7aa195961297135b598c4feab1 | italoohugo/Python | /1UNIDADE/Lista4/Q5.py | 217 | 3.9375 | 4 | print('Programa Calculo do ano bissexto')
ano = float(input('Digite o ano: '))
if (ano % 4 == 0) and (ano % 100 == 0) or (ano %400 == 0):
print('Este ano é bissexto')
else:
print('Este ano não é bissexto') |
4f9330b3e37d6a639622ce5c564c6d208b334b38 | jzferreira/algorithms | /algorithms/sort/python/selectionsort.py | 385 | 3.8125 | 4 | #!/bin/python3
from sort_tools import generate_random_list
def selection_sort(a):
for i in range(len(a)):
current = i
for j in range(i+1, len(a)):
if (a[current]) > a[j]:
current = j
a[i], a[current] = a[current], a[i]
return a
values = generate_r... |
36bdfff9c89079a9675e119ffb2bce4f70c22d6c | Man1ish/derivativeinpython | /example17.py | 213 | 4.03125 | 4 | # Example 17: Find the derivative of the trigonometric function f(x) = sin2x using the limit definition
import sympy as sp
x = sp.symbols('x')
f = sp.sin(2*x)
der = sp.diff(f,x)
print(der)
# output : 2*cos(2*x) |
989d351bb9a4f9359df8f2c5c1ebe7f07dceb384 | razak02/python-challenge | /PyBank/main.py | 2,813 | 3.8125 | 4 | # Import the libraries
import csv
import os
# Initiatilize the variables used in the program. Initialize integers = 0 and strings = "".
# Initialize
current_value = 0
prior_value = 0
max_profit=0
max_profit_month = " "
max_loss = 0000000
average_PnL = 0
numRows =0
total = 0
numRows = 0
greatest_inc_pr=0
grea... |
b8b4847e06fa41013762a1ab7185fbdd8e477c5d | hhe0/Leetcode | /Easy/0001-0099/0058/python/Solution.py | 456 | 3.5625 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
i = len(s) - 1
start = False
res = ''
while i >= 0:
if s[i] != ' ':
start = True
res += s[i]
elif start:
... |
f9fc335dc34c12745dec8e1ee212b022f9196aa8 | Inquizarus/pyroch | /src/uplink.py | 768 | 3.796875 | 4 | """
The uplink is the way robots communicate with satellites
"""
class Uplink(object):
satellite = None
override_missing_satellite = False
def __init__(self, satellite=None):
self.satellite = satellite
def is_position_clear(self, posX, posY):
if self.satellite is not None:
... |
6bd632abe0953c859971e7e74ef853ee4bb7a910 | eduardogomezvidela/Summer-Intro | /10 Lists/Excersises/24.py | 470 | 3.8125 | 4 | #adder up to first even number
list = [1, 35, 7, 5, 11, 6, 7, 3, 4, 6, 8, 10, 11] #1 + 35 + 7 + 5 + 11 == 59
adder = 0
new_list = []
for num in list:
new_list.append(num%2)
up_to = (new_list.index(0)) #Gets up to what number we will add (even number)
counter = 0
answer = 0
for num in list: ... |
7e87e838d3ed4ab27d76f4d1d359c290a198da28 | in6days/CodingBat-Python-Solutions | /Logic-2.py | 3,423 | 4.4375 | 4 | #Medium boolean logic puzzles -- if else and or not
#We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big
# bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.
# This is a little harder than it looks a... |
8262cc64c430ce9e54c87066c2f9c1d87110bf31 | jokemanfire/test_for_python | /web_client/didianchaxun.py | 1,514 | 3.546875 | 4 | # -*- coding:utf-8 -*-
# 使用百度API查询吃饭地点
from urllib.request import urlopen
from urllib.parse import quote
import json
def APIlink(link):
APIresult = urlopen(link).read()
return APIresult
def main():
link = "http://api.map.baidu.com/place/v2/search?"
link3 = "http://api.map.baidu.com/place/v2/suggesti... |
ed8662f10f2e3e8da4d06025447f8f45f21dcbc1 | molendzik/AdventOfCode2020Python | /Day 4/Solution 7/main.py | 2,055 | 3.59375 | 4 | #read file and convert content to a list of lines
with open("input.txt", "r") as file:
data = file.readlines()
#define function that will merge correct strings and remove empty ones
def merge_items(list):
first_index = list.index(" ")
list.remove(" ")
if first_index < len(list) - 1 and " " in list:
... |
3990466f9db63e85f9c63f55fb2fe6f754d91a39 | Ahead180-103/ubuntu | /python/shell.py/02_string.py | 349 | 4.0625 | 4 | #!/usr/bin/python3
'''
输入任意字符串,判断这个字符串是不是回文
回文是指中心对称的文字
如:
上海自来水来自海上
abcba
'''
s=input("请输入字符串:")
reverse_string = s[::-1] #把字符反过来
print(reverse_string)
if reverse_string == s:
print(s,"是回文")
else:
print(s,"不是回文")
|
f71095b64b8ab9df1cb036aa3a18ad1cc10ec4b9 | vaishali-khilari/COMPETITIVE-PROGRAMMING | /leetcode/Sorted matrix .py | 1,139 | 4.4375 | 4 | Given an NxN matrix Mat. Sort all elements of the matrix.
Example 1:
Input:
N=4
Mat=[[10,20,30,40],
[15,25,35,45]
[27,29,37,48]
[32,33,39,50]]
Output:
10 15 20 25
27 29 30 32
33 35 37 39
40 45 48 50
Explanation:
Sorting the matrix gives this result.
Example 2:
Input:
N=3
Mat=[[1,5,3],[2,8,7],[4,6,9]]
Output:
1 2 ... |
ff4ba374d423f15a1fc1cf541abdbd8b414fb7b3 | cmdbdu/little | /piglatin.py | 813 | 3.703125 | 4 | #coding:utf8
import string
# 接受输入的字符串
# 判断是否是单词
# 是否有辅音
# 组词
def piglatin():
self_sound = ['a', 'e', 'i', 'o', 'u']
s = raw_input('Input something please!\n')
words = s.split()
new_words = ''
for word in words:
tmp_word = word.lower()
position = []
for i in range(len(tmp_... |
a52f62da1239defdfdf3bfc2c4816205ac9c7e34 | mintisan/dsp-examples | /machine-learning-with-signal-processing-techniques/auto-correlation_in_python.py | 1,308 | 3.640625 | 4 | # http://ataspinar.com/2018/04/04/machine-learning-with-signal-processing-techniques/
# The auto-correlation function calculates the correlation of a signal with a time-delayed version of itself.
# The idea behind it is that if a signal contain a pattern which repeats itself after a time-period of \tau seconds,
# there... |
61bef90211ffd18868427d3059e8ab8dee3fefde | kami71539/Python-programs-4 | /Program 25 Printing text after specific lines.py | 303 | 4.15625 | 4 | #Printing text after specific lines.
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text) |
4099fd2a5412344e11f6270d1c751d7d7cb4b7d1 | junyoung-o/PS-Python | /by date/2021.02.18/1874.py | 1,662 | 3.703125 | 4 | from typing import Sequence
n = int(input())
sequence = []
result = None
candidate = None
class Stack():
def __init__(self):
self.s = []
self.size = 0
def is_empty(self):
if(self.size == 0):
return True
return False
def push(self, target):
self.s.appe... |
4eb376be35f50b426d5c180f806e58d060ae7911 | Jingleolu/learn-python | /day3/triangle.py | 283 | 3.578125 | 4 | """
判断输入边长能否构成三角形,如果能则计算出三角形的周长和面积
"""
a, b, c = map(int, input('请输入三条边长:').split())
if a+b > c and a+c > b and b+c > a:
print('三角形的周长为%d' % (a+b+c))
else:
print('不能组成三角形') |
6e49f8327734e7d9ae784662a9fdf8bd827f34ae | coderlzy/python- | /比赛训练7天/day1字符串/批量替换字符串.py | 229 | 3.59375 | 4 | while True:
try:
str1=input("请输入一个字符串:")
#手动替换
list1=list(str1)
for i in range(len(list1)):
if list1[i] is " ":
list1[i]="%20"
print("".join(list1[i]),end="")
except EOFError:
break
|
af6181886e558f7277bc98cc2f655e40cddce358 | GuilhermeEsdras/Estrutura-de-Dados | /em C/Exercícios Resolvidos/Exercícios URI Resolvidos/Lista Uri 1 - Revisao de Algoritmos/2415 - Consecutivos.py | 378 | 3.515625 | 4 | # -*- coding: utf-8 -*-
N = int(input())
num = [int(x) for x in input().split()]
maior_cont = 0
cont = 0
numero_anterior = 0
for i, v in enumerate(num):
if v == numero_anterior or i == 0:
numero_anterior = v
cont += 1
if cont >= maior_cont:
maior_cont = cont
else:
... |
bdfa7c4a9cb85fe1bd2bb4b073f9fb6de6ff85c0 | aleri-a/Artificial-Intelligence_MDH | /1.2 GBF Astar/main.py | 4,529 | 3.546875 | 4 | #A* abnd greedy-best first
# Malaga to Valladolid
'''
Implementation:Order the nodes in the stack in decreasing order of desirability
greedy best ->f(n) = h(n)
A*-> f(n) = g(n) + h(n)
pazi g(n) ti je duzina prethodnih puteva + duzina novi put
'''
from queue import PriorityQueue
import time
class MyPriorityQu... |
c75ff5bce9ac25b82fdae6d6d568b3682a5c58b8 | Agnes-Wambui/ProjectEuler | /Project Euler/P14:Longest Collatz sequence.py | 704 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 27 16:14:45 2018
@author: thejumpingspider
"""
maximum_length = 0
for i in range (10,1000000):
j = i
collatz_sequence = []
while j > 1:
collatz_sequence.append(j)
if j%2 == 0:
j = j/2
coll... |
9d8889ea4a3c3568983cd986075c10bc214673a6 | kaczorrrro/CS231N-2017-Spring | /assignment1/cs231n/classifiers/softmax.py | 4,248 | 3.703125 | 4 | import numpy as np
import math
from random import shuffle
from past.builtins import xrange
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy arr... |
ddb4d8fe8179c162014a5e7d2adc2739fe389f2b | changooman/HeyThatsMyFish | /version-three-tehuacana/Fish/Player/strategy.py | 7,351 | 4.125 | 4 | from Fish.Common.game_tree import GameTreeNode
class Strategy():
"""A Fish game-playing strategy that can place penguins
and make moves for any player in the game.
"""
def make_placement(self, state):
"""Places a penguin on the game board for the current player.
Attempts to place in th... |
4cf77b7fd2d6f7dbce6630089dbda1fb98e07a70 | ChrisWaites/data-deletion | /src/desc_to_del/clean_data.py | 8,683 | 3.5625 | 4 | import numpy as np
import pandas as pd
# documentation
# output: clean data set, remove missing values and convert categorical values to binary, extract sensitive features
# for each data set 'name.csv' we create a function clean_name
# clean name takes parameter num_sens, which is the number of sensitive attributes t... |
3d064e6585be43f39b01bc2b7ffcf7a32a08379b | Sleeither1234/t10-HUATAY.CHUNGA | /huatay/CLI2.py | 4,498 | 4.03125 | 4 | #ejercicio 02
# se muestra las funciones dependiendo la opcion elejida
def suma():
#asignacion de valores dentro de la funcion
primer_numero=libreria.validar_numero(input("Ingrese el primer valor "))
segundo_numero=libreria.validar_numero(input("Ingrese el segundo valor"))
#realizacion del calculo de lo... |
5c35aa45664aed8a1595adf8183c11b4d95580c7 | Mohit130422/python-code | /35 reverse.py | 229 | 3.625 | 4 | #value rverse
def main():
n=int(input("enter no"))
rev=0
rem=0
while (n>0):
rem=n%10
rev=rev*10+rem
n = n//10
print("Rverse=",rev)
if __name__=="__main__":
main()
#run
|
e69781477eeb9c745e6f8edd7d8a6c6688351c3d | imjoung/hongik_univ | /_WSpython/Python06_06_DictionaryEx03_최임정.py | 277 | 3.609375 | 4 | dic={'name':'imjoung','phone':'01089960000','birth':'1009'}
print("이름은 : %s 입니다."% dic['name'])
print("핸드폰 번호는 : %s 입니다."%dic['phone'])
print("생일은 : %s 입니다."%dic['birth'])
print("="*15)
a={1:'a',1:'b'}
print(a)
print("="*15) |
fddcf8759b274b5da713d52759c9b4894e3013d5 | JoachimIsaac/Interview-Preparation | /LinkedLists/23MergeKSortedLists.py | 1,587 | 4.34375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
"""
UMPIRE:
Understand:
--> So we are going to recieve an array of linked lists as our input?yes
--> Can we use extra space?
--> What do we return ? a sorted linked li... |
9caba39d4ee9df48e75b4dfceb85774fbdd80e43 | bakunobu/exercise | /1400_basic_tasks/chap_7/7_84.py | 290 | 3.671875 | 4 | from main_funcs import get_input
def count_pos(n:int, p:int=5) -> bool:
pos_count = 0
for _ in range(n):
a = get_input('Введите число: ', False)
if a >= 0:
pos_count += 1
if pos_count > p:
break
print(pos_count <= p) |
5035cb2fc2f7e9c501ed776f72f5f47d8ff3e141 | n0skill/AVOSINT | /libs/icao_converter.py | 2,913 | 3.78125 | 4 | base9 = '123456789' # The first digit (after the "N") is always one of these.
base10 = '0123456789' # The possible second and third digits are one of these.
# Note that "I" and "O" are never used as letters, to prevent confusion with "1" and "0"
base34 = 'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'
icaooffset = 0xA00001 # The... |
6ffe4602847aa9e88c13a41ba9fcba2d040ec53c | jfxugithub/python | /函数式编程/匿名函数.py | 679 | 4.15625 | 4 | #!/usr/bin/evn python3.5
# -*- coding: utf-8 -*-
#匿名函数访问每一个生成的0-9序列,将结果组合成一个list
print("匿名函数的使用:")
print("求取0-9的平方list:",list(map(lambda x:x*x,list(range(0,10)))))
'''
匿名函数的语法:
lambda 参数:表达式 #(表达式中的变量必须是参数中的,且表达式只能有一个)
lambda:表示匿名函数的关键字
x :表示入参
x*x :表示表达式
'''
#匿名函数也可以作为返回值赋值给变量
is_odd = lambda n : n % 2 ... |
68290a3beff7dd6825bea0d9aca023584c84ef84 | gslmota/Programs-PYTHON | /Exercícios/Mundo 2/ex060.py | 648 | 3.703125 | 4 | # Cadastro de Pessoas
tp = th = tm = 0
while True:
idade = int(input('Digite a sua idade:'))
sexo = ' '
while sexo not in 'FM':
sexo = str(input('Digite o seu sexo: ')).strip().upper()[0]
if idade >= 18:
tp += 1
if sexo == 'M':
th += 1
if sexo == 'F' and idade < 20:
... |
fb113957ae9d3359c436c5a578fafde8210888ba | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/sttbar001/question2.py | 694 | 4.09375 | 4 | money =0
cost =0
cost = eval(input("Enter the cost (in cents): \n"))
while money < cost:
money = (eval(input("Deposit a coin or note (in cents): \n")))+money
change = money-cost
if change!= 0:
print("Your change is:")
doll1 = int(change/100)
if doll1 >0:
print(str(doll1)+" x $1")
change ... |
61417cf678356138b1353b656347f8a137e139de | AKShaw/PyBot | /algorithms.py | 2,078 | 4.09375 | 4 | class check_sensors():
def __init__(self, sensor_distance):
self.sensor_distance = sensor_distance
#sensor_distance[0] = right sensor distance
#sensor_distance[1] = left sensor distance
#sensor_distance[2] = center sensor distance
"""def check_start(self):
if (self.senso... |
2b76d634811db9cd14c071b1e816378ac6f47d65 | August1s/LeetCode | /Linked List/No21合并两个有序链表.py | 1,437 | 3.90625 | 4 |
'''
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
l3 = ListNode(None)
head = l3
while l2 != None and l1 != None:
if l1.value <= l2.value:
l3.next = ListNode(l1.value)
l3 = l3.next
l1 = l1.next
else:
l3.next = ListNode(l2.va... |
966e601e4ee55ac1bdceada3e3660e2cd0259a19 | Julian-Chu/leetcode_python | /lintcode/lintcode788.py | 3,371 | 4 | 4 | class Solution:
"""
@param maze: the maze
@param start: the start
@param destination: the destination
@return: the shortest distance for the ball to stop at the destination
"""
def shortestDistance(self, maze, start, destination):
if not maze:
return -1
start_x ... |
32a67dfff86a5bd3f0ad48a18d084678e5b47590 | CamiloCardonaArango/python_seti | /Reto_3/clases.py | 936 | 3.859375 | 4 | """ Módulo que contiene las clases utilizadas para el reto de la semana 3"""
class Compuerta:
""" Clase principal de las compuertas """
def __init__(self, entrada_a, entrada_b):
""" Inicializa la clase compuertas """
self.entrada_a = entrada_a
self.entrada_b = entrada_b
class Compuert... |
a231ca976ee3feace2a2f184663a35ae470d70d3 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/patchcarrier/Lesson03/list_lab.py | 2,401 | 4.375 | 4 | #!/usr/bin/env python3
### Series 1 ###
print("\n-----------Beginning Series 1-----------")
fruit_list = ["Apples","Pears","Oranges","Peaches"]
print(fruit_list)
# Add a user specified fruit to the list
another_fruit = input("Specify another fruit: ")
fruit_list.append(another_fruit)
print(fruit_list)
# Print the f... |
297b183f237054fa5ba85b21a2b5bc29f454a2fd | umairnsr87/Data_Structures_Python | /1542A - odd set.py | 334 | 3.671875 | 4 | test = int(input())
for _ in range(test):
pairs = int(input())
nums = list(map(int, input().split()))
odd, even = 0, 0
for num in nums:
if num % 2 == 0:
even += 1
else:
odd += 1
flag = min(odd, even)
if flag<pairs:
print("NO")
else:
... |
eb0f36a43259a0137d6fbac318c80e3f8c8a3f89 | yogii1981/Fullspeedpythoneducative1 | /loginpage.py | 628 | 3.71875 | 4 | class User:
def __init__(self, username=None, password=None):
self.__username = username
self.__password = password
def username1(self):
self.__username = input('What is the username?')
def password1(self):
self.__password = int(input("Enter a password"))
def login(se... |
ab67df17f094a82af28132e27b5e3d87e36c426b | flaviojussie/Exercicios_Python-Inciante- | /EstruturaDeRepeticao - PythonBrasil/exec33.py | 285 | 3.59375 | 4 | cont = 1
soma = 0
maior = 0
temp = 1
while temp != 0:
temp = float(input('Temperatura %d: '%cont))
if temp > maior:
maior = temp
soma += temp
cont += 1
media = soma/cont
print('A maior nota registrada no periodo foi %d e a media geral foi %5.1f'%(maior, media)) |
5c881e7b343b5cac4080b6adc1e069b08f02c62d | piotrek9999/Mario | /SuperMarioDemo/SuperMarioDemo/classes/enemy.py | 1,591 | 3.875 | 4 | """ Class Enemy. """
import pygame as pg
from pygame import sprite
class Enemy(sprite.Sprite):
"""
This is a class for Enemy object.
Attributes:
image : The image of Enemy.
rect : The coordinates of Enemy.
last_direction : Last direction of Enemy horizontally.
counter : T... |
28e571bab5e55960e7c5e29137bf37db5fe0537b | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mrpgeo001/question1.py | 1,340 | 4.09375 | 4 | """Program for checking is strings are palindromes
Geoff Murphy
MRPGEO001
6 May 2014"""
string = input("Enter a string:\n")
def pal_check(string):
palindrome = 0 #Initial value of a. If a = 0, not a palindrome. If a = 1, the string is a palindrome.
... |
33374838a317e965f52ee1665a4cc5f9854427b2 | JiaXingBinggan/For_work | /code/tree/is_same_tree.py | 1,277 | 3.875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSameTree(self, p, q):
"""
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同... |
44429ba938831e52b43fa93fecba01e127d7d637 | heet-gorakhiya/Scaler-solutions | /Searching/Searching-2-AS_aggressive_cows.py | 3,562 | 3.96875 | 4 | # Aggressive cows
# Problem Description
# Farmer John has built a new long barn, with N stalls. Given an array of integers A of size N where each element of the array represents the location of the stall, and an integer B which represent the number of cows.
# His cows don't like this barn layout and become aggressive ... |
7c663ad0c8d254ad85132c26724ff9af30ec621c | dieforice/Unity_LeThanhCuong | /Session4/4.9/many squares.py | 312 | 3.53125 | 4 | from turtle import *
bgcolor("yellow")
speed(-1)
def draw_4_squares(sz):
color("blue")
pensize(2)
for _ in range(4):
for i in range(4):
forward(sz)
left(90)
right(90)
## draw 4 squares with same sizes sz
for n in range(6):
draw_4_squares(100)
left(15)
|
21cd4f4514397e1b044b7bca7a23f2e009947e0d | oliviagonzalez/caesar | /helpers.py | 803 | 3.875 | 4 | def alphabet_position(letter):
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for l in alphabet:
if l == letter.lower():
return alphabet.index(l)
return "error. input should be a single letter"
def get_letter_by_posit... |
040aeed610b90165c3ef16d6aaa14bf44b4da825 | RenataTNT/Python-OOP | /OOP_Task_2.py | 1,173 | 3.609375 | 4 | # Используя навыки работы с текстом, получите количество студентов GeekBrains со стартовой страницы сайта geekbrains.ru.
# У вас два пути решения:
# * использовать регулярные выражения (библиотеку re),
# * использовать библиотеку BeautifulSoup.
import os
import re
from bs4 import BeautifulSoup as BS
with ope... |
66dbe8a67a0a07a36eaf83e574e60aaebe5a4f4d | panok90/gb-lessons | /task-1.py | 553 | 4.375 | 4 | # Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
list = [1, "list", True, [1, 2], {1: 1, 2: 2}]
for item in li... |
10e2acf037d9baf5b3650bd8a8e2ad6dda20ee26 | pkuipers1/PythonAchievements | /Les05/shuffleAndReturn.py | 695 | 3.921875 | 4 | #Schrijf een functie die de letters van een woord willekeurig door elkaar schudt.
#Je mag deze code hiervoor hergebruiken.
#Bij het aanroepen van de functie moet je elk woord mee kunnen geven als argument.
#De functie moet het geschudde woord terug geven via een return.
#Roep de functie 3x aan met een ander woord en... |
bb6c715bb6d1dd259ca158345e13f5489f12ddaf | alirezaghey/leetcode-solutions | /python/path-with-maximum-gold.py | 2,008 | 4.28125 | 4 | # https://leetcode.com/problems/path-with-maximum-gold/
# Related Topics: DFS, Backtracking
# Difficulty: Medium
# Initial thoughts:
# Aside from the starting cell, each cell has at most three paths that go out of it
# (that's because we can't go back to our previous cell since we have already visited it).
# We ne... |
5cb6ad2533e4dbe68af6399b05c293f3bfc92bef | kimth007kim/python_choi | /Chap10/10_17.py | 410 | 3.984375 | 4 | from tkinter import *
mycolor="blue"
def paint(event):
x1,y1=(event.x-1),(event.y+1)
x2,y2=(event.x-1),(event.y+1)
canvas.create_oval(x1,y1,x2,y2,fill=mycolor)
def change_color():
global mycolor
mycolor="red"
window = Tk()
canvas= Canvas(window)
canvas.pack()
canvas.bind("<B1-Motion>",paint)
but... |
f90b6cdd7837dda28f05dd18902fc47fd304c20f | sitayebsofiane/cours-PYTHON | /divers/vetusté.py | 324 | 3.5625 | 4 | #coding:utf-8
def calcul_prix(anné_achat,coef,prix):
nbr=2019-anné_achat
while nbr>0:
nbr -=1
prix *=1-coef
return prix
a=int(input('entrez année d''achat '))
b=float(input('entrez coef '))
c=float(input('entrez prix '))
print('le prix qui sera rembousé est {}'.format(calcul_prix(a,b,c)))
|
2f9907ec41c94565a282c7e323dd14c04c28eda4 | sghosh1991/InterviewPrepPython | /LeetCodeProblemsMedium/17_letter_combination_phone_number.py | 1,121 | 3.71875 | 4 | """
https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
"""
class Solution(object):
def __init__(self):
self.results = []
self.mappings = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs... |
c4d1a247b25bbbab1e375d29e092fb00d7ac185c | qqewrt/python_lecture | /if_and_or_test.py | 164 | 3.8125 | 4 | a = 10
b = 13
if (a%2==0)and(b%2==0):
print('두 수 모두 짝수입니다.')
if (a%2==0)or(b%2==0):
print('두 수 중 하나 이상이 짝수입니다.') |
efd5f51c616973dc5d934562db033412acd92857 | everqiujuan/python | /day19/code/08_format.py | 1,280 | 3.828125 | 4 |
print()
"""
format方法
"""
#括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换
print("我叫{},今年{}!".format("张三",22))
#括号中的数字用于指向传入对象在 format() 中的位置
print("我叫{0},今年{1}!".format("张三",22))
print("我叫{1},今年{0}!".format("张三",22))
#
#在format()中使用关键字参数,它们的值会指向使用该名字的参数
print("我叫{name},今年{age}!".format(name="张三",age=22))
print(... |
45a47c79160a813d031597ea9435036b1c2a584a | cvhs-cs-2017/practice-exam-Narfanta | /Loops.py | 330 | 4.3125 | 4 | """Use a loop to make a turtle draw a shape that is has at least 100 sides and
that shows symmetry. The entire shape must fit inside the screen"""
import turtle
shape = turtle.Turtle()
shape.pu()
shape.left(90)
shape.forward(200)
shape.right(90)
shape.pd()
for i in range(150):
shape.forward(10)
shape.right(2.4... |
e88858c7d026401f5314490a29c412152f080b99 | abayirli/leetCodeProblems | /Challange_2020_June/03_TwoCity_Scheduling.py | 1,085 | 3.609375 | 4 | # LeedCode June Challange Day 3
# Two City Scheduling Problem
# Definition:
# There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0],
# and the cost of flying the i-th person to city B is costs[i][1].
# Return the minimum cost to fly every person to a city... |
4cce30096d92a65dd4c81a4beac8461525039239 | obiwan1715/python_practice | /word_by_letters.py | 167 | 4.15625 | 4 | def wordbreakdown(word):
for i in word:
print i
wordbreakdown("Ben")
#this was the old code before I made it a function
#word="Hello"
#for i in word:
#print i
|
42053fdee06ee51ea948310eab6dc8cf38fc41e7 | 2SEHI/Python-Programming-Test | /programmers/StrToNum.py | 381 | 3.765625 | 4 | '''
2021 카카오 채용연계형 인턴십
숫자 문자열과 영단어
https://programmers.co.kr/learn/courses/30/lessons/81301?language=python3
'''
def solution(answer):
g = {0:'zero', 1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
for key, value in g.items():
answer = answer.replace(value, str(key) )
... |
e46034dedbbd933b511799b870b5a7789415df08 | nbiadrytski-zz/python-training | /cookbook/class_object/calling_super.py | 177 | 3.734375 | 4 | class A:
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
super().__init__()
self.y = 2
a = A()
print(a.x)
b = B()
print(b.y)
|
4c03861d33f444543e0be19b79e5da66b82cab0b | interwho/Python-in-a-Week | /2 - Python Assignment #1 - New/Ex1.py | 1,535 | 4 | 4 | #Ex1.py
#
#Variables:
#name - name of the item
#price - price of the item
#tax - HST
#full - Full Price + HST
#inp - Temp. Reset Variable
#
#Input: Name and price of an item
#Output: Name, Price, HST, and Total Price of an item
#Process: Get data > verify > calculate > round final answers > print output
i... |
79fa6789bfafb6879d743cdee60c22ddfeb286d2 | KlimentiyFrolov/-pythontutor | /Занятие 6. Цикл while/задача 6.PY | 140 | 3.953125 | 4 | #http://pythontutor.ru/lessons/while/problems/seq_sum/
a = int(input())
b = 0
while a != 0:
b = b+a
a = int(input())
print(b)
|
7b2d88511b752ce1827756de7c4037dea274c72a | leungcc/pythonLxf | /FunctionalProgramming/sorted/basic.py | 576 | 4.09375 | 4 | #最基础用法
print( sorted([36, 5, -12, 9, 21]) )
#加入key命名关键字参数
print( sorted([36, 5, -12, 9, 21], key=abs) )
#字符串排序默认按照 ASCII 的大小比较的,由于'Z'<'a',所以大写字母Z会排在小写字母a前面
print( sorted(['bob', 'about', 'aaaaa', 'Zoo', 'Credit']) )
#现在我们提出排序要忽略大小写
print( sorted(['bob', 'about', 'aaaaa', 'Zoo', 'Credit'], key=str.lower) )
#要进行反向排序,... |
f35ff7a26908e26922a02b7fc3837dd5ae50b2d1 | Rachaelllwong/-mini-proj | /temp.py | 3,266 | 3.640625 | 4 | import matplotlib.pyplot as plt
import numpy as np
maze = []
walls = []
Start =[]
end = [47,1]
Dimensions = 51
with open(r"C:\Users\racha\OneDrive\Desktop\maze.txt", 'r') as f:
line = f.readlines() #reading the lines in the file
for element in line:
if element == 'True\n':
... |
31132e7c1660696bf6263bb26bec66c8227fcda4 | amritat123/function-questions | /maximum_from_nested_list.py | 264 | 3.546875 | 4 |
def max_num(num_1):
i=0
while i<len(num_1):
j=0
max=0
a=num_1[i]
while j<len(a):
if a[j]>max:
max=a[j]
j+=1
print(max)
i+=1
max_num([[2,4,6,81,0],[1,3,5,17,9]]) |
9796cad82a78cb5c764dc6614eedda75dd2ffdfb | Annatcaci/InstructiuneaFOR | /FOR 4.py | 111 | 3.6875 | 4 | n=int(input("Introduceti n"))
s=0
for i in range(1,n):
if (i%3==0) and (i%5==0):
s+=i
print(s) |
e9318639c8e27cebce108114f3da4d5ced52e97c | hellozepp/iotest-pyy | /iotestpy/oop/ooptest1.py | 611 | 4.0625 | 4 | class Person:
X=1
def __init__(self,id,name):
self.id=id
self.name=name
def xxx(self):
print(self.id)
def __str__(self):
return "str id: "+str(self.id)+" name: "+self.name
def __repr__(self):
return "repr id: " + str(self.id) + " name: " + self.name
if __n... |
e2c05ba1b49422a276903a770cedeead42b4f532 | larryv/CodeChef | /practice/easy/test.py | 432 | 4 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
test.py
Your program is to use the brute-force approach in order to find the Answer to
Life, the Universe, and Everything. More precisely... rewrite small numbers
from input to output. Stop processing input after reading in the number 42.
All numbers at input are integers of... |
a5a8da9c1b8d2bb88dfe2280bf260c7595eb6e99 | spencerhcheng/holbertonschool-higher_level_programming | /0x0B-python-input_output/6-from_json_string.py | 175 | 3.71875 | 4 | #!/usr/bin/python3
import json
def from_json_string(my_str):
"""
Returns an object represented by
a JSON string
"""
f = json.loads(my_str)
return(f)
|
f8795cf79763ee8f27f77eeb8937b20d550fcb1a | alirezaghey/leetcode-solutions | /python/maximum-xor-of-two-numbers-in-an-array.py | 971 | 3.515625 | 4 | from typing import List
class Solution:
# Time complexity: O(n) where n is the length of nums
# Space complexity: O(n)
def findMaximumXOR(self, nums: List[int]) -> int:
masks = [2**i for i in range(31, -1, -1)]
res = 0
trie = {}
for num in nums:
node = ... |
bfe0555eb1f8c2c7901e1883838081444727ac27 | SensibilityTestbed/indoor-localization | /gyro_step_online.r2py | 6,231 | 3.6875 | 4 |
"""
<Program Name>
pedometer.r2py
<Purpose>
This is a script for walking step counter. Analysis of the sensor data
from accelerometer to detect the walking / running steps. Introducing
pre-calibration stage, noise level threshold and moving average filter
to accurate step detection for difference devices.
... |
d3d6df0264cc316ead026be346635fa4e8aaffa8 | garona2dz/ChongChongChong | /shuJuJieGou/xuanZePaiXu.py | 1,145 | 3.53125 | 4 | list1 = [2, 4, 5, 3, 1]
list2 = [3, 2, 1, 5, 4]
def selection_sort1(deal_list):
i = 0
while i <= len(deal_list) - 2:
j = i + 1
while j <= len(deal_list) - 1:
if deal_list[i] >= deal_list[j]:
temp = deal_list[j]
deal_list[j] = deal_list[i]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.