blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9ca0c66aff5c1be675f1dc8357029502405eb15b | Zeranium/PythonWorks | /Ch02/p.50.py | 328 | 3.609375 | 4 | """
날짜 : 2021/02/18
이름 : 장한결
내용 : 교재 p50 - 슬라이싱 예
"""
oneLine = "this is one line string"
print("문자열 길이 :",len(oneLine))
print(oneLine[0:4])
print(oneLine[:4])
print(oneLine[:])
print(oneLine[::2])
print(oneLine[0:-1:2])
print(oneLine[-6:-1])
print(oneLine[-6:])
print(oneLine[-11:]) |
cd0d1111d33c07e8d9437bfd42c072d03e9dba3a | Kimsangchul0603/BAEKJOON | /Step/Array/3052.py | 490 | 3.671875 | 4 | # 나머지
# 수 10개를 입력받은 뒤, 이를 42로 나눈 나머지를 구한다.
# 그 다음 서로 다른 값이 몇 개 있는지 출력하는 프로그램을 작성하시오.
# 입력값을 42로 나눈 값을 모아서 list 생성 = num_list
# 중복값을 제거하기 위해 list를 set으로 변환
# 변환된 set 원소의 개수를 출력
num_list = []
for i in range(10):
num_list.append(int(input()) % 42)
set_num_list = set(num_list)
print(len(set_num_list)) |
24f185e04d274bce322367b4cdbb2eda1df5a154 | plaplant/Project_Euler | /python/problem1/problem1.py | 279 | 4.09375 | 4 | def main():
# Find the sum of numbers divisible by 3 or 5 up to 100
max_int = 1000
int_sum = 0
for i in range(1,max_int):
if i%3==0 or i%5==0:
int_sum += i
# Write out result
print "Sum: ",int_sum
if __name__=='__main__':
main()
|
623653371bd14c08186c1bdebe5ca2acb51b204c | fanyin/cis526-projects | /amarder/grade | 1,510 | 3.5 | 4 | #!/usr/bin/env python
from __future__ import print_function
import optparse
import sys
# Algorithm taken from http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
if len(s2) == 0:
retu... |
d108cf44997a88769f8a98b0c9bb83e938528a17 | ietuday/python-basics | /specialFunc.py | 742 | 3.6875 | 4 | def printer(msg):
print(msg)
printer('Uday')
x = printer
x('Rohan')
def indirect(func,msg):
func(msg)
indirect(printer,'test')
y = x
y("test2")
print(y.__name__)
#lamda
#normal Function
def func(x, y, z): return x + y + z
print(func(1,2,3))
#lamda function
var = lambda x,y,z: x+y+z
print(var(1,2,3))
de... |
ba19476fc221550c1e58b5fb8a64bdb99d3a1856 | LyceeClosMaire/MP6-le-mastermind | /algo début louis.py | 384 | 3.5625 | 4 | n = 4
c = []
for j in range(n):
choix = input("choisir la couleur pour la case (choix)" + str(j))
c.append(choix)
print(c)
reponses = []
for i in range(n):
reponse = input("choisir la couleur pour la case (reponse)" + str(i))
reponses.append(reponse)
print(reponses)
if reponses[0] == c[0]:
pr... |
24616eedd851ca949368823bcdbe6adc80f882a3 | digitalladder/leetcode | /problem1240.py | 1,648 | 3.75 | 4 | #problem 1240 / tiling a rectangle with the fewest squares
def tilingRectangle(self, n: int, m: int) -> int:
self.best = m * n
def dfs(height, moves):
if all(h == n for h in height):
self.best = min(self.best, moves)
return
if moves >= self.best:
return
min_height = min(height)
idx = height.inde... |
d5bbfb0570a4bc46c864f191c029a67f5be7e642 | StormKing969/Black-Jack-Game | /Card Game - Black Jack.py | 1,395 | 3.671875 | 4 | import random
Player_Cards = []
Dealer_Cards = []
def Value(cards):
current = sum(cards)
return current
while len(Dealer_Cards) != 2:
Dealer_Cards.append(random.randint(1, 11))
if len(Dealer_Cards) == 2:
print("Dealer has X &", Dealer_Cards[1])
dealer_total = Value(Deale... |
504b27de1891df0df192d51e3f9a8b0a3a421cc4 | oscarrobinson/airQuality | /data/jsonGen.py | 3,099 | 3.546875 | 4 | import csv # imports the csv module
import sys # imports the sys module
f = open(sys.argv[1], 'rU') # opens the csv file
jsonString = ""
s1Days = []
s2Days = []
s3Days = []
s4Days = []
def dayDataAsString(data):
string = "";
for datum in data:
string+=datum
return string.rstrip(',')
try:
jsonString... |
4cf379594699b70902cde9eb14eb15d8d7b0cc68 | vanesa1/mineria-de-datos | /knn.py | 2,624 | 3.953125 | 4 | #Mandar a llamar al csv(archivo donde estan guardados nuestros datos)
import csv
#Importar libreria math para poder hacer operaciones matematicas
import math
#Se declara y se abre el archivo de nuestros datos para nuestro ejemplo
f= open('DataSet.csv')
#Lee el archivo con los datos
lns=csv.reader(f)
#lee la ... |
8574366f81c12fbbdb085283bc80b379464d0928 | JLowe-N/Algorithms | /AlgoExpert/kadanesalgorithm.py | 430 | 3.828125 | 4 |
'''
Given an array that can contain both positive and negative integers, find the max sum
of any subarray consisting of adjacent elements
'''
# Complexity - Time O(N) | Space O(1)
def kadanesAlgorithm(array):
maxEndingHere = array[0]
maxSoFar = array[0]
for i in range(1, len(array)):
maxEndingHere... |
85ac117670b8aed0798b1257014ec55b67b01fa9 | gitthabet/MS-BGD | /build/pyson/src/pyson/iface/setters.py | 6,682 | 4.21875 | 4 | '''
Setting values
==============
There are many different functions that, similarly to `getitem`, provide the
write functionality to JSON structures using paths directly.
There are many similar functions that differ in the way they handle non-existing
nodes and in the way they distinguish behavior in mappings and... |
0493036ea04c2c9e328dd6e11a7acc5df34c9c66 | gamecmt/pcc | /chapter4/numbers.py | 902 | 4.09375 | 4 | for value in range(1,5):
print(value)
numbers = list(range(1, 6))
print(numbers)
even_numbers = list(range(2, 11, 2))
print(even_numbers)
squares = []
for value in range(1, 11):
square = value**2
squares.append(square)
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares))
squares = [value**... |
17638dfbf1771ec182a5c0fb443a2134636b6519 | palarm/python_lesson_2 | /while.py | 538 | 3.703125 | 4 | # Цикл While
i = 0
while i < 10:
print(i)
i = i + 1
if i == 5: break
answer = None
i = -1
while answer!='Volvo':
i = i + 1
if i == 0:
answer = input('Какая лучшая марка автомобиля?')
elif i == 1:
answer = input('А если подумать?')
elif i == 2:
answer = input('Еще о... |
1862d08152d1b447e0bb289a5488133cd53ca546 | edu-athensoft/stem1401python_student | /py201221a_python2_chen/day16_210118/list_1.py | 950 | 4.375 | 4 | """
Write a Python program to sum all the items in a list.
[Homework] 2021-01-18
Write a Python program to multiply all the items in a list.
"""
# step 1. to create a list
list1 = [1,2,3,4,5,6]
# step 2. to sum all the items
a = [1, 2, 3, 4, 5]
b = sum(a)
print(b)
# step 2. to sum all the items using for loop
# ho... |
bbacb3d7bdcb62c309a6f346827fb55936e32b11 | stefan-lippl/flask-intro | /project_database_as_a_serivce/web/app.py | 4,053 | 3.578125 | 4 | """
export FLASK_APP=app.py
1. Registration of user (costs 0 tokens)
2. Store a sentence in the db for 1 token (each user has 10 tokens)
3. Retriev his sentence for 1 token
"""
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from pymongo import MongoClient
import bcrypt
app = Flask(__... |
b49113c8336da4e7487be6cb77b6b43534545bb9 | malikovmuhammadqodir/python-projects | /library.py | 1,642 | 3.890625 | 4 | # 2 classes library and student
class library:
def __init__(self, listofbooks):
self.availableBooks = listofbooks
def displayAvailableBooks(self):
print("Books that we have rigth now")
for book in self.availableBooks:
print(book)
def lendBook(self, ... |
ac66a1da63f3486d096db8dfb7bcb72a38fe4428 | Ercion/Advance_Python | /iterator_example.py | 925 | 4.21875 | 4 | def main():
#define a list of days in English and French
days= ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
daysFr=["Dim","lun","Mar","Mer","Jeu","Ven","Sam"]
#use iter to create an iterator over a collection
i=iter(days)
print(next(i))
print(next(i))
#iterator using a funct... |
0c4f769c038f07506945df7fc26532d7cd9617f9 | Virteip/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 327 | 3.828125 | 4 | #!/usr/bin/python3
def text_indentation(text):
if type(text) == str:
for i in range(len(text)):
if text[i - 1] in ".?:":
continue
print(text[i], end="")
if text[i] in ".?:":
print("\n")
else:
raise TypeError("text must be a st... |
744581834f39b0d1cb6149a04be2dea10f115c21 | RenegaDe1288/pythonProject | /lesson20/mission9.py | 1,166 | 3.71875 | 4 | # play = {'jack': [(1, 69485), (6, 95715)],
# 'qwerty': [(2, 95715), (5, 197128)],
# 'Alex': [(3, 95715), (7, 93289), (8, 95715)],
# 'M': [(4, 83647), (9, 54)],
# }
def win(players, n):
maximum = 0
for key, data in players.items():
for num in data:
if num[1]... |
9a327208eb675b7ea59f2ec49efcb1ff12811e58 | egregius313/python_experiments | /find_files.py | 528 | 3.53125 | 4 | #!/usr/bin/env python
import os
def find(pattern):
for root, dirs, files in os.walk('/'):
for dir in dirs:
if pattern.lower() in dir.lower():
print(os.path.join(root, dir))
for file in files:
if pattern.lower() in file.lower():
print(os.path... |
ff9358fabcd07d304e679d9412afd745a6fa8eb9 | yennanliu/CS_basics | /leetcode_python/Linked_list/merge-two-sorted-lists.py | 6,265 | 4.15625 | 4 | """
Merge two sorted linked lists and return it as a sorted list.
The list should be made by splicing together the nodes of the first two lists.
Example 1:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Example 2:
Input: l1 = [], l2 = []
Output: []
Example 3:
Input: l1 = [], l2 = [0]
Output: [0]
Co... |
e1f3ff980bc735ae55c8362106b8004a9cac6fe6 | ntrx/cryphdataprotector | /rsa.py | 1,858 | 3.671875 | 4 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
import functions as func
import time
import os
## INPUT:
# rsa (text, [enc/dec - 1/0],[enc/dec settings 1 - manual, 0 - auto], p, q)
# 1: text - input text (letters)
# 2: method - number '1' if encode
# - number '0' if decode
# 3 4 5:- parametres p and q, e... |
22ea2ceb40f9ac3d93bf691936476f9971d42cb6 | tpauls/tic_tac_toe | /moving.py | 2,193 | 4.25 | 4 |
def get_selection():
x = input (f'Select column 1, 2, or 3: ')
while True:
try:
x = int(x)
if x < 1 or x > 3:
raise ValueError
break
except:
print (f'"{x}" is an invalid column entry!')
x = input (f'Select again column ... |
2bd6248130c69c882fc808ff1444350aafa508e9 | vaishnavivisweswaraiah/Cloudcomputing_Big-Data-Programming | /pyspark_transormation_Action.py | 972 | 3.90625 | 4 | from pyspark import SparkContext
from operator import add
#Question 3.1 How much did each seller earn? Develop the Spark RDD
# (Spark RDD means using only the transformations and actions, no DataFrame/SQL) version to solve the query.
#Creates sparkContext
sc=SparkContext(appName="seller_earn_RDD_transformation_acti... |
c7282b1ea3e2eda9ed1e4b31381b70228c58483e | jl-robledo/python_DAW | /pandas/programacionFuncional7_ComprensionListas.py | 1,450 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 08:42:48 2021
@author: Jose Luis Robledo
Comprensión de listas
Es un tipo de construcción que consta de una expresión que determina cómo
modificar los elementos de una lista, seguida de una o varias clausulas for y,
opcionalmente, una o varias clausulas... |
7cc4acc5ca4a034beb69a4434c734b81f6a75cfe | zengcong1314/python1205 | /lesson02_data_type/demo06_字符串操作.py | 293 | 3.71875 | 4 | name = "yuze wang"
#字符串的变量,字符串操作
#首字母大写
print(name.title())
print(name.lower())
print(name.upper())
#find:查找某个子字符串,如果能够找到,返回索引值
print(name.find("w"))
print(name.find("wa"))
print(name.find("a"))
print(name.find("wg")) |
3c4e25351b46363a2772bff5c1b4dc88925dcf92 | baggy2797/Leetcode | /sort-colors/sort-colors.py | 714 | 3.84375 | 4 | class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.sort()
# length = len(nums)
# left = 0
# right = length-1
# while left <= right:
# if nums[left] is n... |
f7c8a1a05cb3c5300a5b831188bb3f1ebe77f5e8 | JohnEFerguson/ProjectEuler | /p36.py | 435 | 3.671875 | 4 | #!/usr/bin/env python
#
# Jack Ferguson 2018
#
# Problem 36
#
# q: Find the sum of all numbers less than 1000000 which are a palindrome in decimal and binary representations
# a:
#
from helpers.binary import binary_string
from helpers.palindrome import is_palindrome_str
LIMIT = 1000000
ans = 0
for i in range(0, LIM... |
d85a6989c78e0f61d9a62e032d481ff166c74d19 | EdisonKagona/Algorithms | /ReverseWord.py | 950 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 5 07:45:57 2020
@author: Edison Kagona
"""
"""
Write a function that takes in a string of one or more words, and returns the same string,
but with all five or more letter words reversed (Just like the name of this Kata).
Strings passed in will consist of only letters ... |
fcff8ecb41d469a3f391ed544f119ef4c8d12fa4 | StefGou/pyp-w1-gw-language-detector | /language_detector/main.py | 441 | 3.671875 | 4 | # -*- coding: utf-8 -*-
def detect_language(text, languages):
globalcount = 0
lang = ""
for dictionary in languages:
count = 0
for word in text.split():
if word in dictionary['common_words']:
count += 1
... |
9667c6102fb577a4c1b3cbc02f8502e7c2a70e06 | Keemthecoder/anothaone | /proj04_lists/proj04.py | 1,440 | 4.21875 | 4 | # coding=utf-8
# Name:
# Date:
"""
proj04
practice with lists
"""
#Part I
#Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#and write a program that prints out all the elements of the list that are less than 5.
for a in range(0,5):
print list1
y = int(raw_input("How many num... |
22493e7b961a3a724d5a7ec8724befbf98d4ac5a | Ivanqza/Python | /Python Fundamentals/FinalsExamTraining/Mirror words - regex.py | 849 | 3.921875 | 4 | import re
pattern = r"(?P<separator>@|#)(?P<word1>[A-Za-z]{3,})(?P=separator)(?P=separator)(?P<word2>[A-Za-z]{3,})(?P=separator)"
text = input()
matches = [match.groupdict() for match in re.finditer(pattern, text)]
if not matches:
print(f"No word pairs found!")
print(f"No mirror words!")
else:
print(f"{l... |
1901e2f96c1bdf9365c6a8e4523bd54ee4850641 | AlexFletcher/CellBasedHackathon | /Openalea/CPIBOpenAlea/sa_oa/ext/color.py | 17,163 | 3.5625 | 4 | import random as rd
class Color (object):
"""Classe managing simple color : R,G,B and Transparency
:author: Jerome Chopard
:license: don't touch"""
def __init__ (self, red=0, green=0, blue=0, alpha=1) :
"""constructor, store the components of a color with values between 0 and 1
:Parameters:
... |
bd4f8df0bfcb23092b346c796bcece0178f5d6f8 | bouillotvincent/coursNSI | /gui_04.py | 1,253 | 3.5 | 4 | # Le but de cette application est de voir comment « lier » les mouvements
# de la souris au Canvas afin de récupérer les coordonnées de la souris et
# de les afficher à chaque mouvement (en temps réel) dans la zone de texte.
##----- Importation des Modules -----##
from tkinter import *
##----- Définition des Fonctio... |
c2c84ec6b0ea7748031598f2478ab26585d42551 | MonkeyDCode/Calculo-de-Metricas | /sample1.py | 221 | 3.75 | 4 | #Mario Alberto Gutierrez Corral
#invertir una cadena
#definicion de funciones
def CadC(C):
n=len(C)
if (n == 1):
return C
else:
return C[-1]+CadC(C[:-1])
#P.P
C = raw_input("Cual es el texto: ")
print CadC (C)
|
66cb920df601ffec309f337d018a2e8cda2b9476 | wqh872081365/leetcode | /Python/014_Longest_Common_Prefix.py | 576 | 3.671875 | 4 | """
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
list_str = sorted(strs)
result = 0
if len(list_str) == 0:
... |
756fbc188e96e92906037c00b81853db02450134 | MurradA/pythontraining | /Challenges/P016.py | 304 | 4.1875 | 4 | isRain = input("Is it raining? (Yes/No):".strip())
if isRain.lower() == "yes":
isWindy = input("Is it windy? (Yes/No):".strip())
if isWindy.lower() == "yes":
print("Is it too windy for an umbrella!".strip())
else:
print("Take an umbrella!")
else:
print("Enjoy your day!") |
267d19c702201517338ae8b06bbbbff6ffdaf7d5 | farjadfazli/code-challenges | /binarysearch_odd-number-of-digits.py | 413 | 4.28125 | 4 | """
Odd number of digits
Given a list of positive integers nums, return the number of integers that have odd number of digits.
Example 1
Input
nums = [1, 800, 2, 10, 3]
Output
4
Explanation
[1, 800, 2, 3] have odd number of digits.
"""
class Solution:
def solve(self, nums):
result = 0
for num... |
87da9fd9a0d4845ed22a9af7b45849b0e92bb40b | mtianyan/LeetcodePython | /126-word-ladder-ii.py | 7,176 | 3.734375 | 4 | from collections import defaultdict
from typing import List
from collections import deque
import string
class Solution:
"""
链接:https://leetcode-cn.com/problems/word-ladder-ii/solution/yan-du-you-xian-bian-li-shuang-xiang-yan-du-you--2/
"""
def findLadders(self, beginWord: str, endWord: str, wordList:... |
143ec55ad2d418e2c7cf38b3083fe91f9f9e2a93 | daniel-reich/ubiquitous-fiesta | /ch3ZsbzJt56krcvhy_6.py | 284 | 3.890625 | 4 |
def square_root(n):
low, high = 1, n
while low <= high:
mid = (low + high) // 2
sq = mid**2
if sq == n:
return mid
if sq < n:
low = mid + 1
ans = mid
else:
high = mid - 1
return ans
|
774492bc499514d911be473c11633a2f9307a699 | Helton-Rubens/Python-3 | /exercicios/exercicio067.py | 300 | 3.78125 | 4 | print('\033[1;4;35mTABUADA!\033[m\n')
while True:
numero = int(input('Quer ver a tabuada de qual valor? '))
print('---'*10)
if numero <= 0:
break
for cont in range(1, 11):
print(f'{numero} x {cont} = {numero * cont}')
print('---'*10)
print('Programa finalizado!')
|
69bb7644389703eb52a97e789cabe71b7cc4d5ac | drafski89/useful-python | /multipool/multiappend_tofile_py2.py | 4,885 | 3.96875 | 4 | #!/usr/bin/env python
# Imports
import multiprocessing
from multiprocessing import Lock
import time
OUTPUT_FILE_NAME = "multiappend_results"
# Constant for the count function to count to
# Higher number will show greater differences in multithreading
COUNT_TO_NUMBER = 10000000
# count function
# Purpose: Count fro... |
5f2537595343bb3df8e74bcec70df74848d580bf | jijiaxing/python_basic | /作业/day07/hm_03_global方法.py | 315 | 3.828125 | 4 | #如果在函数中需要修改全局变量,需要使用global进行
num = 10
def demo1():
print("demo1"+"-"*50 )
#global关键字,告诉编辑器num是一个全局变量
global num
num = 100
print(num)
def demo2():
print("demo2"+"-"*50)
print(num)
demo1()
demo2()
print("over") |
eb2522976506e124232b43bd53a6bf952c442ea8 | briansu2004/Unscience-Computer-Hackerrank | /hackerrank/solutions/palindrome_index.py | 957 | 4 | 4 | #!/bin/python3
#
# Problem Author: amititkgp @ hackerrank
# Difficulty: Easy
# link: https://www.hackerrank.com/challenges/palindrome-index/problem
#
# Solution:
# - Author: Byung Il Choi (choi@byung.org)
# - Video: https://youtu.be/fDn7QGOWcYo
#
import math
import os
import random
import re
import s... |
7f4658fe65a9c6007f2d38edf3d406b69d93ee2a | Raekian/function_basics_two | /functions_basic_two.py | 645 | 3.765625 | 4 | def countdown(num):
countList = []
for x in range(num, 0, -1):
countList.append(x)
return countList
print(countdown(5))
def printReturn (list):
print(list[0])
return list[1]
printReturn([5,6])
def firstPL(list):
return (list[0] + len(list))
print(firstPL([1,2,3,4,5]))
def greate... |
13731ab91a61e3ff69e257819aa9762e69a9fbd4 | goWithHappy/python | /test/asynchronousIO/yieldDemo.py | 154 | 3.921875 | 4 | def odd():
print('step 1')
yield 1
print('step 2')
yield 3
print('step 3')
yield 5
o=odd()
for i in range(1,5):
print(next(o)) |
bf9920748710b7b0daf69b84f68091eeacd08bd1 | mlanjula94/Leetcode_Interview_questions_1 | /FizzBuzz.py | 432 | 3.703125 | 4 | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
FBArray = []
for n in range( 1, n+1):
if n % 3 == 0 and n % 5 ==0:
FBArray.append("FizzBuzz")
elif n % 3 == 0:
FBArray.append("Fizz")
elif n % 5 ==0:
... |
c66526885ec0fb419daf49868de07c161cfb242d | assassint2017/Classic-machine-learning-algorithm | /python_code/sklearn_code/naive_bayes/MultinomialNB.py | 591 | 3.546875 | 4 | """
朴素贝叶斯分类器中的多项式模式
用于处理离散特征
"""
from sklearn import naive_bayes
from sklearn import datasets
import sklearn.model_selection as ms
bayes = naive_bayes.MultinomialNB()
digits = datasets.load_digits()
data = digits.data
label = digits.target
train_data, test_data, train_label, test_label = ms.train_test_split(data, ... |
064ae82141e73ff5e198fce475690d5a1d705bb1 | Nagarjuna-H0/training | /practice.py | 68 | 3.53125 | 4 | i=int(input("enter i val"))
j=int(input("enter j value"))
print(i+j) |
b8849d7685a9563705178bf1300295a29fc9a1e0 | Gifly/Actividad2 | /Snake.py | 3,026 | 3.65625 | 4 | from turtle import *
from random import randrange
from freegames import square, vector
import random
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
def colorRand(init):
"Randomizes the colors"
val=random.randrange(1,6) #Genera un número del 1 al 5 aleatoriamente
if val==1: #En cas... |
7d657307ffc4319f3289428f333e6fb8f03460a4 | ajy720/Algorithm | /Programmers/level 1/정수 제곱근 판별.py | 244 | 3.796875 | 4 | from math import sqrt
def solution(n):
answer = 0
t = int(sqrt(n))
if t**2 == n:
answer = (t+1)**2
else:
answer = -1
return answer
if __name__ == "__main__":
n = int(input())
print(solution(n))
|
d9a413ddc7eeb7b5a99969fab49647167fdf27e9 | CodingAW/C98---Functions | /mTable.py | 176 | 4 | 4 | def table():
num = float(input("Enter the number: "))
tableNum = num
for i in range(10):
print(tableNum)
tableNum = tableNum + num
table() |
fb0ff2976cee49d57779c37f48c3bb8e5baf2bf5 | machil1/CPS-3320 | /filehangman.py | 2,741 | 4.09375 | 4 | #Lawrence Machi III
#Below will pick a random word to choose for hangman
import random
#A = ['p','y','t','h','o','n']
#B = ['d','o','m','a','n','s','k','i']
#C = ['k','e','a','n']
#D = ['p','o','d','c','a','s','t']
#selection = [A,B,C,D]
#selection = random.choice(selection)
selection = []
f = open("selection.txt",... |
6983bea9b9c9d891aa54f5493e4fc29f5f53ffa7 | Brad-Kent/CSSE1001_Assignment-1 | /a1.py | 4,695 | 3.578125 | 4 | #!/usr/bin/env python3
"""
Assignment 1
CSSE1001/7030
Semester 2, 2018
"""
from a1_support import is_word_english
import a1_support as a1
__author__ = "Brad Kent, s45355194"
def procedual_menu():
print("Welcome")
while True:
# Display Menu Options
display_user_options()
... |
f173e14bd602194801d681b3968908c1cadc9e3c | a93-git/codingame-solutions | /clash/reverse/rev-clash10.py | 551 | 3.671875 | 4 | """ If any one bit in the corresponding bits of two given binary numbers is 1, set that bit to 1, else 0
00101
10100
------
10101
"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
t = input()
t2 = input()
print(t, t2, file=sys.... |
8dedda99cd4d56f2002e1642279f4394b51f6a92 | Washington-bezerra/Python-Execicios | /Exercicio 096.py | 370 | 4 | 4 | #faça um programa que tenha um função, que receba as dimensões de um terreno retangular (altura e comprimento) e mostre a área do terreno.
print(f' CONTROLE DE TERRENO', f'\n', f'-'*22)
def terreno(a, b):
print(f'A área de um terreno {a} x {b} é de {a*b}m²')
a = float(input(f'ALTURA (m): '))
b = float(inp... |
e1f1df976f2c10f1c1d2f15e4d1451f311dc9806 | xCrypt0r/Baekjoon | /src/10/10698.py | 458 | 3.765625 | 4 | """
10698. Ahmed Aly
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 23일
"""
from sys import stdin
input = stdin.readline
def main():
for i in range(1, int(input()) + 1):
question, answer = input().split(' = ')
if eval(question) == int(answer):
print(f'Case... |
43ca16ded0d002ca940835551ed13d6508a4a693 | NikiDimov/SoftUni-Python-Fundamentals | /basics/!special_numbers.py | 608 | 3.953125 | 4 | number = int(input())
# for num in range(1, number+1):
# sum_of_digits = 0
# digits = num
# while digits > 0:
# sum_of_digits += digits % 10
# digits = int(digits/10)
# if sum_of_digits == 5 or sum_of_digits == 7 or sum_of_digits == 11:
# print(f"{num} -> True")
# else:
# ... |
8fdc9a113c1bcf28087ec892d9a0896f67c546af | d-r-e/machine_learning-bootcamp-42AI | /day02/ex00/sigmoid.py | 257 | 3.5 | 4 | #! /usr/bin/env python3
import numpy as np
def sigmoid_(x):
return 1 / (1 + np.exp(-x))
if __name__ == "__main__":
x = -4
print(sigmoid_(x))
x = 2
print(sigmoid_(x))
x = np.array([-4, 2, 0])
print(sigmoid_(x))
|
f1c95888802c5f22b21e0252c4f34bf842b6f34d | Alfinus/crash_course_in_python | /chapter_7/confirmed_users.py | 662 | 4.03125 | 4 | #combining while loops with dictionaries
#starting with users that need to be verified
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'biran', 'candace']
confirmed_users = []
#verify each user until there are no more unconfirmed users.
# Move each verified user into the list of c... |
59efacf8de4b3dc0d96589e76518673bef0d57f2 | DavidFontalba/DAW-Python | /secuenciales/7minutos.py | 856 | 4.125 | 4 | # Programa para convertir minutos en horas:minutos:segundos
# Autor: David Galván Fontalba
# Fecha: 10/10/2019
#
# Algoritmo
#
#Pedir minutos
#Cálculo:
# hh <-- minutos//60
# mm <-- ((minutos/60)-(hh))*60
# ss <-- (mm - int(mm)*60)
#Muestro resultado
print("Bienvenido a este programa que transformará los minutos que ... |
9c5de8ceb0d242a9b4f43b169ff56f593f2ff494 | TewariSagar/Python | /fileWriting.py | 460 | 4.125 | 4 | #the 'w' atttribute is only for writing to a file but if the file doesnt exist it creates the file. If the file already exists it just overwrites it
#newfile.txt doesn't exist so this file will be created in the PWD
newfile = open("newfile.txt","w")
newfile.write("I like python\ndo you?\nthis is a bad way of writing\... |
12724ac97109e24c75c50cd18e75839400cdf38b | taitujing123/my_leetcode | /074_searchMatrix.py | 1,317 | 3.90625 | 4 | """
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例 1:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(obj... |
d1bdac9d5694096fb6f99b1ff0044234bd2763bd | minus9d/python_exercise | /dive_into_python3/ch06_generators.py | 1,640 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
def build_match_and_apply_functions(pattern, search, replace):
def matches_rule(word):
return re.search(pattern, word)
def apply_rule(word):
return re.sub(search, replace, word)
return (matches_rule, apply_rule)
def rules(rules... |
e401226c7f99127a48c7979e4950db911d697588 | ArturVargas/Intro-a-Python3 | /12_Class_and_Obj/app.py | 781 | 3.515625 | 4 |
# Del archivo Student importa la clase Student
from Student import Student
# Por buenas practicas cada clase deberia estar en su
# archivo correspondiente, pero para fines practicos lo hice en el mismo
from Student import Person
#Creamos nuestro primer estudiante
# Enviamos los parametros en el mismo orden como los... |
86e3d64b34ded28d57da0b21992f4f60d38a6683 | jeanpratt/star-site | /utils.py | 1,656 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
FIRST_YEAR = 2013
FALL_START_MONTH = 8
###
### Semesters are always formatted as semester_year (e.g., “fall_2013”, or “spring_2014”)
###
def is_fall():
return datetime.now().month >= FALL_START_MONTH
def format_semester(semester, year):
... |
33c5b21d8639c7b61f6ee0b64dd570f15445751f | YashKhant2412/MovieInfoBot | /Code/conn.py | 522 | 3.546875 | 4 | import sqlite3
from openpyxl import load_workbook
conn = sqlite3.connect('Movie.db')
wb = load_workbook('Movie.csv')
ws = wb['Movie']
conn.execute("create table if not exists Movies (movie text, seat text, price int)")
for i in range(1,10):
temp_str = "insert into food_items (movie, seat, price) values ('{0}', '... |
8a738a9565e4643a17bcd21d1acc617f76e5246a | homezzm/leetcode | /LeetCode/简单/053MaximumSubarray.py | 283 | 3.84375 | 4 | class Solution(object):
def maxSubArray(self, nums):
n=len(nums)
for i in range(1,n):
if nums[i-1]>0:
nums[i]+=nums[i-1]
return max(nums)
if __name__ == '__main__':
solution=Solution()
print(solution.maxSubArray([-2])) |
a79e79e731024639e70f2f8d8293eb1d3711a527 | AzraHa/introduction-to-python | /8/8.2.py | 83 | 3.5625 | 4 | n = input()
while n!="":
if n[0]!="b":
print(n,end =" ")
n=input()
|
93c37d67449eeae809daba975f642d80d1fc3c3f | dpezzin/dpezzin.github.io | /test/Python/dataquest/functions_debugging/make_tokens_lowercase.py | 505 | 4.5 | 4 | #!/usr/bin/env python
# We can make strings all lowercase using the .lower() method.
text = "MY CAPS LOCK IS STUCK"
text = text.lower()
# The text is much nicer to read now.
print(text)
# The tokens without punctuation have been loaded into no_punctuation_tokens.
# Loop through the tokens and lowercase each one.
# Ap... |
196db9ab5afcf2b148356663c4a538a9649c5af1 | brian-ketelboeter/learning-python | /7_counting.py | 572 | 4.03125 | 4 | counting_number = 0
prompt = "Tell me how long you want me to run."
prompt += "\nGive me an integer value greater than 1: "
number = input(prompt)
while counting_number <= int(number):
counting_number += 1
if counting_number % 2 == 0:
continue
print(counting_number)
prompt = "Tell m... |
adec6d9ec353999295bdb92360eead10762e59ea | SunkeerthM/CSES | /Sorting and Searching/sum_of_two_values.py | 449 | 3.5625 | 4 | '''
CSES Problem Set
Sorting and Searching - Sum of Two Values
# Author : Sunkeerth M
# Description : https://cses.fi/problemset/task/1640
# Date : 10-08-2020
'''
n, ar_sum = map(int,input().split())
arr = list(map(int,input().split()))
d_1 = dict()
for i in range(n):
p = arr[i]
if ar_s... |
11db762066af042710aa4b380527774b405b6028 | jonsant/python | /uppg/uppg1.py | 221 | 3.640625 | 4 | print("Vad heter du? ")
namn = input()
print("Hur gammal är du? ")
age = input()
print("Hej, " + namn.title() + "!\n" + age + "??? ojoj!")
if int(age) < 50:
left = 50 - int(age)
print("50 om " + str(left) + " år!")
|
7a293463ada5b767466a4c4e8a18066f363018d6 | CaioAntunes3/CodePython-C-to-F | /Tabela c to f.py | 198 | 3.546875 | 4 | #tabela de fahrenheit para celcius de 50 a 150
f = 49.0
celcius = 0
for i in range (50,151,1):
celcius = 5/9 * (f - 32)
f += 1
print("fahrenheit =",f,"celcius = %.2f" %celcius) |
34fcdb4951ec2872aa753391173369ea0079d55a | leticiafelix/python-exercicios | /09 - Tuplas/desafio074.py | 396 | 3.90625 | 4 | #faça um programa que gere 5 numeros aleatórios e coloque numa tupla, depois disso mostre a listagem dos números gerados
#e indique o menor e o maior valor da tupla
from random import randint
n = (randint(1,10), randint(1,10), randint(1,10), randint(1,10), randint(1,10))
print(f'Os valores sorteados foram: {n}'
... |
e6ba4a9685ba74921d3eb328f97d53516f4a1a55 | FelixOnduru1/100-Days-of-Code | /Day10/calculator.py | 1,140 | 4.21875 | 4 | def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def divide(n1, n2):
return n1/n2
operations = {"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
num1 = f... |
51db4822f6d5415c806f1122902119d884c578e9 | ciyengar3/ComputerVisionPrograms | /cropandaverage.py | 4,174 | 3.546875 | 4 | import cv2
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False
higherbound = 5
stepsize = 10
def click_and_crop(event, x, y, flags, param):
... |
6e368ba32ad0e72d6b65f090471988589f196e32 | grwkremilek/leetcode-solutions | /python/0020.valid-parentheses/valid_parentheses.py | 384 | 3.78125 | 4 | #https://leetcode.com/problems/valid-parentheses/
def isValid(s):
parents = {')' : '(', '}' : '{', ']' : '['}
stack = []
for i in s:
if i in parents.values():
stack.append(i)
else:
if stack and stack[-1] == parents[i]:
stack.pop()
... |
43b4c608e20b0c9c9b900a1eaf838f86537d0f61 | yuqiaoyan/Python | /soshProblem.py | 1,642 | 4 | 4 | #-------------------------------------------------------------------------------
# Name: soshProblem
# Purpose:
#
# Author: Bonnie
#
# Created: 10/02/2012
#-------------------------------------------------------------------------------
import sys
def insertInSortedArray(line,pos,topN):
#gi... |
8c2d9ad1405e2f173724f3eb68144804ffc12312 | JustKode/python-algorithm | /2.Sort/bubble_sort.py | 217 | 3.859375 | 4 | def bubble_sort(list_var):
for i in range(len(list_var) - 1):
for j in range(i, len(list_var)):
if list_var[i] > list_var[j]:
list_var[i], list_var[j] = list_var[j], list_var[i] |
7bcb8fba79de5b99e7a62f86a0e291c521f0ba3c | UniquelyElite/Advent-Of-Code-2020 | /Day3/task2/index.py | 1,050 | 3.734375 | 4 | #Open and gather the information from a txt file
information = open("./Day3/input.txt")
forest = information.read()
lines = forest.split("\n")
#Get the width of the trees before they repeat
width = len(lines[0])
treeArray = []
path = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]]
def calculate(right, down) :
#For locati... |
4356cc3f58b37ab7e901b6f062cc3b3d95e288a5 | udhayprakash/PythonMaterial | /python3/19_Concurrency_and_Parallel_Programming/01_MultiThreading/a_function_based/b3__join_get_primes.py | 946 | 3.875 | 4 | from threading import Thread
# Callable function forming the thread body for the Prime Number Producer
def get_prime_numbers():
print("Prime number thread started")
# 2 is a prime number
print(2)
for each_num in range(2, 20):
is_prime = False
for divisor in range(2, each_num):
... |
7268972bed2067608a946f741826643f9d3fdb79 | eliasscosta/exercicios_python | /gerarlista_primos.py | 121 | 3.6875 | 4 | n = int(raw_input('Entre com nuermo: '))
for k in range(2,n):
while n % k == 0:
print k
n = n/k
|
2e332924921d72e13fdd3fdff650796f82396e70 | DavidMS51/Microbit-Scroll-Display | /node_scroll_show3.py | 2,291 | 3.5625 | 4 | # microbit Scrolling Display application - 1 of 3 applications
# David Saul copyright 2017 @david_ms, www.meanderingpi.wordpress.com
# Inspired by and utilising code by David Whale [@whaleygeek]
# Available under MIT License via github.com/DavidMS51
# This code is for the display node microbits. This listens for mes... |
2afdc8553420a6f367e500fba770eadec2fe1256 | Pariyat/Quick-Data-Science-Experiments-2017 | /support_vector_machines/perceptron/perceptron.py | 1,856 | 3.765625 | 4 | # https://blog.dbrgn.ch/2013/3/26/perceptrons-in-python/
from random import choice
import numpy as np
def heavyside_step_function(val):
res = np.greater_equal(val, np.zeros(val.shape)) * 1
res[res == 0] = -1
return res
'''
X is an array of shape (N, dim), last dim is 1 (for \beta_0)
y is an array of shape (N,), w... |
4d30de8611edc824f597aef6b97df9cad2b3c87a | vinibrsl/project-euler | /problem-12.py | 294 | 3.765625 | 4 | def divisors_count(n):
count = 0
for i in range(1, n+1):
if (n % i) == 0:
count += 1
return count
def triangulate(n):
y = [int(x) for x in list(str(n))]
return sum(y)
triangle = 1
while divisors_count(triangle) <= 500:
triangle += triangulate(triangle)
print(triangle)
|
b8aa85427d23e95afb533d01c826dd6b493536e9 | chriseverts/python-exercises | /list_comprehensions.py | 4,413 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 17, 19, 23, 256, -8, -4, -2, 5, -9]
# Example for loop solution to add 1 to each number in the list
numbers_plus_one = []
for number in num... |
8e48a9e532595fd4bbe4d5dadb80b8a5a424d08c | ajbaldini/code_practice | /hash_map_questions/palindrome_permutations.py | 1,389 | 3.828125 | 4 | """
write a function that given a string checks if a palindrome is possible and generates as many permutations as possible
does not have to return sensible words
"""
def isPalindrome(h_left, right_s, middle_c):
h_left = h_left
right_s = right_s
middle_c = middle_c
for c in right_s:
if c in h_l... |
9c04275fba003f1acfd476f30545e7768ce724fb | lheinke-astro/plotext | /plotext/nums.py | 3,527 | 3.71875 | 4 | def decimal_characters(characters = 3):
dec_characters = characters - 2
return dec_characters
def decimal_points(characters = 3):
dec_characters = decimal_characters(characters)
if characters == 1 or characters == 2:
dec_characters = 0
return dec_characters
def delta(level = 0, characters ... |
c3014798da9fb8e3326e3fcaa3fe5c2b76834db7 | p-ambre/Hackerrank_Coding_Challenges | /birthday_cake_candles.py | 1,057 | 3.9375 | 4 | #You are in-charge of the cake for your niece's birthday and have decided the
#cake will have one candle for each year of her total age. When she blows out
#the candles, she’ll only be able to blow out the tallest ones. Your task is to
#find out how many candles she can successfully blow out.
#For example, if your nie... |
3e10110752be45ea34672f93baec8ad208d1589c | turbocornball/Asymptotic-Analysis | /analysis.py | 1,463 | 3.625 | 4 | import matplotlib.pyplot as plt
import time
import math
log_time = []
linearithmic_time = []
linear_time = []
quadratic_time = []
polynomial_time = []
exponential_time = []
inputs = []
n = 5
def logarithmic(n):
return math.log(n)
def linearithmic(n):
return n*math.log(n)
def linear(n):
return n
de... |
d5c7ac4897b7eb77eceb69e002ca03c3e74bfc38 | suhasreddy123/python_learning | /example programs/Python Program to Find the Sum of Natural Numbers.py | 148 | 4.09375 | 4 | #Python Program to Find the Sum of Natural Numbers
n=int(input())
sum1=(n*(n+1))/2
print(sum1)
sum=0
for i in range(1,n+1):
sum=sum+i
print(sum) |
e50f5d2330c35f37d918978c3abc6460be9f7476 | tuthanmadao/PyThoncode | /Buoi8_bai2_themchuoivaocuoifile.py | 795 | 3.734375 | 4 | """
Bài 02: Viết chương trình thêm một chuỗi nào đó vào cuối file
"""
str_add = "Ngôn Ngữ lập trình Python\n"
file_name = "file_test.txt"
def read_file(name):
"""
Đọc nội dung của file
:param name: tên file cần đọc
:return: ko có giá trị trả về.
"""
with open(name, 'r', encoding='utf-8... |
4ffb3bc4858a6bd3087f1e3ecc8875ce820b6cd9 | angelobarbara/python_course | /python_basico/saludos.py | 74 | 3.90625 | 4 | nombre = str(input('¿Cuál es tu nombre?'))
print('Hola ' + nombre + '!') |
56f8dd95c9170eb8b8e11454807b86a5792fe8b1 | adelehedrick/kaggle-workshop | /tutorial.py | 2,264 | 3.765625 | 4 | import pandas as pd
import numpy as np
# 1. Loading the Data Using Pandas
# using pandas we can read the csv file directly into a dataframe
#df = pd.read_csv('data/train.csv')
# 2. Preview the Data
# take a peek at the first ten lines of the csv file
#print(df.head(10))
# 3. Remove irrelevant data
#df = df.drop(['... |
22a4182cb4d06fccf4fa048ae51d5b36401bca17 | MaferMazu/FuncionSeguroConTDD | /Person.py | 798 | 3.515625 | 4 | import datetime
MIN_AGE_PENSIONM=60
MIN_AGE_PENSIONF=55
MIN_QUOT= 750
class Person:
def __init__(self, name, genre, birth, quotation):
self.name = name
self.birth = birth
self.genre = genre
self.quotation = quotation
def __str__(self):
return "Persona de genero: " +... |
36988611ac3b5257d656219b3c417e20a488ae86 | burakbayramli/books | /Social_Network_Analysis_for_Starupts/chapter6/friedkin.py | 2,131 | 3.65625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
friedkin.py
Created by Maksim Tsvetovat on 2011-08-08.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import sys
import os
import networkx as net
import matplotlib.pyplot as plot
import matplotlib.colors as colors
import random as r
class Person(object):
... |
3ecf28db702fb15aaec5d2bd375b47d8af8a4a0e | Stvaik/Python_lessons_basic | /lesson03/home_work/hw03_normal.py | 2,060 | 3.90625 | 4 | # Задание-1:
# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.
# Первыми элементами ряда считать цифры 1 1
def fibonacci(n, m):
pass
for Y in range(0, 5 + 1):
print(Y)
def fibonacci(n, m):
a = []
golden = 1.618034
for i in range(n, m + 1):
x = (golden ** i - (1 -... |
62c17340f762bcfe44c2790fbcfd7b774b2c0c42 | mspontes360/Programacao-Python-Geek-University | /section5/exercicio31.py | 1,024 | 4.28125 | 4 | """
Faça um programa que receba a altura e o peso de uma pessoa. De acordo com a tabela
a seguir, verifique e mostra qual a classificação dessa pessoa.
Altura Peso
Até 60 Entre 60 e 90 (Inclusive) Acima de 90
Menor que 1.20 A D ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.