blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f712a98de96dc6ee40cdfacadd6f900d1574f69e | Hwisaek/MJU | /Project/PythonProgramming/과제2/이창민60142013-2.py | 415 | 4.0625 | 4 | print("문제 1")
str1=input("문자열 1: ")
str2=input("문자열 2: ")
print(str1+" "+str2)
print("문제 2")
speed=input("차의 속도를 입력(km) >> ")
speed2=int(speed)/1.61
print(speed,"(km)은 ",speed2," 마일(miles) 입니다.")
print("문제 3")
a=40120
b=6378.1*3.141592*2
print("알려진 지구 둘레: ",a)
print("지구와 같은 원 둘레: ",b)
c=float(a)-float(b)
print("차이: "... |
b33092331c86dab914e4e2c5882b2bc5d10c197a | mVolpe94/Python-Practice | /fizzbuzz.py | 618 | 3.625 | 4 | import time
multiples_list=[3,5,10,6]
fizzbuzz_list = ['fizz', 'buzz']
def fizzbuzz(i, multiples_list):
output = ""
for index in range(len(multiples_list)):
if i % multiples_list[index] == 0:
if (index + 1) % 2 == 0:
char = fizzbuzz_list[1]
else:
... |
3071f722faa54b489992b153651e53a813912d13 | iCodeIN/competitive-programming-5 | /leetcode/Tree/binary-tree-longest-consecutive-sequence.py | 1,003 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestConsecutive(self, root: TreeNode) -> int:
# https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/... |
1cdd063255c960b109997758905d517899729475 | mpsb/practice | /codewars/python/cw-rainfall.py | 2,398 | 4.21875 | 4 | '''
dataand data1 are two strings with rainfall records of a few cities for months from January to December. The records of towns are separated by \n. The name of each town is followed by :.
data and towns can be seen in "Your Test Cases:".
Task:
function: mean(town, strng) should return the average of rainfall for t... |
4697dee77206fa21aa35a4d2c6f483cdaf146748 | vggithub7/nitkkr | /ML LAB/Python lab/17th/Pro2.py | 871 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 22:52:21 2018
@author: sunbeam
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# data cleaning
# read the datset
df = pd.read_csv('/home/sunbeam/MLPractise/dataset/50_Startups.csv')
df_x= df.iloc[:,0:4].values
df_y ... |
152dbc8e30529f18b24a948a5bf37779f0de0d46 | ramielrowe/notabene | /notabene/flatten_notification.py | 1,619 | 3.6875 | 4 | # Copyright 2014 - Dark Secret Software Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
97d94556e690f781fb9f1c9e9c472e2f79cb0cec | JayzLiu/CodingInterviews | /P31_stack_push_pop_order.py | 1,211 | 3.59375 | 4 | class Solution(object):
def is_legal_order(self, push_order, pop_order):
if len(push_order) != len(pop_order):
return False
if not push_order or not pop_order:
return False
index = 0
aux_stack = []
for num in pop_order:
if aux_stack and aux... |
7dd78d3300b149ebcac207f50db2a5c81f5d87cc | qinyia/diag_feedback_E3SM | /generate_html.py | 5,586 | 3.625 | 4 |
def generate_html(casedir,webdir=None):
'''
Dec 22, 2021: generate html page to visualize all plots.
input:
casedir -- the directory where related files are saved.
webdir -- the directory where you can open the html file.
Both compy and nersc have such web server.
Yo... |
6cd96bdb290da1832408aa019e7e81abfb5338c6 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4367/codes/1649_2443.py | 397 | 3.640625 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
from math import*
r=float(input("escolha o raio"))
a=float(input("escolha a altura"))
n_o= int(input("escolha 1 ou 2"))
if(n_o==1):
v=(pi*a**2*(3*r-a))/3
print(ro... |
548d130c493e471f9abd3598c7906ea90ff8af81 | GenyGit/python-simple-code | /function02.py | 296 | 3.953125 | 4 | #вычисляет значение функции. разные формулы в зависимости от участка х
def fx(x):
if x <= -2:
return 1 - (x + 2) ** 2
elif -2 < x <= 2:
return -1 * (x / 2)
else:
return (x - 2) ** 2 +1
print(fx(0))
|
f9b89734503a57e4f1039a64ff25c1401e45d5c8 | chinku8431/PythonFolder | /Functions/Udemy/Map.py | 114 | 3.5625 | 4 | def add(x):
#return x+2
return x*2
newlist=[10,20,30,40,50]
result=list(map(add,newlist))
print(result) |
d684bdeeb66b806d1b269b4bdc1a6eb11d293132 | hsclinical/leetcode | /Q02__/56_Paint_House/Solution.py | 645 | 3.5 | 4 | from typing import List
class Solution:
def minCost(self, costs: List[List[int]]) -> int:
n = len(costs)
if n == 0:
return 0
else:
total = costs[0]
if n == 1:
return min(total)
else:
for i in range(1, n):
... |
40d287b9c577b3428c7c81d8f653975ea6847315 | liuilin610/leetcode | /Tree/144BinaryTreePreorderTraversal.py | 996 | 3.640625 | 4 | # 144 Binary Tree Preorder Traversal
# I recursive
# recursive left child then right child
class solution():
def PreorderTraversal(slef, root):
"""
: type root : TreeNode
: rtype : List[int]
"""
if not root: return None
res = []
res.append(root.va... |
8e98cc807e638cc6947458dd3277078161c033fe | goncalofialho/istKillMe | /fp/Sopa de letras/Nova pasta/projeto_2_tiporesposta.py | 2,893 | 4.0625 | 4 | #tipo resposta
def resposta(lst):
"""
resposta : lista de tuplos(string; coordenada) --> resposta
resposta(lst) tem como valor a resposta que contem cada um dos tuplos que
compoem a lista lst.
"""
if isinstance (lst, list):
for a in range (len(lst)):
if isinstance(lst[a], tu... |
fc29c1b40b537c358c09fcaa86c1f1784fa320ae | lcc19941214/python-playground | /src/functional-programming/higher-order-functions/sorted.py | 611 | 3.78125 | 4 | # coding=utf-8
# sorted
'''
not like javascript, sorted in python will return a new list
'''
L = [123, 41, 46, 61, 43]
L2 = sorted(L)
print(L)
print(L2)
# reverse
L = [1, 2, 3, 4, 5, 6, 7]
def fn_reverse(a, b):
if (a < b):
return 1
if (a > b):
return -1
return 0
L2 = sorted(L, fn_reve... |
1a733d8fd04c111f102ad7f84cccee3eca0ab002 | poorna20/Strings | /eveodd.py | 176 | 3.875 | 4 | s=input()
a=list(s)
odd=[]
eve=[]
for i in range(1,len(a),2):
eve.append(a[i])
odd.append(a[i-1])
for i in odd:
print (i,end='')
for i in eve:
print (i,end='')
|
71e9ab00681100eb90404de1c591585fcb816936 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/nth-prime/644855994e3b4ba0bf205487e675c212.py | 369 | 3.984375 | 4 | def nth_prime(target):
i, k = 0, 0
while k < target:
if is_prime(i):
k += 1
i += 1
return i - 1
def is_prime(n):
if n in xrange(2, 3):
return True
if n == 1 or n % 2 == 0:
return False
i = 3
while i < (n * 0.5 + 1):
if n % i == 0:
... |
05f3416fc9f959871305f17b757f233e865ec6b9 | cjc3259/cs373-xml | /SphereXML.py | 4,399 | 3.53125 | 4 | #!/usr/bin/env python
# ------------------------------
# projects/xml/RunXML.py
# Copyright (C) 2013
# Glenn P. Downing
# -------------------------------
"""
To run the program
% python RunXML.py < RunXML.in > RunXML.out
% chmod ugo+x RunXML.py
% RunXML.py < RunXML.in > RunXML.out
To document the program... |
b59a31c59310366c458df5766aa18956fa2bf525 | dong822/insight | /src/pharmacy_counting.py | 1,319 | 3.875 | 4 | file_in=open("insight_testsuite/tests/test_1/input/itcont.txt","r") # read file input
file_out=open("insight_testsuite/tests/test_1/output/top_cost_drug.txt","w") # write file output
drugs={}# drugs store drug_name, num_prescriber, total_cost
next(file_in)# jump the first line
for line in file_in:# loop every l... |
502e869d98e6d177b05a0658913b89d27e1830c3 | MUDDASICK/CodeSamples | /Intro_Python_Net_Eng/functions2/example1.py | 304 | 3.78125 | 4 | def my_adder_function(my_list):
total = 0
for num in my_list:
total = total + num
print(total)
my_adder_function(1,3,5)
#def my_better_adder_function(*args):
# total = 0
# for n in args:
# total = total + n
# print(total)
#my_better_adder_function(1,3,5)
|
45098a5c8c90a2d41cd5370546a721f3e5516286 | ghkdwl1203/python-ml | /Algorithm/연습문제/al-problem5.py | 105 | 3.546875 | 4 |
def ex5(n) :
i=0
while i<n:
if i%3==0 and i%5==0:
print(i)
i = i + 1
ex5(100)
|
7d4a43ca16576e35ebd53db981f42cacb9500811 | richygregwaa/Giraffe | /06 list functions.py | 652 | 4 | 4 | lucky_numbers = [4, 8, 15, 16, 23, 42]
friends = ["Kevin", "Karen", "Jim", "Jim", "Oscar", "Oscar", "Toby"]
print(friends)
friends.extend(lucky_numbers)
print(friends)
friends.append("Creed")
print(friends)
friends.insert(1, "Kelly")
print(friends)
friends.remove("Jim")
print(friends)
# friends.clear()
friends.pop() #... |
61954678906cc0efb07a1e531216cae94073a20b | SaiSriLakshmiYellariMandapaka/Sri_PythonDataQuest | /practice mode_4_python.py | 7,849 | 4.4375 | 4 | #Practice using conditional statements in Python.
#1.
'''If we run this Python code, what will be printed to the screen?
x = 10
y = '10'
if x == y:
print('A')
else:
print('B')
We proposed a few possible answers. Assign to a variable named correct the answer that you think is correct. For example, if you think ... |
5d241c7865bf58f00d9c7450aaac9eedd7286702 | Spookso/draughts | /one_minimax.py | 16,672 | 4 | 4 | import pygame, math, movement, time, random
# Initiates the pygame library
pygame.init()
# Sets up a window of size 800 x 800 pixels with the tag 'resizable'
win = pygame.display.set_mode((800, 800), pygame.RESIZABLE)
# Sets the caption for the window as "Draughts"
pygame.display.set_caption("Draughts")
# allows pyga... |
8fdf9603b3ab51a7e715b594a5e5a0593cd8d442 | IvanCampelo22/collections-python | /comprehensions_listas.py | 229 | 3.6875 | 4 | listas_simples_inteiro = [1, 2, 3, 4, 5, 14, 4, 5]
nova_lista = []
for i in listas_simples_inteiro:
nova_lista.append(i * i)
print(nova_lista)
nova_lista_elegante = [i * i for i in range(1, 10)]
print(nova_lista_elegante)
|
f01797cc57d89162b61b4b8faf39b6beee8d2ebf | HamadSMA/satr.codes-python-101-project | /telephone-directory/Phone-directory-optimized.py | 1,539 | 4.25 | 4 | directory = {
1111111111:"Amal",
2222222222:"Mohammed",
3333333333:"Khadijah",
4444444444:"Abdullah",
5555555555:"Rawan",
6666666666:"Faisal",
7777777777:"Layla"
}
def getkey(nm):
for key, value in directory.items():
if nm == value:
return key
end = False
while not end:
print("To search ... |
79ab447c31d2fca41482b0cd5bd07cb2eb11e8fb | loisbaker/100-days-of-code | /Day26/main.py | 358 | 4.3125 | 4 |
import pandas
df = pandas.read_csv('nato_phonetic_alphabet.csv')
nato_dict = {row.letter: row.code for (index, row) in df.iterrows()}
input_word = input('Enter a word: ').upper()
try:
code_list = [nato_dict[letter] for letter in input_word]
except KeyError:
raise KeyError("Sorry, only letters in the alphabe... |
1fdef693a5a7ab05f3e6e5122825d4a642b2b3c1 | wtjones/MathIsPy | /Quaternion.py | 2,727 | 3.625 | 4 | import copy
import math
from Vector import Vector
class Quaternion(object):
def __init__(self, *args):
if len(args) == 0:
self.scalar = 0.0
self.vector = Vector(0.0, 0.0, 0.0)
else:
self.scalar = args[0]
if args[1] is Vector:
... |
516c2f8d5dd24aa3fca7769bb3c628d3b63474ed | arkadiuszpasek/python-linears | /zad2.py | 1,091 | 3.671875 | 4 | # Placeholder for the assignment, refer to the example.py for tips
# How to use SAPORT?
# 1. Import the library
from saport.simplex.model import Model
# 2. Create a model
model = Model("2")
# 3. Add variables
x1 = model.create_variable("x1")
x2 = model.create_variable("x2")
x3 = model.create_variable("x3")
x4 = mo... |
6c19275a92131736ee784b58f315f9439e93b52e | j-lazo/population_models | /scripts/2species_CA.py | 10,417 | 3.828125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 7 11:25:05 2018
@author: jl
"""
#####--------------------SIMPLE AUTOMATA
import random
import numpy as np
import matplotlib.pyplot as plt
import copy
import os
import datetime
import timeit
start = timeit.default_timer()
datafile_path =os.getc... |
18d5ef54533a5ef001b992563b70e91b51f4441b | luizdefranca/Curso-Python-IgnoranciaZero | /Aulas Python/Exercícios Extras/Python Brasil/3 - Estrutura de Repetição/Ex 37.py | 1,584 | 4.3125 | 4 | """
37. Uma academia deseja fazer um senso entre seus clientes para descobrir
o mais alto, o mais baixo, a mais gordo e o mais magro, para isto você deve
fazer um programa que pergunte a cada um dos clientes da academia seu código,
sua altura e seu peso. O final da digitação de dados deve ser dada quando o
usuário digi... |
39f92eeccd9627ddbce0dd911425163375b4ddf6 | quangngoc/CodinGame | /Python/the-river-ii-.py | 286 | 3.5 | 4 | def meets_digital_river(r1, r2):
return r1 == r2 + sum(map(int, str(r2)))
def solution():
r1 = int(input())
for r2 in range(max(1, r1 - 50), r1):
if meets_digital_river(r1, r2):
print('YES')
break
else:
print('NO')
solution()
|
ceb114185bfadf22a9bc49bee64e7a0e9df94ab3 | ananthuk7/Luminar-Python | /data collections/list/list.py | 910 | 4.15625 | 4 | # list1 = [1, 2, 3, 4, 5,1]
# print(list1)
# print(type(list1))
#
# # <=== properties ===>
#
# # support duplicate data's
# # it keeps order
# # heterogeneous
# # nesting is possible
# # mutable
#
#
# # creating an empty list
# list2 = []
# print(type(list1))
# list2.append("hello")
# print(list2)
# list2.append(8)
# p... |
69d4033d0b28744543a2a08ba251ec1c98b15d53 | pallavibharadwaj/algoexpert | /dynamic_prog/min_coins_to_make_change.py | 858 | 3.609375 | 4 | # input: n=non-negative integer representing target amount
# denoms = array of distinct positive integers representing coin denominations
# output: minimum number of coins to make change for the target amount using given coin denominations (unlimited repetitions)
def minNumberOfCoinsForChange(n, denoms)... |
6852996f47fd52128753d3664380f92986dad9d5 | Jimut123/code-backup | /python/coursera_python/WESLEYAN/week3/COURSERA/week_3/copy_file_worked.py | 1,134 | 3.75 | 4 | # -copy_file.py *- coding: utf-8 -*-
"""
Exercise: Convert this function to a standalone program or script that
takes two file names from the command line and copies one to the other.
Steps:
1. Delete "Def" line. You don't need it.
2. Use Edit menu of Spyder to Unindent all the lines.
3. import the system library sys
... |
d79d9f2eaf74e505f993ca2818c85fe07ea0ec0b | Shubhankar-wdsn/Hackerrank-Python | /Diagonal Difference.py | 834 | 4.03125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
d1 = 0
d2 = 0
for... |
0731a906b2239a552d94f19f999258be8c3c25f7 | Xuanfang1121/bert_entity_extract | /bert_bilstm_crf_ner/test.py | 218 | 3.890625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/5/18 22:50
# @Author : zxf
arr = [1, 3, 2, 1, 5]
n = len(arr)
s = [0]
for val in arr:
print("s", s)
print(s[-1] ^ val)
s.append(s[-1] ^ val)
print("final s: ", s) |
c5f69e74846395eee6320da33b21194ae977a37d | NiceToMeeetU/ToGetReady | /Demo/DataStructre/binary_tree.py | 28,135 | 3.78125 | 4 | # coding : utf-8
# @Time : 21/03/03 9:27
# @Author : Wang Yu
# @Project : ToGetReady
# @File : binary_tree.py
# @Software: PyCharm
"""
二叉树的基本学习
- 树的遍历
- 递归解决问题
- 二叉搜索树相关
"""
import collections
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val... |
e885370daab81f312a1739472429784f0879f7c5 | sweetysweets/Algorithm-Python | /myclass/homework1/problem4.py | 7,589 | 3.65625 | 4 | """
汉诺塔
Description
汉诺塔问题中限制不能将一层塔直接从最左侧移动到最右侧,也不能直接从最右侧移动到最左侧,而是必须经过中间。求当有N层塔的时候移动步数。
Input
输入的第一行为N。
Output
移动步数。
Sample Input 1
2
Sample Output 1
8
"""
import sys
# ----------Stack_base_on_list-----------
class Stack(object):
def __init__(self):
self._stack = []
def push(self, data):
... |
59e78bf596e6e39dde5b058735eec6a073f7f7d9 | cychug/projekt3 | /010_Instrukcja _warunkowa_IF.py | 433 | 3.703125 | 4 | """
JESLI (PRAWDA)
TO...
JESLI COS INNEGO (PRAWDA)
TO...
A CAŁKOWICIE W INNYM WYPADKU
TO...
elif od ang else if
"""
a = int(input("Podaj liczbę a: "))
b = int(input("Podaj liczbę b: "))
print("a =", a, "b =", b)
if (a > b): # ważny jest dwukropek
print(a, "jest większe od",... |
d23f6a1e0e681fbdf5d8bb3fdde3e88985890835 | noemidmjn/COM404 | /1-basics/5-functions/6-enigma/bot.py | 389 | 4.21875 | 4 | print("Please enter a character to display...")
character = str(input())
print("Please enter total number of characters...")
total_n_of_characters = int(input())
print("Please enter a whole number...")
whole_number = int(input())
for count in range (1, total_n_of_characters + 1, 1):
if (count % whole_number == 0):
... |
d6e61c0bc24ec07bf7e7b926e7013194742d22bd | Vishavjeet6/python-programmes | /linkedlist.py | 812 | 4.125 | 4 | class Node:
def __init__(self,cargo=None,next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
def print_list(node):
while node is not None:
print(node,end=" ")
node = node.next
print()
def print_backward(list):
if list is N... |
f5d14bc523cb0ad5ea3fe16bd7e06afe6924aab2 | Rudy-Neyra/Rudy-Stuff | /curso/07clases_objetos/objetoDentroDeObjeto.py | 780 | 3.609375 | 4 | class Pelicula:
# Constructor de la clase
def __init__(self, titulo, duracion, lanzamiento):
self.titulo = titulo
self.duracion = duracion
self.lanzamiento = lanzamiento
print("Se creo la pelicula", self.titulo)
def __str__(self):
return "{} lanzado en {} con duraci... |
8dcff97665717bfd4281d3d7f43876f4bab673d5 | liuzhiqiang123/test | /one/abs.py | 268 | 4.0625 | 4 | # 1.循环输出列表中定义的数字绝对值
#tupleAbs = [12,0,-1]
#for num in tupleAbs:
# print(abs(num))
# 2.定义函数,用于输出两个数字相乘后的绝对值
def calcAbs(value1,value2):
return (abs(value1 * value2))
print(calcAbs(10,-10)) |
5663a19becf3e98f55dcb3de149f4093dd07e8c8 | Erick-ViBe/Cracking-the-Coding-Interview | /ArraysAndStrings/WordsRepetition.py | 654 | 3.8125 | 4 | import re
def CountRepetitionWords(x):
x = re.sub(r'[\,\.\!\¡\?\¿\-\:\;\(\)]', '', x)
SeparateWords = x.lower().split()
words = {}
for word in SeparateWords:
if word in words:
words[word] += 1
else:
words[word] = 1
print(words)
if __name__ == '__main__':... |
6266354dd8169b004d92b382339475b311900282 | nihathalici/Break-The-Ice-With-Python | /Python-Files/Day-5/Question-17-alternative-solution-1.py | 758 | 3.71875 | 4 | """
Question 17
Question:
Write a program that computes the net amount of a bank account based a transaction log
from console input. The transaction log format is shown as following:
D 100
W 200
D means deposit while W means withdrawal.
Suppose the following input is supplied to the program:
D 300
D 300
W 200
D 100... |
5707d7f67a36ecbc8ad0c8141fdab4bdbc7cac7f | soumyadc/myLearning | /python/statement/loop-iterator.py | 436 | 4.375 | 4 | #!/usr/bin/python
# iterator supports 2 methods: iter(var_list) and next(var_iter)
list = [1,2,3,4,5] # This defines the list
it = iter(list) # this builds an iterator object
#prints next available element in iterator. every time next() is called next value is fetched from iter operator
print(next(it))
print(next(i... |
98d2aaac3e9b04942fd8bfd83a17833222ee5667 | eronekogin/leetcode | /2019/subsets.py | 491 | 3.84375 | 4 | """
https://leetcode.com/problems/subsets/
"""
from typing import List
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
# Presumption: All numbers in nums are unique.
# So we could use dynamic programming, which
# dp[n] = dp[n - 1] + [item + [n] for item in dp[n - 1]... |
74266da65476c0877fd98f0af8bcf5defb1b876c | kanav-raina/black_hat_python | /stat.py | 1,083 | 3.75 | 4 | from math import sqrt
arr=list()
n=input("enter the number of elements")
print("enter the numbers")
#MEAN
for i in range(n):
arr.append(int(input()))
sum=0
for i in range(n):
sum=sum+arr[i]
mean=sum/(len(arr)*1.0)
print("MEAN :{0}".format(mean))
#MEDIAN
crr=arr
arr=sorted(arr)
if (len(arr)%2==0):
median... |
3a04d66524dee277b30d194c66f36c3ebe7dd467 | sdo91/programming_puzzles | /project_euler/solved/p050.py | 2,952 | 3.8125 | 4 | #!/usr/bin/env python
import time
import primefac
import math
import itertools
"""
Consecutive prime sum
Problem 50
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest su... |
422b1a4a0e525ce3147ad2ddf73d114236de91c5 | juannlenci/ejercicios_python | /Clase03/arboles.py | 6,016 | 3.640625 | 4 | #arboles.py
import csv
arboles =[]
especies =[]
ejemplares = {}
def leer_parque(nombre_archivo, parque):
'''
Se le pasa nombre de archivo y parque y
devuelve unas lista con los datos de cada
arbol del parque elegido
'''
arboles =[]
#El encoding="utf8" lo agrego para evitar "UnicodeDecodeE... |
e427f7f80840407b29779eda3b0dd8586e0e7c65 | LuisReyes98/python_bases_course | /poo/complejidad.py | 1,006 | 3.84375 | 4 | import math
< # -*- coding: utf-8 -*-
class Complejidad_algoritmica:
def __init__(self, n):
self.n = n
def constante(self):
return 1
def logaritmica(self):
return math.log10(self.n)
def lineal(self):
return self.n
def log_lineal(self):
return self.n * m... |
f189a8de9c30e767d3183df06215648d0f896bf6 | rlupton20/recur | /tests/test_recur.py | 1,287 | 3.734375 | 4 | from recur.recur import recur
from functools import reduce
def test_factorial():
def factorial(n):
"""Factorial of n."""
@recur
def f(recur, acc, n):
"""Tail recursive factorial function."""
if n == 0:
return acc
else:
re... |
aa9024bcb4625faf5aea0cffc4d48567630def4e | greatabel/puzzle_I_cracked | /3ProjectEuler/i153Gaussian_int.py | 2,892 | 3.671875 | 4 | '''
As we all know the equation x2=-1 has no solutions for real x.
If we however introduce the imaginary number i this equation has two solutions: x=i and x=-i.
If we go a step further the equation (x-3)2=-4 has two complex solutions: x=3+2i and x=3-2i.
x=3+2i and x=3-2i are called each others' complex conjugate.
... |
231581a0d55b46015b1d68d08c5b695396bce852 | cseharshit/Python_Practice_Beginner | /55.Selection_Sort.py | 297 | 3.59375 | 4 | from random import randint
x=int(input("Enter number of elements: "))
arr=[randint(1,100) for i in range(x)]
print(arr)
j=x-1
while j!=0:
k=0
for i in range(1,j+1):
if arr[i] > arr[k]:
k=i
# Swap the values
arr[k],arr[j]=arr[j],arr[k]
j-=1
print(arr) |
003e18553d638393da225caa8d3edf51e6171807 | briansu2004/MyLeet | /Python/Reverse Linked List/main.py | 2,524 | 4.15625 | 4 | """
https://leetcode.com/explore/learn/card/recursion-i/251/scenario-i-recurrence-relation/2378/
Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3... |
15316ca24c18327b61e69664bcfd2f4a9dcd0685 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/allergies/35817a216b994f26835749c13665efd1.py | 454 | 3.578125 | 4 | def allergyList(l):
n = l%256
aDict = {
1 : "eggs",
2 : "peanuts",
4 : "shellfish",
8 : "strawberries",
16: "tomatoes",
32: "chocolate",
64: "pollen",
128: "cats"
}
binNum ='0'*(8-len(bin(n)[2:]))+bin(n)[2:]
binNum = binNum[:8][::-1]
return [aDict[2**(i)] for i in range(8) if binNum[i] == '1']
class All... |
d9f6e19064e365e93ecfb7e1133fe23787ffcf8a | chenqumi/DataStruc_ZJU | /PTA/Python/ListLeaves.py | 247 | 3.75 | 4 | #chenqumi@20171224
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys,os,re
import Queue
arr = Queue.Queue()
#print(arr.items)
for i in range(10):
arr.addQ(i)
print(arr.items)
for i in range(10):
item = arr.deQ()
print(item) |
f873e0e503ea2bb5eaac86fe05677e2b105c06ea | MrHamdulay/csc3-capstone | /examples/data/Assignment_2/mphkga007/question2.py | 2,842 | 4.03125 | 4 | print('Welcome to the 30 Second Rule Expert')
print('------------------------------------')
print('Answer the following questions by selecting from among the options.')
did_anyone_see_you=input("Did anyone see you? (yes/no)\n")
if did_anyone_see_you=="yes":
who_was_it=input("Was it a boss/lover/parent? (yes/no... |
7d09f6304c4566e32905be914fe0e955e0436f6f | hgxur88/study | /python/14.구구단.py | 275 | 4 | 4 |
#while문을 사용해서 구구단 프로그램을 만들어 봅시다.
# 실행하면 아래와 같은 결과물이 출력되어야 합니다.
i = 1
while i <= 9:
j = 1
while j <= 9:
print("{} * {} = {}".format(i, j, j * i))
j += 1
i += 1
|
904220a1f8c1b4a4bb24b0a2d5b22c2a712a5384 | monetree/core-python | /py6/py5.py | 303 | 3.703125 | 4 | #waf that return results of add, sub,mul,div
def cal(a,b):
sum = a + b
sub = a - b
mul = a * b
div = a / b
return sum,sub,mul,div;
x,y= [float(i) for i in input("enter the number to calculate: ").split(",")]
sum,sub,mul,div=cal(x,y)
print(sum)
print(sub)
print(mul)
print('%.2f'%div) |
b6b0e1a64a2273f60db2b276afb3346e37afd73e | SirLeonardoFerreira/Atividades-ifpi | /Atividade 01 - semana 07/questão2_semana7_atividade01.py | 436 | 3.75 | 4 | def compra_avista(preco):
poupanca = 10000
mes = 0
while preco > poupanca:
poupanca *= (1 + (0.7 / 100))
preco *= (1 + (0.4 / 100))
mes += 1
return mes
def main():
preco_carro = float(input("Digite o preço que o carro custa hoje: "))
mes_total = compra_avista(preco_carro... |
8f22e417d0437653ece483604674409323d4d043 | thaus03/Exercicios-Python | /Aula14/Pratica.py | 487 | 3.765625 | 4 | '''for c in range(1, 10):
print(c)
print('FIM')
c = 1
while c < 10:
print(c)
c += 1
print('Fim')
for c in range(1, 5):
n = int(input('Digite um valor: '))
print('FIM')
'''
n =1
par = impar = 0
while n != 0:
n = int(input('Digite um valor: '))
if n != 0:
if n % 2 == 0:
par ... |
c0bbbee44c6314617813b6ccb1ad63f8a5fbbab6 | arossbrian/my_short_scripts | /summation.py | 165 | 3.984375 | 4 | # ask for two inputs
def sum():
num1 = int(input("num 1: "))
num2 = int(input("num2 : "))
addition = num1 + num2
return addition
print(sum())
|
69364978465689d056bf2597b23106945bb8bef8 | Yaphel/py_interview_code | /剑指OFFER/二叉搜索树转双向链表.py | 2,416 | 3.84375 | 4 | #要求是不占用额外空间
#可记录重复数字的二叉排序树
class Tnode(object):
def __init__(self,data):
self.data=data
self.count=1
self.lc=None
self.rc=None
self.next=None
self.prev=None
def constructor(arr):
arr_len=len(arr)
root=Tnode(arr[0])
for i in range(1,arr_len):
constructor_slave(arr[i],root)
return ... |
4eb474bbae4244f7f0bda6afd4397bdfbd1b43bc | green-fox-academy/hoanjinan | /week-01/day-2/exercises-w1d2/loops/optional/draw_square.py | 400 | 4.28125 | 4 | # Write a program that reads a number from the standard input, then draws a
# square like this:
#
#
# %%%%%%
# % %
# % %
# % %
# % %
# %%%%%%
#
# The square should have as many lines as the number was
num = int(input("Please input an integer number: "))
for i in range(1, num + 1):
if i == 1 or i == nu... |
e6ef38f1523629011822c1f9535dd60218fedb27 | Shandy100/BMS | /BMS_final.py | 8,111 | 3.875 | 4 | from tkinter import *
from tkinter.messagebox import *
import sqlite3
def login_user(username,password):
con=sqlite3.connect("createuser.db")
cur=con.cursor()
cur.execute("select * from user")
row=cur.fetchall()
for i in row:
if(i[0]==username and i[3]==password):
s... |
a4eefc32070b061d643d8108aecd4363aa66d27d | rmdimran/Mastering_Python | /ReturnStatement.py | 98 | 3.828125 | 4 |
def cube(num):
return num * num * num
print(cube(3))
"""
result = cube(3)
print(result)
""" |
a759fd7089244580412284c4372de30aaffaa6a0 | sooyoungkim/flipped-python-intro | /1_Hello_python.py | 119 | 3.625 | 4 | # atom 에서 파일 실행(Run) : command + i
print("Hello, Python")
a=5
b=3
print(a+b)
c="abck"
print(c.lower())
|
15b148f7b90c4ae624db17bbdd0ba8a920594d61 | Jachubogdziewicz/hyperskill | /banking.py | 5,226 | 3.71875 | 4 | import random
import sqlite3
random.seed()
conn = sqlite3.connect("card.s3db")
cur = conn.cursor()
conn.commit()
def generate_account_number():
global account_number, card_pin
bank_id = "400000"
account_id = str(random.randint(99999999, 1000000000))
calc_checksum = bank_id + account_id
calc_chec... |
22ed6dad5bbe0d3f1fadd9e0529cb27342182681 | BaldvinAri/Python_verkefni | /Vika 06/assignment9_3.py | 398 | 4.03125 | 4 | def divide_safe(num1_str, num2_str):
try:
num1_float = float(num1_str)
num2_float = float(num2_str)
return round( num1_float / num2_float , 5 )
except ValueError:
return
except ZeroDivisionError:
return
num1_str = input('Input first number: ')
num2_str = input('In... |
a11b7e9cc3fa6d7324fb8dcb76a4b7f00b0f3279 | LisaLaw/Python | /Friday_13th.py | 1,011 | 4.40625 | 4 | #Given the month and year as numbers, return whether that month contains a Friday 13th
import datetime #Python library to work with dates
#ask the user for a month and convert it to type int
user_month = input('Give me a month (from 1-12): ')
month = int(user_month)
#ask user for a year and convert it to type int
u... |
35705fe8df670568a899dda7fd312c234f41c6f0 | moreiraandre2/python | /ListasDicionario.py | 2,239 | 3.859375 | 4 | def addDados(nome,email,cpf):
dados = {'nome': nome,'email':email,'cpf':cpf}
return dados
def addCurso(cod,curso,hr):
dados = {'cod': cod,'curso':curso,'hr':hr}
return dados
def addCursoAluno(c,a):
dados = {'curso': c,'aluno':a}
return dados
if __name__ == '__main__':
op = "i"
... |
360af674ee24bb9614144ab9ebff523c6cc8c6b1 | griffinhiggins/100AlgorithmsChallenge | /ToDo/matrixElementsSum/matrixElementsSum.py | 396 | 3.671875 | 4 | def matrixElementsSum(arr):
sum = 0
length = len(arr) - 1
for i,x in enumerate(arr):
for j,y in enumerate(x):
if i < length:
if arr[i+1][j] == 0:
continue
sum += y
return sum
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
... |
7b6fba579ba88a1f5f1d100d541d4cb701124b5f | SeanNeilTalbot/The-Start-of-my-Python-Journey | /1.7.MathOperations.py | 1,875 | 4.1875 | 4 | #MathOperations.py
#Most common math operations in Python and the use of them. We also take a look at formatting
age = 47
decades = 4
addition = age + decades
subtraction = age - decades
multiplication = age * decades
division = age / decades
exponent = age ** decades
modulo = age % decades
print(addi... |
ba01553db0acaac5b004c04a509abdba009fe4a4 | SeohuiPark/DatastructureAlgorithm | /greedy/hackrank/gridchallenge_0708_Ver2.py | 1,417 | 3.671875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
import string
import time
start = time.time()
### 내가 푼거지만 공간복잡도 측면에서 별루인듯.
# Complete the gridChallenge function below.
def gridChallenge(grid):
# 1. define map fuction
def map(f, it):
result = []
for x in it:
... |
620c4cfde531ef995541f9b758975d5f98acb741 | pabhd3/Coding-Challenges | /adventofcode/2019/03 - Crossed Wires/wires.py | 1,806 | 4.21875 | 4 | def findPath(directions, intersections=None):
if(intersections is not None):
# Relation of known intersections to step count
path = {i: 0 for i in intersections}
else:
# Set of coordinates visited
path = set()
x, y, steps = 0, 0, 0
for d in directions:
# Pull dire... |
6f2b554ec2951d7b8199a00dcb7e34e7dedda466 | oliverwreath/DataScience | /Set5/ridership_by_weather_reducer.py | 1,574 | 3.796875 | 4 | import sys
import logging
from util import reducer_logfile
logging.basicConfig(filename=reducer_logfile, format='%(message)s',
level=logging.INFO, filemode='w')
def reducer():
'''
weather type -> average value of ENTRIESn_hourly
that the input to the reducer will be sorted by weather type, such that all
ent... |
88a5df8a04c7ed79edef955995b95ede6c43907f | sybrandb/glz_new | /feestdag.py | 1,151 | 3.546875 | 4 | from datetime import datetime
class FeestDag(object):
"""" for every festival specifies three attributes: the day, it's name, and it's color """
l_fieldnames = ['dag','benaming','kleur']
def __init__(self, datum, benaming, kleur='groen'):
"""
:type self: object
"""
self.... |
9e241c4fd0ee919e1765074f0e9818e7332745e3 | gabrielbf/python-study | /Python for Data Structures, Algorithms, and Interviews/Solutions/Section 15 - Recursion/lecture103_rec_coin.py | 1,678 | 4.03125 | 4 | '''
Section 15 - Lecture 103 - Coin Change Interview Problem
rec_coin_meu Minha solução para o problema usando recursão
rec_coin Solução do curso sem memoização
rec_coin_dynam Solução do curso com memoização
'''
def rec_coin_meu(target, coins):
# Base case
if (target == 0) or (not coins):
... |
39aa629692a149261fd805b6da2dbed3ba83d8bb | jamesthesnake/CS347-Rush-Hour-Project | /BreadthFirstGraphSearch/Python/puzzleproject2.py | 1,766 | 3.59375 | 4 | # File: puzzleproject2.py
# Author: Addie Martin
import random
import sys
import time
from collections import deque
from board import Board
from node import Node
moves = 0
boardname = ""
current = Board()
#Loading in the board
if len(sys.argv) <= 1:
boardname = raw_input("What board would you like to load?\t")
else:
... |
085e63fabb92b254f721ecc1488fa30f88d08f7c | RegCookies/Offer-Sward | /Number/is_power_2.py | 136 | 3.71875 | 4 | def isPower(n):
return n&(n-1) == 0
if __name__ == "__main__":
n1 =3
n2 =4
print(isPower(n1))
print(isPower(n2)) |
d0dd7a5a7ddb8022970f006cbcb0b28b5aa38b91 | kmoy1/CheapestNetwork | /SimulatedAnnealing.py | 1,181 | 3.59375 | 4 | from __future__ import print_function
import math
import random
from simanneal import Annealer
from utils import average_pairwise_distance
import networkx as nx
class SimulatedAnnealing(Annealer):
# Test annealer with a travelling salesman problem.
# pass extra data (the distance matrix) into the constructor
de... |
413f0339ec6deed6926944336e42e794c88368d4 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/leetcode/LeetCode/924 Minimize Malware Spread.py | 3,068 | 3.921875 | 4 | #!/usr/bin/python3
"""
In a network of nodes, each node i is directly connected to another node j if
and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware. Whenever two nodes are
directly connected and at least one of those two nodes is infected by malware,
both nodes will be infected by m... |
864039ad5912c6e607288846465128da484b6959 | nicolesay/Expense-O-Tron-9000 | /IsNumber.py | 255 | 3.90625 | 4 | def IsNumber():
i_amount = 0
while True:
try:
i_amount += float(input('Enter Amount of Transaction > '))
return i_amount
except ValueError:
print('Must be a Number!')
continue |
8717b667ca656fdbaf90eb98b9a5fc809a7f6c31 | IkeyBenz/ColorChecklist | /checklist.py | 943 | 3.96875 | 4 | checklist = []
def create(item):
checklist.append(item)
def read(index):
return checklist[index]
def update(index, item):
checklist[index] = item
def destroy(index):
checklist.pop(index)
def listAllItems():
index = 0
for item in checklist:
print('Index:', index, 'Item:', item)
... |
a08bd8bb9b056e71ad0f9b81cdd9c7eedd7221df | manish33scss/practice_randomstuff | /simple_calc_tkinter.py | 2,644 | 3.75 | 4 | """
Created on Sat Jul 25 04:33:02 2020
@author: manish kumar
"""
from tkinter import *
root = Tk()
root.title(" Calcula-THOR")
enter = Entry(root,width = 15,borderwidth = 3, bg= "white", fg= "cyan" )
enter.grid(row = 0 , column = 0 )
def button_click(number):
#enter.delete(0,END)
curr = enter.get()
en... |
c302b8fa905cbbfac6b6feb3207df2e0fb8940dd | rayray2002/TPE-2014 | /python/urllinks.py | 464 | 3.5625 | 4 | # Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program
import urllib
from BeautifulSoup import *
url = "http://python-data.dr-chuck.net/known_by_Greg.html"
for i in range(7):
#global url
html = urllib.urlopen(url).rea... |
2f78919c7c166ae165af1bec6e2fa9173abf8503 | Nushrat-Jahan/Python-codes | /Bubble sort visualizer/bubble_sort.py | 438 | 4.0625 | 4 | import time
def bubble_sort(arr, displayBar, animSpeed):
for _ in range(len(arr)-1):
for j in range(len(arr)-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
displayBar(arr, ['blue' if a == j or a ==j+1 else 'red' for a in range(len(arr))])
... |
bc1aea20523d38e0945a5d876eecbb01acae2de1 | Tbeck202/PythonCourse | /BuiltInFunctions/reversed.py | 201 | 3.984375 | 4 | nums = [1, 2, 3, 4]
print(reversed(nums))
for char in reversed("Go Jazz"):
print(char)
# for x in reversed(range(0, 10)):
# print(x)
nums2 = reversed(nums)
for num in nums2:
print(num)
|
e096d678c3d64fe866300407e6cc7a9a0f95a974 | serjnobelev/python_start | /oop_super.py | 775 | 3.8125 | 4 | # super() – обращение к родителю
class Calc(object):
def __init__(self, value):
self.value = value
def count(self):
return self.value * 10
class ExtCalc(Calc):
def __init__(self, value, k):
super().__init__(value)
self.k = k
def count(self):
prev = super().... |
07eba77d64e63c47c2d80824f24ae2969209743d | Imaginerum/training-python | /0050_class_rocket_example.py | 1,156 | 3.9375 | 4 | from random import randint
from math import sqrt
class Rocket:
def __init__(self, speed=1, altitude=0, x=0):
self.altitude = altitude
self.speed = speed
self.x = x
def move_up(self):
self.altitude += self.speed
def __str__(self):
return "Rakieta jest aktualnie na ... |
7f33f88849c7c02cdd2a7b967fd345e12ac34d85 | shashankp/cv-eg | /game/misc/pygame-test.py | 2,027 | 3.890625 | 4 | import pygame
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
blue = ( 50, 50, 255)
green = ( 0, 255, 0)
dkgreen = ( 0, 100, 0)
red = ( 255, 0, 0)
purple = (0xBF,0x0F,0xB5)
brown = (0x55,0x33,0x00)
# Function to draw the background
def draw_background(scr... |
d58923cc63cc5c4f3aa4f66d4335c0021f1f3236 | cyr1k/gb-homework | /permutations.py | 3,089 | 4.25 | 4 | import sys # To use sys.argv to read command line arguments
permutations = [] # Initialize list of permutations
"""Loads file from command line argument. Prints error and exits if file not found. Otherwise,
reads file line by line and returns list of strings to be to be permuted."""
def loadFile(file):
try:
... |
0c1ec69b003ded4abc88804a39925e37b330e499 | FalgunMakadia/analyze-re | /projectfolder/compute.py | 1,035 | 3.71875 | 4 | import sys
threshold = float(sys.argv[1])
limit = float(sys.argv[2])
if not 0.0 <= threshold <= 1_000_000_000.0 or not 0.0 <= limit <= 1_000_000_000.0:
print("--- Threshold and Limit value must be between 0.0 and 1,000,000,000.0 ---")
exit()
output = []
sum = 0.0
input_count = int(input("Enter number of inputs (m... |
dac7136cdfa026b9cd1500f4f0078d31cb12c6d1 | timetobye/BOJ_Solution | /problem_solve_result/2804.py | 427 | 3.53125 | 4 | row, column = input().split()
row_lst = list(row)
column_lst = list(column)
cnt = 0
for word in row_lst:
try:
idx = column_lst.index(word)
break
except:
cnt +=1
for x in range(len(column_lst)):
if x == idx:
print(row)
continue
for y in range(len(row_lst)):
... |
312dd3dd41ecd5cb8703f55332af10e6f552024b | luozhiping/leetcode | /middle/single_number_iii.py | 620 | 3.671875 | 4 | # 260. 只出现一次的数字 III
# https://leetcode-cn.com/problems/single-number-iii/
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums or len(nums) < 2:
return []
xor = 0
for n in nums:
... |
397fc4b3c351c562efc67c7ddb37b63ed7afed9f | ATLS1300/PC06-Funcy-Animation | /wrapAroundBoundary.py | 1,794 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 4 21:20:00 2021
@author: sazamore
A wraparound boundary, demonstrated with a ghost moving left
to right against a black background. Ghost crosses a boundary
10 times before stopping.
"""
import turtle
# ================ LIBRARY SETTINGS SETUP ==... |
b4844373f2b42312407893fdbe165e5f101beb05 | yti21/Python-General_Programming | /080719PA.py | 2,658 | 3.96875 | 4 | def nth_element(data, n):
''' Return the nth element of the list '''
element = data.pop(n)
return element
def num_words(string):
''' Return the word count '''
string = string.split()
length = len(string)
return length
def repeat_last(data):
''' returns a new list with the l... |
eb186a081c474fab1b49883bc974a33910047e9f | ncrubin/ManifoldLearning-spectral | /KNN.py | 1,135 | 3.71875 | 4 | def KNN_NCR(X, k):
"""
Brute force algorithm for finding k-nearest-neighbors given a data set.
input 1) X matrix where rows are data-points
input 2) k integer. number of nearest-neighbors.
return 1) indices of k-nearest-neighbors for each row of X
return 2) distances of k-nearest-neighbors fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.