blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
12fe069d7bb9afefb5009feeaaa6da81cc2b0093 | pspino/TP1-IFT725 | /prog/ift725/classifiers/linear_svm.py | 5,114 | 3.6875 | 4 | # Code adapté de projets académiques de la professeur Fei Fei Li et de ses étudiants Andrej Karpathy, Justin Johnson et autres.
# Version finale rédigée par Carl Lemaire, Vincent Ducharme et Pierre-Marc Jodoin
import numpy as np
def svm_naive_loss_function(W, X, y, reg):
"""
Structured SVM loss function, nai... |
6e9d3e1b2d3dd5f5316ee6595aa5e0a17344d770 | MrRabbit0o0/LeetCode | /python/55.py | 472 | 3.84375 | 4 | # coding: utf8
class Solution(object):
def canjump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return True
last = len(nums) - 1
i = last - 1
while i >= 0:
if nums[i] + i >= last:
last = i... |
afde39773401856fb22261dde1ce1544dd49c786 | sramyar/algorithm-problems | /bfs.py | 384 | 3.59375 | 4 | from graph import Graph
def bfs(Graph: G, start = 0):
seen = [start]
q = [start]
while len(q)>0:
new = q.pop(0)
for node in G.outEdges(new):
if node not in seen:
q.append(node)
seen.append(node)
return
G = Graph(5)
G.addEdge(0,1)
G.addEdge(... |
0c1c77832b7d54f212b803748e1a5d98547045c3 | ldwhyzy/flask_tutorial | /samples/thought/arguments__position_keyword.py | 1,798 | 3.984375 | 4 | '''
位置参数
可变参数(收集任意多基于位置或关键字的参数)
func(*arg), func(**kw), func(*arg, **kw)
#命名关键字参数func(posi, *arg, keyword_only, **kw)
#函数定义时keyword_only必须在变长参数之后,关键字参数之前。函数调用时key_word必须以关键字赋值,不能与默认参数混淆。
#func(a, *b, c, **d) func(1, 2, c=999)
#name=value的形式,
#在调用时代表关键字参数,调用时只有关键字参数和非关键字参数之分。
#在def定义时代表默认值参数
#参数顺序
#函数调用中,参数出现顺序:任... |
ca8b5cb08a90f7a48cd3a1e047b624f84b1be329 | Yusful33/pythonforeverybody | /MomAndSon.py | 210 | 4.09375 | 4 |
question = input("Are you a child or mom? ")
if 'child' in question:
print('Your mom loves you')
if question == 'mom' or question == 'Mom':
print('Your son loves you')
print('You\'re so lucky')
|
5910b77f5d44f90b64092ce53952db08f77909e4 | ksy37667/Algorithm-study | /algorithm_PS/BEAKJOON/disjoint-set/1717.py | 686 | 3.578125 | 4 | n, m = map(int, input().split(' '))
example = dict()
rank = dict()
def find(num):
if example[num] != num:
example[num] = find(example[num])
return example[num]
def union(num1, num2):
root1 = find(num1)
root2 = find(num2)
if rank[root1] > rank[root2]:
example[root2] = root1
el... |
2ad7c7a50ce4e8512f3ea01ab52ca2fae34c20a6 | bhusalashish/DSA-1 | /Data/Heap/K Closest Points to Origin/K Closest Points to Origin.py | 983 | 3.859375 | 4 | '''
#### Name: K Closest Points to Origin
Link: [link](https://www.youtube.com/watch?v=XC4EotTewro&list=PL_z_8CaSLPWdtY9W22VjnPxG30CXNZpI9&index=8)
We say that we can sort before we do anything
For list of coordinate values, find the k elements that are closest to origin
Nearest means smaller distance, max_heap
Cr... |
97f8c019d145f45a95b0f7c91bfacfa974bed835 | praveen9375/numpy | /rangednumpydata.py | 198 | 3.75 | 4 | #Our initial array will just be all the integers from 0 to 11, inclusive. We'll also reshape it so it has three dimensions.
import numpy as np
arr = np.arange(12)
reshaped = np.reshape(arr,(2,3,2))
|
8b852805f7247b75eded332bb0d538a63e0d107a | kingname/LeetCode | /sort-list.py | 1,587 | 3.8125 | 4 | """
https://leetcode.com/submissions/detail/369690505/
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
"""
# Definition for sin... |
8db00abbea6e309b2295e86313d3943b6a105459 | heyese/hackerrank | /buy_sell_single_share.py | 2,199 | 3.875 | 4 |
# Given a list of prices
# Can pick a point to buy, then a subsequent point to sell
# Want the maximum profit
def max_profit_brute_force(values):
max = 0
for index, buy_point in enumerate(values):
for sell_point in values[index+1:]:
profit = buy_point - sell_point
if profit > ... |
5eda7293536a47a4ebe2805a84bd4257b24d3b56 | CheesyModz/Python-Games | /Connect-Four/ConnectFourGame.py | 10,423 | 3.875 | 4 | '''By: Gary Huang
Date : Feb 24,2019
Description: This program is Connect Four Game.'''
import random
BOARD = []
def makingBoard (col, rows):
'''This function will create a board based off of the user's input using ASCII characters'''
#For every row it makes a new list and adds spaces
for indexRow... |
19ed527f02cf32f3faef66461f556be0c896ac5a | YunsongZhang/lintcode-python | /US Giants/Linked List/103. Linked List Cycle II.py | 797 | 3.796875 | 4 | class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
class Solution:
"""
@param head: The first node of linked list.
@return: The node where the cycle begins. if there is no cycle, return null
"""
def detectCycle(self, head):
if hea... |
35094a0b9cdfc66ff8d623ea8b70b2f7b0c6f412 | perlcloud/Clipboard-Saver | /Clipboard-Saver.py | 5,896 | 3.765625 | 4 | """Save the contents of the clipboard when it changes"""
import os
import re
import csv
import time
import pyperclip
from datetime import datetime
def csv_start(path):
"""Creates a .csv file if one does not exist"""
if not os.path.isfile(path):
with open(path, 'w', newline='') as log:
fi... |
0df0fb49d52258903cf9a95e09cd4d535a7e410d | AnjalBam/iw-assignment-python-iii | /solutions/B_console_app/main.py | 1,853 | 3.65625 | 4 | import sys
from IT_academy.student import Student
from IT_academy.course import AllCourses
from IT_academy.display import display_student_data
from IT_academy.operations import complete_course, update_data, register_student
def main():
print("""
Welcome To IW Academy
We provide a wide range of Tech and P... |
65b71b31409f8675c7d7e55b87bc708e2ef47b67 | VenterMEI/data_struct | /lectcode/11_Container With Most Water.py | 1,163 | 3.703125 | 4 | """
Runtime: 84 ms, faster than 14.96% of Python3 online submissions for Container With Most Water.
Memory Usage: 16.1 MB, less than 5.13% of Python3 online submissions for Container With Most Water.
"""
"""
note
使用的hash表,o(nlogn)的时间复杂度(排序的nlogn),o(n)的空间复杂度。
感觉还行,不知道为啥运行了怎么旧。
"""
import pdb
class Solution:
def m... |
ac193d81654dfc19afb4252d91feaa5b9d7d0f47 | samyumobiMSIT/CSPP1 | /CSPP1-practice/m3/hello_happy_world.py | 117 | 4.09375 | 4 | #code to print hello world when happy is more than 2
HAPPY = int(input(""))
if HAPPY > 2:
print("hello world")
|
5c39a3bdc8bbff765f7e39ffccb674bfc47c427d | achbogga/Artificial-Intelligence-B551-Fall-2015 | /achbogga-a6/orient.py | 10,025 | 3.5 | 4 | #Achyut Sarma Boggaram @achbogga a6 B551 fall-15
#Please email me if you wish to anything else about the code
#Nearest k neighbours knn()
#######Design Decisions####################
#Distance metric used is Euclidean distance
#Standardization of each dimension over the whole dataset done
#Neural nets with one h... |
1bacfc960bd1abd20fba4911f1996716d8752581 | prabhanjanholikar/TicTacToe | /Tictactoe.py | 5,904 | 3.625 | 4 | #import packages
# pip install pygame
import pygame as pg
import sys
#import pygame
from pygame import display
from pygame.locals import *
import time
# Initialise global variables
game_start = True
XO = 'X'
winner = None
draw = False
width = 400
height = 400
line_color = (10, 10, 10) # Black Colour line
# TicTacToe... |
5ab1ee9dc59e26a0352641229c20e981cc4dce9c | marcio-pg/Code-Abbey | /Problem 40 - Paths in the Grid.py | 2,705 | 3.75 | 4 | # Problem #40 - Paths in the Grid http://www.codeabbey.com/index/task_view/paths-in-the-grid
# Submission by MPadilla - 01/Aug/2015
print("Input grid's number of rows and column separated by spaces")
size=input().split()
rows=int(size[0])#Lee tamaño de la rejilla.
print("Input grid. @ is start, + are safe tile... |
85fd2358f8267f5a96f44186291d604abe3c250a | pfolus/cms_system_python | /views/accountant_view.py | 787 | 4.125 | 4 | def show_menu():
menu = ['1. Show list of students',
'2. Show detailed list of students',
'3. Shoutbox message',
'4. Change password',
'5. Add an event',
'6. Show upcoming events',
'7. Remove an event',
'8. Private messages',
... |
ca83b772b11c410223109e016d9318e089250c1a | victorvhs/zumbi_curso | /lista_2/ex3.py | 889 | 3.953125 | 4 | # -*- coding: utf-8 -*-
#Exercio numero 3
#João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de
#seu trabalho. Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca do
#estado de São Paulo (50 quilos) deve pagar uma multa de R$ 4,00 ... |
85eec3db458821b27646d1cc5a52dd941a010ff6 | chenjiancong/code | /stu_python/using_dict.py | 540 | 3.640625 | 4 | #!/usr/bin/env python
# encoding: utf-8
# 'ab' is short for 'a'ddress'b'ook
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print('Swaroop\'s address is ', ab['Swaroop'])
print('\nTher... |
a4fb8451eeabc144bcbdeef5d7fe591da99f8ffb | Aiyane/aiyane-LeetCode | /251-300/单词模式.py | 1,373 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 单词模式.py
"""
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaa... |
f7b3935c4ca61c10a0706ebc77612af4f218179c | TEnders64/ScoreAndGradePython | /scoreAndGrade.py | 610 | 4 | 4 | def scoreAndGrade():
for i in range (0, 10):
score = input('Your score:')
if(score >= 60) and (score <= 69):
grade= 'D'
print 'Score:',score,';Your grade is:',grade
elif(score >69) and (score <= 79):
grade = 'C'
print 'Score:',score,';Your grade is:',grade
elif(score >79) and (score <= 89):
gra... |
a65dd415ae05ea93773354728f0d23f7a5dd0c6b | vincentlaucsb/csv-parser | /programs/csv_bench.py | 522 | 3.8125 | 4 | import argparse
import csv
parser = argparse.ArgumentParser(description='Count the number of lines in a CSV')
parser.add_argument('file', type=str, nargs=1,
help='File to parse')
parser.add_argument('encoding', nargs='?', type=str, default='utf-8',
help='File encoding')
args = ... |
e2eb07556f14c7d6fef9782f27ef3149704932e5 | AdamGoins/back | /python/PycharmProjects/CS-126SI/Functions/FunctionArguments.py | 982 | 3.65625 | 4 | """
Adam Goins
CS126 SI
Chapter 5
Functions and Arguments
"""
def main():
homework_points_acquired = [7, 5, 3]
homework_points_total = [10, 10, 10]
homework_total = addPoints(homework_points_acquired)
homework_overall = addTotal(homework_points_total)
quiz_points_acquired =... |
ff516bbb50899018df24a6085ba6da54b6ccfed2 | zhaoyangliu/Othello | /Dragon.py | 26,548 | 3.625 | 4 | import copy
import time
TIME_LIMIT = 15
class Dragon:
def __init__(self):
self.board = [[' ']*8 for i in range(8)]
self.size = 8
self.board[4][4] = 'W'
self.board[3][4] = 'B'
self.board[3][3] = 'W'
self.board[4][3] = 'B'
# a list of unit vecto... |
3144e880e36d49904aae3be3c62e292a938a34fa | VrushaliRN/Movie_trailer_website | /media.py | 724 | 3.515625 | 4 | import webbrowser
class Movie:
# This provides documentation about the class "Movie"
# This class movie related information
# Initializing and creating space in memory for what"
# we are creating in this movie_website_trailer_project
# "selfmade" is the object being created
def __init... |
49aa6ba2f50405ffb882a654f798a06479d38fc4 | icoder-new/sums.py | /replace_vowels.py | 387 | 3.78125 | 4 | #!/usr/bin/env python3
def replaceStr(str,c,c2):
i = 0
d = 0
n_str = ""
while i < len(str):
if str[i] == c[d]:
n_str += c2
else:
n_str += str[i]
i+=1
return n_str
def reStr(str,c,c2):
i = 0
strs = str
while i < len(c):
strs = replaceStr(strs,c[i],"")
i+=1
return... |
63c72561eb0fc59f609985d40ed79bcecaf9bc1e | BeautyFades/Navi | /Q2.py | 505 | 3.984375 | 4 | ### DESAFIO 2 ###
### Feito por Fellipe Domingues Fernandes para o teste Summer Job na Navi
import math
vector = [None]*10
for i in range(len(vector)):
if (i % 2 == 0):
vector[i] = pow(3,i) + 7*(math.factorial(i))
else:
vector[i] = pow(2,i) + 4*(math.log(i))
posLargest = vector.in... |
312c5173e085f807cccb8453913c390614d9a3c3 | phuonggtrann/CS112 | /Project - Labs/CentExchange.py | 835 | 3.65625 | 4 | def ChangeMaker(price, payment):
# Write your code here
totalPayment=0
for i in payment:
totalPayment+=i
change = totalPayment-price
coinChange=change-int(change)
def helper(remain, result):
temp=0
if remain>=25:
temp=25*int(remain//25)
result[3]+=... |
663e31edd7f07b8a4044ae889404107a3c59a135 | akashsharma99/PyRock | /pattern4.py | 207 | 3.8125 | 4 | '''
Created on Oct 28, 2017
@author: Akash
1
12
123
1234
12345 n=5
'''
n=int(input("Enter a size\n"))
for i in range(n):
for j in range(i+1):
print(j+1,end="")
print("\n",end="") |
5c426f9498bccaa62d01d1ea191aa2c404d6d00d | cooper-1/Pythonofspider | /第11章/使用Thread子类创建线程.py | 664 | 3.65625 | 4 | # -*-coding: UTF-8
# @Time : 2021/10/17 12:14
# @Author : Cooper
# @FileName: 使用Thread子类创建线程.py
# @Software: PyCharm
import threading
import time
class SubThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = '子线程' + self.name + '执行, i= ' + str(i)... |
2e47e40c3fc8875bd312f17482844426986f23b1 | jeremyprice/game | /mobs.py | 5,706 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'alex barnes'
import mechanics
import json, random
#load mob data from external json file
with open('./resources/mobs.json') as mobjson:
mobData = json.load(mobjson)
#initialize empty mob index
mobIndex = {0:[], 1:[], 2:[], 3:[], 4:[]}
#fill mob index.... |
435a058724beac5cb0b80bb456f95c60aa7c9a24 | uuga8/leetcode-solutions | /python/20. Valid Parentheses.py | 881 | 3.59375 | 4 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
open = ["(", "{", "["]
close = [")", "}", "]"]
if len(s) < 2 or s[0] in close:
return False
stack = []
def checkers(s):
... |
75bc7c435acb74b05db3d210d44ee14d9e330ec1 | marcoscinturon/Ahorcado | /Ahorcado.py | 6,556 | 3.71875 | 4 | #paises: Camboya, Finlandia, Marruecos, Noruega, Ucrania
#frutas: Aguacate, Melocotón, Pomelo, Mango, Pistacho
#géneros musicales: Clásica, Gospel, Country, Flamenco, Punk.
#animales: Girafa, Delfín, Gorila, Jaguar, Mariposa
#películas: Los vengadores, Crepúsculo, La naranja mecánica, El conjuro, Psicosis.
from ... |
24a0c29dd5a149abf82e575b51132aa7acb61016 | Viktor-Lai/Data_structure | /递归/JumpFloorII.py | 411 | 3.703125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def recurs(self,n,i):
if(i==n):
return 0
if(i==n-1):
return 1
if(i==n-2):
return 2
sum = 0
j=1
while(i+j<n):
sum += self.recurs(n,i+j)
j+=1
return sum+1
def... |
a9ce584e45f81d63fd78fe600672b6422960cd8e | rsmetana/Python | /venv/100_days_of_python/Day8/greet.py | 673 | 4.125 | 4 | # Review:
# Create a function called greet().
# Write 3 print statements inside the function.
# Call the greet() function and run your code.
#def greet():
# print('Hello')
# print('This is a greeting')
# print('!!!!!!!!!!!')
#greet()
def greet_with_name(name):
#name variable above is the parameter
print(f'Hel... |
d4ce0413663b1363985573752ae308eb6a6d57f1 | sumairlaghari/AllAssignments | /AssignmentsNo5/As5.3.py | 138 | 3.9375 | 4 | list=[2,1,1,5,3,2,10,5,6,8,9,11,2,22]
def even(list):
for i in list:
if i % 2 == 0:
print(i)
even(list) |
09883dcf1ed913abfd7b2db7ef57a91eedcfbca0 | NiteshBabu/LeetCodeBrawl | /Easy/count_say.py | 543 | 3.625 | 4 | def count_say(n:int) -> str:
result = '1'
if n == 1:
return result
char_pointer = 0
count = 0
current_string = ''
while n > 1:
while count < len(result):
try:
while result[char_pointer] == result[count]:
count += 1
except IndexError:
pass
current_st... |
64358dd55c796be7107f45c8aef41cd909346dee | igorfreire/pygame | /jogo00.py | 1,753 | 3.578125 | 4 | import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
#aqui cria uma janela 500 por 500
pygame.display.set_caption("Primeiro jogo")
#variaveis posicao do personagem
x = 50
y = 425
width = 20
height = 30
vel = 5
#abaixo variaveis para utilizar no personagem pulando - jump
isJump = False
jumpCount = 1... |
c0e3d816130dae566448110d37f41aa0b5fd44cb | gitliyucg/Python | /数据类型/list.py | 340 | 3.828125 | 4 | classmates = ['Michael', 'Bob', 'Tracy']
# print(classmates[0])
# print(len(classmates))
# print(classmates[-1])
# print(classmates[len(classmates) - 1])
# 添加删除元素
classmates.append('hehe');
print(classmates)
classmates.insert(0, 'haha');
print(classmates)
classmates.pop()
print(classmates)
classmates.pop(0);
print(clas... |
cdc7440f78164227b6e5187297b0e706ff87daca | Valerich1804/python_lesson | /lesson5/hw05_easy.py | 1,569 | 3.78125 | 4 | # Задача-1:
# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,
# из которой запущен данный скрипт.
# И второй скрипт, удаляющий эти папки.
import os
import shutil
import sys
path_dir = [('dir_' + str(i + 1)) for i in range(9)]
# Создание пустых директорий
def make_dir(paths):
dir_path = os.path.join(... |
e5653d666353ebd6daa7c241d23f395d31f33b90 | akgarhwal/Coursera-Fundamentals-of-Computing | /An Introduction to Interactive Programming in Python -Part 1/pong.py | 5,008 | 4.0625 | 4 | # _author_ = 'akgarhwal'
# to Play this game open below link
# link : http://www.codeskulptor.org/#user44_OIodC3QHbGmVlX5.py
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 2... |
cd8d403314779f82f4d9b0e1388fac0c2dd8a680 | mao/python_study | /chapter08/08_make_album.py | 755 | 3.9375 | 4 | def make_album(artist, album_name, track_num=10):
album_info = {'artist': artist,
'album_name': album_name,
'tracks': track_num}
return album_info
active = True
albums = []
while active:
album_name = input('Please input album name: \t')
artist = input('Please input... |
266e4d2d042132b85935ee70411e4e3186d0465b | huazhige/EART119_Lab | /mid-term/sheridanzachary/sheridanzachary_33570_1312520_Problem_2-1.py | 1,679 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
-Problem 2:
Plotting the three functions given and finding the roots of each
"""
import numpy as np
import matplotlib.pyplot as plt
#=====================Define Functions========================================
def my_Secant( fct, x0, x1, tol = 1e-5, N = 20):
"""
... |
3872e37211c502c982b38c227bd1a6f22ec12d96 | rhdmsggg/python | /랜덤숫자맞추기.py | 633 | 3.859375 | 4 | #랜덤 숫자 맞추기
import random
print(">>숫자 맞추기 게임<<")
choice = random.randrange(100)
while True:
#사용자에게 숫자 입력 요청 후 점수로 타입 변환
user_choice = int(input('점수를 입력하세요 : '))
#컴퓨터가 선택한 숫자와 입력받은 숫자가 맞으면 무한 루프 탈출
if choice == user_choice:
break
#입력 숫자와 컴퓨터 선택 숫자 비교 및 정보 제공
if choice <user_choice... |
ca2454f98b1947e170e0f599147ace3572e63473 | neelamy/InterviewBit | /Two Pointers/Diff1.py | 1,000 | 3.5 | 4 | # Source : https://www.interviewbit.com/problems/diffk/
# Given an array A of sorted integers and another non negative integer k,
# find if there exists 2 indices i and j such that A[i] - A[j] = k, i != j.
# Algo/DS : 2 pointers
# Complexity : O(n)
class Diff:
# @param A : list of integers
# @param B : inte... |
8712cd218587b697e191ee2b637de29df2e4dbfe | PrakashChanchal1998/pyathonproject | /tree.py | 102 | 3.859375 | 4 | a=1
for n in range(1,5):
for m in range(1,n):
print(a,end="")
a=a+1
print("")
|
5eed3f5a0a0a57f7083c7efca7a54ea20069ad6a | heyzwming/PythonData | /linalg.py | 1,490 | 3.53125 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# numpy的线性代数库
import numpy as np
import numpy.matlib
'''
函数 描述
dot 两个数组的点积,即元素对应相乘。 相当于矩阵的乘法运算
vdot 两个向量的点积
inner 两个数组的内积
matmul 两个数组的矩阵积
determinant 数组的行列式
solve 求解线性矩阵方程
inv 计算矩阵的乘法逆矩阵
'''
a = np.array([[1, 2], [3, 4]])
b = np.array([[11, 12], [13, 14]... |
d22d95d2ae6c804edcb5d51b4447f79105716e7f | avrahamm/python-bootcamp-062020 | /lesson5/ex1.py | 203 | 3.84375 | 4 | # I would use longer variable names
age_in_years = int(input('What is your age in years? '))
age_in_months = age_in_years * 12
print(f"Your age in years is {age_in_years}, in months is {age_in_months}")
|
7031f91ea57bddb900177f63e771d05493c705ee | arturbs/Programacao_1 | /uni2/l0gj/mediaDoAluno.py | 412 | 3.609375 | 4 | # coding: utf-8
# aluno: Artur Brito Souza
# matricula: 118210056
# UFCG - Programação 1 2018.2
# 10/09/2018
# Programa : media do aluno
"""dados das notas que o usuário coloca"""
nota1 = float(raw_input())
nota2 = float(raw_input())
nota3 = float(raw_input())
"""calculo da nota final de acordo com o cálculo pedido"... |
5ca0116192ccdbcf20933e73730d77be73a7901b | yurkova/hpsc-coursera | /homework2/hw2b.py | 7,652 | 3.984375 | 4 | """
Homework 2b.
Module for polynomial interpolation.
"""
import numpy as np
import matplotlib.pyplot as plt
def quad_interp(xi, yi):
"""
Quadratic interpolation. Compute the coefficients of the polynomial
interpolating the points (xi[i],yi[i]) for i = 0,1,2.
Returns C, an array containing the coeffic... |
05afd0310ecaf88f94c850af8f96449e4874127e | mwong33/leet-code-practice | /medium/flatten_binary_tree_to_linked_list.py | 1,485 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# O(n) time O(n) space
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anythin... |
dd8eedc22e27158a9d996e5f3eb01283f23e7611 | magmarnowak/Python_Beyond_the_Basics | /03_Classes/encapsulation.py | 339 | 3.84375 | 4 | class MyClass(object):
def set_val(self, val):
self.value = val # set_val takes the argument val and sets it as an
# attribute in the instance under the name value
#set_val is a SETTER method - it sets a value in the instance
def get_val(self):
return self.value
#get_val ... |
7dc1fb6af14e006a9f19d85547fb8d0a6cf4434b | neko-niko/leetcode | /剑指offer/new2/从上到下打印二叉树.py | 593 | 3.796875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root: TreeNode):
lst = []
out = []
if not root:
return []
lst.append(root)
... |
09a5f14c85bc827f2591783760a3338a71c5477b | bwiczkowsk96/Python | /petle/for_range.py | 337 | 3.734375 | 4 | string_A = '+---+---+---+---+'
string_B = '| | | | |'
for s in range(6):
print(string_A)
for i in range(9):
if i % 2 == 0:
print(string_A)
else:
print(string_B)
for a in range (1,10):
print('x'*a)
for z in range(1,10):
if z % 2 == 0:
print('o'*z)
else:
... |
31284a8b15ffd949be569cb0ac65c51fd80eb5f4 | jiten123mishra/DATASCIENCEPRACTICE | /MACHINE_LEARNING_PRACTICE/13.FEATURE ENGINEERING/02.SCALE_STANDARDIZE_NORMALIZE/04.FEATURE_SCALING.py | 2,593 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 16:53:29 2019
@author: INE12363221
"""
#WHEN FEATURE SCALING IS REQUIRED ?
#Always use feature scaling we need to calculate euclidian distance
#like KNN or Kmeans, AHC
#linear regression with gradient descent
#HOW to do
#1. standard scaler
#2. min max... |
a2e59d2ef2cb207f94133bf8110f5cfccf4bd38a | Jungeol/algorithm | /leetcode/easy/67_add_binary/dosun.py | 337 | 3.5 | 4 | """
https://leetcode.com/problems/add-binary/
Runtime: 36 ms, faster than 90.55% of Python3 online submissions for Add Binary.
Memory Usage: 13.8 MB, less than 5.41% of Python3 online submissions for Add Binary.
"""
class Solution:
def addBinary(self, a: str, b: str) -> str:
return bin(int(a, 2) + int(b, ... |
934d77bf50ee042f0cf372de2d9e306081fc4b38 | jihoo1214/pyalgo | /merge_sort.py | 1,194 | 3.90625 | 4 | """
PSEUDO CODE:
function mergesort(m)
var list left, right
if length(m) ≤ 1
return m
else
middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = mergesort(left)
right = mergesort(righ... |
e93b7fd384f626cc1f020ed5aa77f63ef351c319 | Nicobossio42/Exercises3004 | /Ex35.py | 330 | 3.8125 | 4 | print("Bienvenidos a la plataforma:)")
Usuario = str("Nicolas")
Contraseña = str("Hola")
Acceso = Usuario + Contraseña
user = str(input("Ingrese su usuario: "))
password = str(input("Ingrese su contraseña: "))
Acces = user + password
if Acces != Acceso:
print("Acceso denegado")
else:
print("Acceso concedido"... |
3c316d48a97c8f9c45316316b099b394a7537ba2 | deboragaleano/itp-u4-c2-hangman-game | /hangman/game.py | 2,776 | 3.75 | 4 | import random
from .exceptions import *
# Complete with your own, just for fun :)
LIST_OF_WORDS = ['mallorca', 'odessa', 'beer', 'beach', 'pool', 'food']
def _get_random_word(list_of_words):
if not list_of_words:
raise InvalidListOfWordsException()
word = random.choice(list_of_words)
return word... |
952e3799a3d4473eb9ef5b1330767e962f4013b1 | Kailashcj/tpython | /hackerrank/geeks/multiply_two.py | 502 | 3.890625 | 4 | #!/bin/python3
def multiply_two(arr, num):
multiple = []
for i in arr:
if num%2 == 0:
multiple.append(i)
i=0
j =len(multiple) - 1
while i < j and i != len(arr) - 1:
if multiple[i] * multiple[j] == 20:
return multiple[i], multiple[j]
else:
j -= 1
if j == i:
i += 1
... |
5b1b40fde88489500f97bfd9296417b25b3c27b1 | jedzej/tietopythontraining-basic | /students/wachulec_maria/lesson_01_basics/clock_face_1.py | 230 | 4.03125 | 4 | H = int(input("Hours (H): "))
M = int(input("Minutes (M): "))
S = int(input("Seconds (S): "))
degree_seconds = S * 30
degree_minutes = M * 30 + (degree_seconds/60)
degree_hours = H * 30 + (degree_minutes/60)
print(degree_hours)
|
bdf076cba94278d00c68ce703e86ff10349aa490 | justinprez/ecocar | /button.py | 1,485 | 3.84375 | 4 | '''
This file contains all of the logic pertaining to the various buttons that this
demo requires
'''
# pylint: disable= E1101
import pygame
from display import YELLOW, GREY
pygame.init()
class Button:
'''
This class allows for the user to make multiple buttons that all have the same
underlying function... |
6ec97fb96f1b56e51390aab493389516764f6828 | YoungsAppWorkshop/codewars | /r1/day8_kebabize.py | 917 | 4.4375 | 4 | #!/usr/bin/env python3
"""
Kebabize - 6 kyu
Modify the kebabize function so that it converts
a camel case string into a kebab case.
the returned string should only contain lowercase letters
Examples
kebabize('camelsHaveThreeHumps') // camels-have-three-humps
kebabize('... |
6362902bd325a30f0b6a9813b5798b65fa732f99 | beninghton/notGivenUpToG | /String/856. Score of Parentheses.py | 1,904 | 3.5 | 4 | class Solution(object):
def scoreOfParentheses(self, S):
def F(i, j):
#Score of balanced string S[i:j]
ans = bal = 0
#Split string into primitives
for k in range(i, j):
bal += 1 if S[k] == '(' else -1
if bal == 0:
... |
37bf2d5b3d35490dc7b035f466b654fa3c4f4ce2 | MacHu-GWU/single_file_module-project | /sfm/binarysearch.py | 7,306 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
This module is provide methods for searching item in a sorted list.
Highlight:
- :func:`find_last_true`: A magic pluggable method, read API reference for more
info.
- :func:`find_nearest`: Find the nearest item of x from sorted array.
**中文文档**
下面是一些讨论:
原生的 ``bisect.bisect_left`` 和 ``... |
e9c456bfc2c5b45273c1a964a12cf059b4de7ec6 | yizumi1012xxx/sports2016 | /generateVariables/data/ball_touch_action.py | 1,465 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
ball_touch_action.py
"""
class BallTouchAction():
"""
BallTouchAction
"""
HOME = 1
AWAY = 2
def __init__(self, frame_id: int, history_id: int, team_id: int,
player_id: int, homeaway: int, ball_x: float, ball_y: float):
self.frame_id = frame... |
f13c9550995c302bf972dd0b958784437357a9c3 | JainulV/myplanB | /database/scrape_course_cat.py | 4,934 | 3.53125 | 4 | #!/usr/bin/env python3
'''
scrape_course_cat.py: Scrapes courses provided by all departments mentioned on the
website https://www.washington.edu/students/crscat/ and saves the data in a JSON file.
__author__='Jainul Vaghasia'
__email__='jnv3@uw.edu'
__status__='Development'
'''
# Last edited by: Akshit Patel, reason:... |
b32c3b3bd09746425e176365bd08d788afb854f1 | izabelcavassim/Genome_scale_algorithms | /Project2/build_suffix_tree_naive.py | 1,662 | 3.84375 | 4 | # Planning project 2
# 1. Function to build the suffix tree (be aware of the index allocation)
# 2. Function to do exact matching using the suffix tree
# 3. Function to print the tree
# 4. Function to evaluate/compare the algorithm
# 5. Write report
from ete3 import Tree
import numpy
from Node import Node
'''
tak... |
96b013ef4750eb66024f86dead5d4811e8f11680 | Techsrijan/techpython | /greatestbetwwentwo.py | 159 | 4 | 4 | a=int(input("Enter First Number"))
b=int(input("enter Second Number"))
print("A=",a,"B=",b)
if a>b:
print("A is greatest")
else:
print("B is greatest") |
2320eb49f1ce69edbf1326dfce6842fe1ad49d54 | dsenator1/Batch-Two | /Yaba/Python/Grade Calculator.py | 322 | 3.546875 | 4 | #Bala Yakubu 08033117843
n = int (input( "enter score:"))
if n>= 0 and n<40:
print("F")
elif n>= 40 and n<45:
print("E")
if n>= 45 and n<50:
print("D")
elif n>= 50 and n<60:
print("C")
elif n>= 60 and n<70:
print("B")
elif n>= 70 and n<100:
print("A")
else:
print("Score :" + s... |
aa5fa4577a550738c9167e2b222a36cdfb53676f | mrcrdg/05-python | /solucoes/aula2/ex09.py | 539 | 4.125 | 4 | #!/usr/bin/env python3
# 9 - Escreva uma funcão chamada showNumbers, que recebe o parâmetro limit. A funcão deve imprimir todos os números entre 0 e limit com uma label para identificar se o número é par ou ímparPor exemplo, se o limite for 3, deve-se imprimir:
limit = int(input("Insira um numero: "))
def showNumber... |
25e114c45066da6e68ef8bfc296a697550236031 | pushkarkadam/basic-math-python | /GraphicalUI/graphical7.py | 1,059 | 3.890625 | 4 | '''
USING CLASSES
'''
from tkinter import *
class BuckysButton:
def printMessage(self):
print("Wow, this actually works!")
def __init__(self, master): #anytime you see "master" it means the main window
frame = Frame(master) #We created a Frame in the main window
frame.pack() #display on the screen to ... |
d2aa26f041914dedc73212c5ae4affa19934de45 | michal0janczyk/udacity_data_structures_and_algorithms_nanodegree | /Project_1/Task0.py | 1,053 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open("texts.csv", "r") as f:
first_line_texts = f.readline()
print(
"First record of texts",
first_line_texts.split(",", 2)[0],
"texts",
first_line_texts.split(",", 2)[1],... |
baa04bf8baa24b0621c9e12bbc210f33193f1dff | marcosaraujo2020/ifpi-ads-algoritmos2020 | /Lista_Prof_Fabio/Fabio01_Parte02/f1_q19_pontos_grafico.py | 460 | 4.09375 | 4 | # ENTRADA
print('A seguir, informe dois pontos quaisquer para um plano')
x1 = int(input('Digite o valor para x1: '))
y1 = int(input('Digite o valor para y1: '))
x2 = int(input('Digite o valor para x2: '))
y2 = int(input('Digite o valor para y2: '))
# PROCESSAMENTO
distancia_pontos = ((x2 - x1) ** 2 + (y2 - y1) ** 2) *... |
60e4ce7139185b6437952a445107866e46b987b3 | CelsoEspinoza/Python.curso | /list_comprehension.py | 651 | 3.890625 | 4 |
def main():
numbers_string = input("Escribe los numeros multiplos separados por comas que deseas ver (ej: 4,6,9): ")
strip_numbers = numbers_string.split(',')
strip_numbers = [int(num.strip()) for num in strip_numbers]
list = [i for i in range(1, 100000) if repeat_conditions(i, strip_numbers)]
prin... |
0187ac1cf958a0125126eb6396da25d368debded | impiyush83/expert-python | /inbuilt_python_functions.py | 307 | 4.15625 | 4 | """
list.sort() when you want to mutate the list.
sorted() when you want a new sorted object back.
"""
l1 = [1, 4, 6, 2, 3]
l1.sort()
print(l1) # l1 is permanatly mutated to sorted list
l1 = [1, 4, 6, 2, 3]
print(sorted(l1)) # l1's sorted list is returned
print(l1) # original list is obtained back
|
6a3031e74a81504126381c87fefb155132ce8ba9 | abhishekjoshi1991/Python_Learning | /All other combo programs/Program_for_fibonacci_series.py | 899 | 4.28125 | 4 | #Program for fibonacci series(1,1,2,3,5,8,13,21...)
#Program 1
x=0
y=1
print(y)
i=1
while i<=10: #to print series upto 10 lines, can use for loop also
a=x+y
x=y
y=a
print(y)
i+=1
#=======================================================================
#Program 2
print('\n')
print('o/p of second ... |
937be08973c8484b16850d385d7a73386b89bfdc | alexandraback/datacollection | /solutions_5690574640250880_0/Python/tres/C.py | 1,675 | 3.515625 | 4 | def colourRest(board, N, R, C):
for i in range(2, R):
for j in range(2, C):
if N <= 0: return
board[i][j] = '.'
N -= 1
for t in range(1,int(input())+1):
R, C, M = map(int,input().split())
N = R * C - M
print('Case #{0}:'.format(t))
rotate = Fal... |
45085c40d441ae5b4006d78eff277ab2fab8fd68 | PoojithRajDunde/Bootcamp---Project | /Sample.py | 208 | 4 | 4 | import hashlib
n1= hashlib.sha3_256()
s=input("enter text:")
e=s.encode()
for i in s:
n1.update(e) #adding iteration
n1.update(b"thee salting output") #adding salting
m=n1.hexdigest()
print(m)
|
cdc3590d81a21b069e1c7af3a6d9107c99bfdb8f | CoreSheep/PythonTutorial | /StringFormatting.py | 387 | 4.15625 | 4 | #1. print "hello, SheepCore"
name = "SheepCore"
print("Hello, %s" %name)
#2. group of string
agender = "male"
age = 22
print("My name is %s, I'm %s with %d." %(name, agender, age))
#3. formatting for list
sports = ["Running", "Basketball"]
print("My favorite sports are %s" %sports)
#4. %f , %d, %s -- string or any ... |
fa2dab85db7bed7d4857418729c6879754d954bd | Vlad-Vargan/hillel_ml | /python_basics/2_class/hw2.py | 8,520 | 4.125 | 4 | """
Заняття ІІ
Цикли
"""
import random
import collections
def square_printer():
# Написати програму, яка зчитує число, виводить його квадратний корінь і приймає наступне число.
# Програма повинна припинити роботу коли їй буде введено від’ємне число.
let = 1
while let >= 0:
try:
... |
a09738442ab0c9f562b807c676f08da584ac06ad | krishdb38/Data_Analysis | /Pyspark/accumulator.py | 539 | 4.09375 | 4 | """
Accumulator variables are used for aggregating the information through
associative and commutative operations. For example,
You can use an accumulator for a sum operation or
counters. The following code block has the details
class pyspark.Accumulator()
"""
from pyspark import SparkContext
sc = SparkContext("loca... |
14446242c3f6034a507304bd1c5d4a6b80b1a281 | kiranlande00/python-practice | /Exercise 5.py | 3,830 | 3.5625 | 4 |
#HEALTH MANAGEMENT SYSTEM
def gettime():
import datetime
return datetime.datetime.now()
def take(k):
if k==1:
print("Enter ::")
print("\t 1.Exercise")
print("\t 2.Food")
c = int(input())
if c==1:
value=input("Type here\n")
... |
4a8a4c3512cb600072abbd39e5663c1564bef693 | hussein343455/Code-wars | /kyu 7/Find the calculation type.py | 1,114 | 4.59375 | 5 | # You have to create a function calcType, which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number).
#
# Based on those 3 values you have to return a string, that describes which operation was used to get the given result.
#
# The possible return strings are: "a... |
8f80684a831b219e41817f9720cc958c2ef9565b | fedcalderon/Python1-Class | /src/chapter04/concepts.py | 1,473 | 4.28125 | 4 | # Chapter 4 - Working with Lists
#define a list variable
# 0 1 2 3 4 5 6 7
magicians = ['alice', 'david', 'carolina', 'ezra', 'sasa', 'jacob', 'fed', 'jazmin']
# use the print() built in function to show values
#print(f"Item 0 = {magicians[0]}")
#print(f"I... |
d097a363a2f6778de79bc5f128f88272abca95d1 | 606keng/weeds_study | /suanfa/合并表记录.py | 179 | 3.5625 | 4 | count = input()
numbers = []
i = 0
while i < int(count):
a,b = input().split()
numbers.append([int(a),int(b)])
i += 1
# numbers = numbers.sort()
print(sorted(numbers)) |
04fdeb6fb17d903370a311fbd2e0482a6fbd9f29 | yhbian/leetcode | /lc32.py | 3,235 | 3.515625 | 4 | class Solution:
def longestValidParentheses(self, s: str) -> int:
# 1. try double pointer, left must point to a "("
# 2. the left must be ")" and sum must be 0
# 3. left can start from -1, and break once match
# 4. once match, i.e. [3: 17], return
if not s or len(s) == 1:
... |
7fffe9ba05b2c0f9f5ae788239f36a722a803a71 | kangkang59812/LeetCode-python | /88.合并两个有序数组.py | 1,390 | 3.875 | 4 | #
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# https://leetcode-cn.com/problems/merge-sorted-array/description/
#
# algorithms
# Easy (46.93%)
# Likes: 446
# Dislikes: 0
# Total Accepted: 122.3K
# Total Submissions: 260.3K
# Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3'
#
# 给你两个有序整数数组 nums1 ... |
878e85e8427236ac5304c42210d0cbb1558f15c7 | SaurabhPal25081995/Full-Python-Course | /Multiple Inheritance-file.py | 616 | 3.625 | 4 | class Player:
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def display(self):
return f"Name of Player is {self.name}, age is {self.age} and gender is {self.gender}"
class Employee:
def __init__(self,name,salary):
self.name... |
7df53635e8a717abde77abac16eea5413e777ba1 | NiyiFalade/PythonR | /Exe1.py | 232 | 4.03125 | 4 | weight = input(' what is your weight in pounds: ')
conversion = float(weight) * 0.453
print('your weight in kilograms is : '+ str(conversion))
for item in ['sss','kkk']:
print(item)
for item in range(5,19,2):
print(item)
|
8e61c08ad79ec82b4f5f91b3b7e097881826a0c9 | gseverina/python-trainings | /hackerrank/longest_subarray.py | 1,035 | 3.875 | 4 | def longest_subarray(arr):
r = []
sub = []
i1 = 0
i2 = 0
while i2 < len(arr):
x = arr[i2]
if sub.count(x) < 2:
sub.append(x)
if len(set(sub)) > 2:
sub.pop()
if len(sub) > len(r):
r = sub
i1 +=... |
95409cefe28dd514f61dc874e60125acec87a4eb | samjongman/python | /multiples.py | 304 | 4 | 4 | """ Lab4 ex 1 """
def multiples(p_input):
""" Prints multiples of input """
for outer in range(1, p_input+1):
print(outer, end=" ")
for inner in range(1, outer):
print(outer*(inner+1), end=" ")
print("")
INPUT = input('Typ een nummer ')
multiples(int(INPUT))
|
66e2a77a94fe4bd752ac4a8f097519ca39e745d2 | UnknownGi/Python-Tutorial-with-Code-and-Explaination | /Chapter #3 - Informal Introduction to Python/3.1.2 - Strings.py | 3,355 | 4.65625 | 5 | # 3.1.2 - Strings
# Besides numbers, Python can also manipulate strings, which can be expressed in several ways.
# They can be enclosed in single quotes ('...') or double quotes ("...") with the same result.
print('String Quotes (Single or Double)')
print('spam eggs')
print('doesn\'t') # Why doesn't it print... |
5293858107d288fd546e747869527bae28c3ebbb | SakshiSSingh/Basic | /Codeforces/133A HQ9+.py | 173 | 3.9375 | 4 | s = str(input())
if 'H' in s or 'Q' in s or '9' in s:
print("YES")
elif '+' in s and ('H' in s or 'Q' in s or '9' in s):
print("YES")
else:
print("NO")
|
a3449f3d0947d2d11ba4358827136487f18822a0 | KC64ML/Python | /Python/code/Day 4/Unchanging_tuple.py | 191 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
T1 = ('a','b','c')
T2 = (1,2,3)
T3 = (4,'d')
print(T1[2]+" "+str(T2[1]))
T1 = T1 + T3
print(T1)
print(T1[2:5])
print(T2[2]*T3)
|
c7284eab601471dfb8fd69eaa7c1af78004e2a38 | samiur98/Data-Structures-Python | /GraphTests.py | 16,400 | 3.625 | 4 | import unittest
from Graph import *
class TestCaseVertex(unittest.TestCase):
#TestCases for the Vertex Class.
def test_add_neighbour(self):
#Test Cases for the add_neighbour method.
v1 = Vertex("v1")
v2 = Vertex("v2")
self.assertFalse(v1.is_neighbour("v2"))
self.assertFa... |
76529a8ad1055699945c4b74bd63bc85ba77df73 | KristofferFJ/PE | /problems/solved_problems/test_054_poker_hands.py | 2,184 | 3.828125 | 4 | import unittest
# Poker hands TODO: wrong parsing
from library.common import Common
from library.poker import Hand, Card, Poker
"""
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.