blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9f74204ff613abb637d94b88a063e22b8d2c159e | KunanonP/freeTimeProject | /fengShuiCompassConverter.py | 7,542 | 3.75 | 4 | import datetime
from datetime import date
from datetime import timedelta
class compassConverter:
def __init__(self, direction):
self.direction = direction
self.result = 0
self.compassDirection = ""
self.zodiac = ""
def degree(self):
degree = self.direction
resu... |
c1b8be093e13dbd83b6ab230cf015fcde2d123d6 | alicesilva/P1-Python-Problemas | /repeticao17.py | 123 | 3.65625 | 4 | #coding: utf-8
n = int(raw_input())
multiplicacao = 1
for i in range(n,0,-1):
multiplicacao *= i
print multiplicacao
|
47eb2155722f0aaa2515f0584eaa8be1f34425d1 | Saeed-Emad/xdata-feat | /feat/xapp/data/securities/metrics.py | 2,430 | 3.78125 | 4 | import pandas as pd
def compute_quotient_metrics(filename,
index_col=0,
resample_period='1M',
shift=0,
quotient_metrics=[('Volume', 'max', 'median'),
('Clos... |
03ddf8ad4abb1621956ea0c0cb9e72d6ac540872 | yutveg/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,574 | 3.96875 | 4 | # TO-DO: complete the helper function below to merge 2 sorted arrays
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
master = [None] * elements
# TO-DO
a_index = 0
b_index = 0
master_index = 0
while(a_index < len(arrA) and b_index < len(arrB)):
if(arrA[a_index] < arrB[b_index... |
9bcf1c58971006eeab15c1465c4bde0f3224dd03 | CauePinheiro-2001/PythonComputacao1 | /exercicios_semana2/2.py | 153 | 3.921875 | 4 | '''2.Escreva um programa que receba um número inteiro digitado pelo usuário e o imprima.'''
print('Programa 2')
x = int(input('Valor:'))
print(x) |
a2b82fe0ac1093e3fa1f0e755ced3f3e09c6165f | himu999/problem_solving | /L#2/problem_26.py | 185 | 3.71875 | 4 | t = int(input())
i = 1
while i <= t:
cont = 0
num = float(input())
while num > 1:
num = num / 2
cont = cont + 1
print(cont, "days")
i = i + 1
|
cf1b55e875374ee6225883d614ceb2ca48f5f14c | nickvnoort/share | /Les 04/Oefening4_3.py | 153 | 3.546875 | 4 | lijst = [4, 0, 1, -2]
def swap (list):
if len(list)>1:
list[0], list[1] = list[1], list[0]
return(list)
print(lijst)
print(swap(lijst)) |
f5fc965ef560894f55c147edc6713137dca54066 | contractorr/personal-website-whole | /portfolio/portfolio_projection.py | 12,402 | 3.765625 | 4 | def invest(starting_amount, cagr, num_years, beginning_year=0, annual_topup=0, topup_years=0):
"""Calculate and plot the value of an investment portfolio over time
Args:
starting_amount(float): the initial amount to be invested
cagr(float): the Compound Annual Growth Rate (CAGR). This i... |
7ba61f4756eff7e8a0f0e47b298d49187f88c647 | sam1208318697/Leetcode | /Leetcode_env/2020_02_22/Minimum Time Visiting All Points.py | 1,188 | 3.65625 | 4 | # 1266.访问所有点的最小时间
#
# 平面上有n个点,点的位置用整数坐标表示points[i] = [xi, yi]。请你计算访问所有这些点需要的最小时间(以秒为单位)。
# 你可以按照下面的规则在平面上移动:
# 每一秒沿水平或者竖直方向移动一个单位长度,或者跨过对角线(可以看作在一秒内向水平和竖直方向各移动一个单位长度)。
# 必须按照数组中出现的顺序来访问这些点。
#
# 示例1:
# 输入:points = [[1, 1], [3, 4], [-1, 0]]
# 输出:7
# 解释:一条最佳的访问路径是: [1, 1] -> [2, 2] -> [3, 3] -> [3, 4] -> [2, 3] -> [1, 2] ... |
34774db9bbbb3fef7f8b50aeb88aa47990afd74d | Azzurra06/Exercices_Python | /Formes/Escalier.py | 586 | 3.578125 | 4 | from turtle import *
hauteur = window_height()
largeur = window_width()
a = int(input("Combien de marches voulez vous ? "))
b = int(input("Quelle est la hauteur des marches ? "))
z = int(input("Quelle est la longueur des marches ? "))
up()
goto((-largeur/2)+20,(hauteur/2)-20)
down()
write("Départ")
i=0
t=0
while i<... |
e3ccfc6e01826dd6525beb651ef80300694e18be | christiaanrr/python-journey | /problems/Practice Problems/tuple.py | 648 | 4.25 | 4 | # Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output,
# where every other element of the input tuple is copied, starting with the first one.
# So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on
# this input would return the tuple ('I'... |
3a073c6aa42cd201e95edf7ff8d07446a8aec1cf | datastax-demos/Connected-Office | /triangulate/triangulation.py | 4,230 | 3.59375 | 4 | import math
import random
import pylab
from sympy import symbols, Eq, solve
random.seed(1337)
MAX_RANGE = 1000
COLORS = 'b,g,r,c,m,y,k'.split(',')
STYLE = '-,--,-.,:,.,o,v,^,<,>,1,2,3,4,s,p,*,h,H,+,x,D,d,|,_'.split(',')
class Generator:
def generate_random_points(self, width):
"""
Generate rand... |
ef49e2adcfa5582fba17a4629e7088a90012e770 | twizztednight/sandbox | /CW solver.py | 2,656 | 3.921875 | 4 | #Brett Zimmermann
#06/06/2012
#global
import codecs
import re
data = { }
#main
def main():
wordlist = codecs.open("words.txt", "r", "utf-8")
sanitize(wordlist)
menu()
wordlist.close()
#basic sanitization
def sanitize(wordlist):
for word in sorted(wordlist):
data.setdefault(word,[])... |
6aa19eb225001ddf4b89db1166d67525a5ffa0c2 | josephgallagher/homework | /exercises/exercise4/exercise_4.py | 672 | 4.0625 | 4 | option = 0
while option != '3':
option = raw_input(\
"\
******************************\n\
EXCERCISE 4 - MENU\n\
******************************\n\
1. Write input to file\n\
2. Write input to screen\n\
3. Quit\n\
******************************\n\
Enter your choice [1-3]: "
)
if option == '1':
wri... |
1fe4d8fc7829991602d27c9c0cd502a2005998ba | MayBaMay/PB_P5 | /models/print.py | 7,665 | 3.703125 | 4 | #! /usr/bin/env python3
# coding: utf-8
"""This module groups main functions of input and display"""
from models.config import NB_CATEGORIES
class Print:
"""All functions grouped in a Print class"""
@staticmethod
def welcome():
"""Display a welcome message and mention OFF as source od datas"""
... |
a3ab2d315158fafb9895f0c4b51e5d0da7274e49 | bianan/a_bite_on_tf | /control-depend/control.py | 688 | 3.5 | 4 | import tensorflow as tf
# We define our Variables and placeholders
x = tf.placeholder(tf.int32, shape=[], name='x')
y = tf.Variable(2, dtype=tf.int32)
# We set our assign op
assign_op = tf.assign(y, y + 1)
mul = tf.assign(y, 2*y )
# We build our multiplication, but this time, inside a control depedency scheme!
with... |
1185eeaf6275b50ea33cff1433ebc59f4174a883 | PrimeNumber012357/Fun-with-games-and-shapes | /fibonacci_noInput.py | 404 | 4.3125 | 4 | def fibonacci(n):
if n == 1:
return 0
if n == 2:
return 1
else:
n_2, n_1 = 0, 1
#Calculate Fibonacci iteratively starting at the 3rd value up n (n+1 is used because ranges exclude the last value)
for num in range(3, n+1):
fib_term = n_2 + n_1
n... |
603ee9bb15cf4d032aa9c0bb240be0116ff44c72 | zhanglae/pycookbook | /ch1/cookbook1_6.py | 902 | 4.125 | 4 | '1.6 Mapping Keys to Multiple Values in a Dictionary'
'''
Problem
You want to make a dictionary that maps keys to more than one value (a so-called "multidict").
'''
d = {'a' : [1,2,3],
'b':[4,5]}
print(d)
#>> {'a': [1, 2, 3], 'b': [4, 5]}
from collections import defaultdict
d = defaultdict(list)
... |
fb47cdbbbbd64e9b1f7fc10ceabd0755b68224d7 | jovany-wang/ray | /python/ray/air/_internal/tensorflow_utils.py | 5,080 | 3.5 | 4 | from typing import Optional, Union, Dict
import numpy as np
import pandas as pd
import tensorflow as tf
from pandas.api.types import is_object_dtype
from ray.air.util.data_batch_conversion import _unwrap_ndarray_object_type_if_needed
def convert_pandas_to_tf_tensor(
df: pd.DataFrame, dtype: Optional[tf.dtypes.D... |
3b9aafc63800127ffdda232f47abd88f59d9092e | Aashutosh180/python-code | /day6assgn1,2.py | 1,148 | 3.9375 | 4 | #Ass1 Day6
class Bank_Account:
def __init__(self):
self.balance=0
print("Hello!!! Welcome to the Deposit & Withdrawal Machine")
def deposit(self):
amount=float(input("Enter amount to be Deposited: "))
self.balance += amount
print("\n Amount Deposited:",a... |
7beb5baa7b8f810e782879d17e9e0c5b8c918d07 | CoderZhangfujiang/Introduction-to-Algorithms | /Algorithm_Basis/insert_sort.py | 480 | 3.78125 | 4 | # _*_ coding:utf-8 _*_
"""
输入:n个数的一个序列
输出:序列的一个排序
"""
def insert_sort(a):
for i in range(1, len(a)):
key = a[i]
# insert a[i] into the sorted sequence a[1...i-1]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j+1] = key
return a... |
cf1917648cb2a8a434482fc7e705f170916bdada | raghavgr/Data-Structures-Algo-Goodrich | /chapter4/factorial.py | 215 | 4.09375 | 4 | """ Computes factorial of given number recursively """
def factorial(num):
"""
Factorial of num. O(N) running time
"""
if num == 0:
return 1
else:
return num * factorial(num - 1)
|
f2b8772107a210f6830a0266f1a0d93bfa97c2cc | klmsathish/DataStructures | /QueueUsingLinkedList.py | 996 | 4.09375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def Enqueue(self,data):
newnode = Node(data)
if self.last_node == None:
self.head = ne... |
70cdcbbfb951f60fe0a9b8c85971c28550ac9871 | pubggamerzytm/TelegramCalculatorBot | /calc_classes.py | 13,087 | 3.78125 | 4 | # модуль с классами калькулятора
from tkinter import*
from tkinter import ttk
import math,sys,re
class Calculator:
"""методы калькулятора"""
def __init__(self, exc):
self.exc = exc
self.signs = "^/*%-+"
self.struck = ['sin', 'cos', 'atg', 'tg', 'sqrt', 'lg', 'log']
self.do = True... |
cd1be03e64205232e1a58f073992c538c3cfef17 | Kabmichal/UI-3 | /ui.py | 13,242 | 3.53125 | 4 | import random
import numpy as np
import matplotlib.pyplot as plt
def number_of_population():
"""
:return: pocet populacie, ktora sa vygeneruje
"""
return 100
def gems():
"""
:return: pozicie v jednorozmenom poli, kde su ukyte poklady
"""
return [11, 16, 27, 29, 39]
def load_map():
... |
d3690066cc4d43826afae8a3596eec9bf1f0f2e3 | arturbs/Programacao_1 | /uni3/uhir/class_corredor.py | 450 | 3.546875 | 4 | # coding: utf-8
# aluno: Artur Brito Souza
# matricula: 118210056
# UFCG - Programação 1 2018.2
# Programa : Classifica Corredor
kilometros = float(raw_input())
hora = float(raw_input())
velocidade = kilometros / hora
if velocidade < 10:
print "Velocidade: %.1fkm/h. Corredor amador." %velocidade
elif velocidade <= ... |
ec5c4e6bd519b37774488ca2816c1341fdf7bcfb | SalmanMapkar/Snake-Game-in-Python | /snake.py | 2,384 | 3.609375 | 4 | import curses
from curses import textpad
import random
def create_food(snake,box):
food=None
while food is None:
food = [random.randint(box[0][0]+1,box[1][0]-1),
random.randint(box[0][1]+1,box[1][1]-1)]
if food in snake:
food = None
return food
def print_score(stdscr,... |
75ecbc9cafb8cacd5a799678531eecba724eb9c8 | Roman111975/Algoritm_Python | /Lesson_7/task_01.py | 979 | 4.34375 | 4 | """
1. Отсортировать по убыванию методом «пузырька» одномерный целочисленный массив, заданный случайными числами на
промежутке [-100; 100). Вывести на экран исходный и отсортированный массивы.
"""
import random
import time
random.seed(time.time())
m = int(input("Введите длину массива m = "))
array = [random.randint(-... |
b6cddf2094e5ca10dee28fc49efceff3802ab324 | ArunPrasad017/python-play | /coding-exercise/Day19-RansomNote.py | 1,520 | 3.984375 | 4 | """
Given an arbitrary ransom note string and another string containing letters from all the magazines,
write a function that will return true if the ransom note can be constructed
from the magazines ; otherwise, it will return false.
Input: ransomNote = "a", magazine = "b"
Output: false
Input: ransomNote = "aa", m... |
b481344e3c9d5e7cdee915c89824b6fa7523e01c | saranyapalani/python | /div.py | 85 | 3.796875 | 4 | print("enter two numbers")
x=input()
y=input()
s=x%y
print("the division is :",s) |
415373221e4e009554bab26d09c2163cafd79a6e | gitshangxy/tutorial | /L7本地文件读写/5 with语句.py | 1,083 | 3.8125 | 4 | # with
# 传统写法
# file = open('english_ascii.txt', 'r')
# content = file.read()
# print(content)
# file.close()
# 传统写法的缺点 每一次要记得打开关闭文件,跟try except连用时结构不太清晰。
# with 读文本文件
with open('chinese_utf8.txt', 'r', encoding='utf-8') as f:
# f.__enter__() # 文件打开的预处理
content = f.read()
print(content)
# f.__exit... |
b62899bab5bb99f74e9847152addd00e0aabd57f | tywins/TC1014 | /fibonacci.py | 310 | 4.125 | 4 | def fib(x):
n = x
m = y
if (n == 0 or n == 1):
return n
if (n > 1):
f = fib(m - 2) + fib(n - 1)
return f
x = int(input("Insert lower bound: "))
y = int(input("Insert upper bound: "))
fc = fib(x)
print ("The fibonacci sequence of ", x, " to ", y, " is: ", fc)
|
61450c76ce09b49278266441253e2255aca0e731 | nkennek/AIL_team24 | /nakahara/cyclegan/write_image.py | 433 | 3.78125 | 4 | """write_image function."""
from PIL import Image
import numpy as np
def write_image(image, path):
"""Save an image to a file.
Args:
image (~numpy.ndarray): An image to be saved.
path (str): The path of an image file.
"""
if image.shape[0] == 1:
image = image[0]
else:
... |
a564175584e9e26ead1f13e23e799924c14a133e | themayurkumbhar/wemake-python-styleguide | /wemake_python_styleguide/logic/tokens.py | 1,380 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import tokenize
from typing import Container, Iterable, Tuple
def split_prefixes(token: tokenize.TokenInfo) -> Tuple[str, str]:
"""
Splits string token by prefixes and the quoted content.
Returns the tuple of modifiers and untouched string contents.
>>> import tokenize
>... |
ed5168cc564ea03370ec8eb4b9bacca0cd1866a9 | jersson/mit-intro-cs-python | /week-02/04-functions/ex-06-power-iter/iterPower.py | 265 | 4.09375 | 4 | def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
result = 1
counter = 0
while counter < exp:
result *= base
counter += 1
return result
print(iterPower(5, 3))
|
84ca0cb861916363400ca7836a55170421f7072f | gistable/gistable | /dockerized-gists/5a653317688b14fd0fc67214c1352831/snippet.py | 2,891 | 4.3125 | 4 | """
Shows how to do a cross join (i.e. cartesian product) between two pandas DataFrames using an example on
calculating the distances between origin and destination cities.
Tested with pandas 0.17.1 and 0.18 on Python 3.4 and Python 3.5
Best run this with Spyder (see https://github.com/spyder-ide/spyder)
Author: Mark... |
9d3b0c4bdbe2fd1917e9acacaffde2254784c51f | amruthapp/pythonprograms | /co1/program07.py | 625 | 4 | 4 | list1 = [1, 2, 3, 4, 5]
list2 = [2, 4, 6, 8]
print("element in list one is", list1)
print("element in list two is", list2)
s1 = 0
s2 = 0
if (len(list1) == len(list2)):
print("lists have same length")
else:
print("lists have different length")
for i in range(len(list1)):
s1 = s1 + list1[i]
print("the sum of ... |
f872b562fd3ebf1db88f5bf3730b7fea8190702c | henriquekirchheck/Curso-em-Video-Python | /desafio/desafio005.py | 251 | 4.03125 | 4 |
# Faça um programa que leia um numero inteiro e mostra ne tella o seu sucessor e seu antecessor
n = int(input('Numero: '))
ns = n + 1
na = n - 1
print('------------------------------------\nO sucessor é {} e o antecessor é {}!' .format(ns, na))
|
f26ff58038745b15f0c1c601b5e717ca90c8c410 | ATV-byte/se-python-homework | /session2/ex15.py | 331 | 3.65625 | 4 | """
Veti primi un string de la tastatura.
Va trebui sa spuneti cate vocale are acest string.
exemplu:
Veti primi: 'cmi'
Veti printa: 1
"""
x = input()
x = x.lower()
vocals = 0
for el in x:
if el == 'a' or el == 'e' or el == 'i' or el == 'o' or el == 'u':
vocals = vocals + 1
pr... |
82b6256a4a0d9ee42a5428b9f30955799bb328f9 | ucsb-cs8-f18/cs8-f18-lecture-code | /lec09/accumulator.py | 2,439 | 4.25 | 4 | # accumulator.py :
# Solving problems that involve collections (strings, lists, tuples, namedtuples)
# Patterns of programming using loops, nested loops
# Nov 1, 2018
def countElements(lst):
'''returns the number of elements in lst'''
count = 0
for item in lst:
count = count+1
return count
def countOddN... |
18cbb597f93a1bf9e7dbab5ddd02411a2e7fe55a | lastmayday/Euler | /12.py | 515 | 3.671875 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import time
def devide(x):
for i in xrange(1, int(x**0.5)):
if x/i*i == x:
yield i
yield x/i
def triangle():
n = 1
while n:
x = sum(i for i in xrange(n))
num = len(list(devide(x)))
if num > 500:
... |
7ad9742f17ca2ba0e83c84789cb57dd8e337b4cc | Quantium/gettingInShape | /excercises/longestPalindrome.py | 2,260 | 4.15625 | 4 | """
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
A palindrome is a string which reads the same in both directions
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
class Solution:
... |
851d60b143cb7c5f6a587de7a872786c68035fe4 | Artemis21/game-jam-2020 | /artemis/engine.py | 5,891 | 3.859375 | 4 | """Module for the physics engine."""
import arcade
import game
import player
from sound import play_sound_effect
def check_for_collision(sprite1: arcade.Sprite,
sprite2: arcade.Sprite) -> bool:
"""Check for collision between two sprites.
Used instead of Arcade's default implementatio... |
63cb9b664f856f53e55e996e1af9811e83d7c39e | 9eor9e/pythonStudy | /0049_while_list_dictionary_practice.py | 411 | 4 | 4 | # 7-8 - 练习1
sandwich_orders = ['sw1','sw2','sw3']
finished_sandwiches = []
while sandwich_orders:
finished_sandwich = sandwich_orders.pop()
print('I made your tuna sandwich ' + finished_sandwich.title() + ' .')
finished_sandwiches.append(finished_sandwich)
print('\n--All finished sandwiches--')
for finished... |
934f46ecbe8ba61f49af7b74b1a96452d5c80eac | qudcks0703/python | /python0303/while01.py | 1,624 | 4.25 | 4 | '''
반복문 : while, for
*** while ***
구조
#1. 반복횟수를 알 때 지정
while 조건식:
실행문...
증감식
#2. 무한반복
while True:
실행문...
// 종료시점
if 조건문:
break
'''
# 10회 반복하기
'''
i = 0
while i <10:
print("hello")
i+=1
'''
# 문제1. 0 ~ 3까지 출력
'''
i = 0
while i < 4:
print(... |
171cfb922bd4d861a333aead7231bd311e73919c | lucaspereirag/pythonProject | /ex091.py | 1,073 | 4 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogador = {'jogador 1': randint(1, 6),
'jogador 2': randint(1, 6),
'jogador 3': randint(1, 6),
'jogador 4': randint(1, 6)
}
#dicionário ranking para criar ordem em jogadores:
ranking = {} #pode... |
05813cfe1a34b542c0407f33383720f725f70a48 | lg-x-vCedeb/Pythonsophy | /Ch6.List.py | 492 | 4.03125 | 4 | num_list = [-1,2,-4]
def absList(num_list):
for i in len(num_list):
if i >= 0:
i = i
else:
i = 0 - i
#i = (i > 0) and i or -i
#i = [-i,i](i>=0)
#num_list(i) = (num_list(i) >= 0)and num_list(i) or -num_list(i)
# YOUR CODE HERE
absList(num_list)
print(nu... |
a2fd8bd239209180ab1d0f33c069925c98742bf1 | nickfang/classes | /projectEuler/webScraping/problemTemplates/214.py | 676 | 3.65625 | 4 | # Totient Chains
#
#Let φ be Euler's totient function, i.e. for a natural number n,
#φ(n) is the number of k, 1 ≤ k ≤ n, for which gcd(k,n) = 1.
#By iterating φ, each positive integer generates a decreasing chain of numbers ending in 1.
#E.g. if we start with 5 the sequence 5,4,2,1 is generated.
#Here is a listing of ... |
39a01049bc2e9f9711eaad84073b45f44523ca48 | Rav2326/python_bootcamp | /Dom cz. 2/Zadanie_3.py | 291 | 3.65625 | 4 | liczby = [1, -1, 2, -2, 3, -3 ]
liczby_dodatnie = 0
liczby_ujemne = 0
for liczby_dodatnie in liczby:
if liczby_dodatnie > 0:
print(liczby_dodatnie)
print()
print()
for liczby_ujemne in liczby:
if liczby_ujemne < 0:
print(liczby_ujemne)
|
2ba97b8aa2e1d5b36ceceb077b1be7fce6588bed | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/1ee300a5b3ec430eb39f1a13c3e320ea.py | 607 | 3.625 | 4 | import datetime
import calendar
from datetime import date, timedelta
from calendar import monthrange, day_name
weekday_translation = dict(zip(day_name, range(7)))
def meetup_day(year, month, day_of_week, iteration):
day_of_week = weekday_translation[day_of_week]
(initial_weekday, days_in_month) = monthrange... |
c699e75ae99e408449a9563dbbc831813b7bab7c | sun5411/myPython | /aaa.py | 312 | 3.515625 | 4 | #!/usr/bin/env python
import re
str = '123&&sdfsfdsdfsf;123s9d9fsdf12315677a1'
number_list = re.findall(r"\d+",str)
string_list = re.findall(r"[a-z]+",str)
### 字符串排序
max_num = sorted(number_list,key=lambda x: len(x))[-1]
max_str = sorted(string_list,key=lambda x: len(x))[-1]
print max_num,max_str
|
0a436a6b91f74765427aa20324b6bdb4352db661 | slawry00/CSCI305 | /Lisp/linked_list.py | 5,473 | 4.15625 | 4 | #Spencer Lawry
#CPE103
#Lab03
#Instructor: Brian Jones
import math
# An AnyList is either None or a Pair(first, rest) where first can be any type
class Pair:
def __init__(self, first, rest):
self.first = first # some value
self.rest = rest # an AnyList
def __eq__(self, other):
return (ty... |
90952360d5774621b631509430682b78187be4ba | DorDob/Python | /second.py | 490 | 4.0625 | 4 | temp = 8
if temp > 20:
print('Chodźmy na spacer!')
elif temp == 20:
print('Robimy grilla <3!')
else:
print('Zostajemy w domu :(')
brand = 'BMW'
if brand == 'Ferrari':
print('red')
elif brand == 'BMW':
print('blue')
elif brand == 'Mercedes':
print('silver')
elif brand == 'Peugeot':
print('p... |
770fd76218559d858ba43bcdc21ce452f028382f | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/LouReis/Lesson02/grid_part_final.py | 1,939 | 4.4375 | 4 | # grid_part_final.py
#
# This is the assignment for Lesson2, each part of the exercise is included.
# As indicated in the exercise, "Do something reasonable", I attempted to meet
# the objectives of the exercise utilizing the demonstrated elements for
# string manipulation that were provided. The end result is a grid ... |
7284713032f82e3f82254ee6c21f0795c0a67a36 | barkev2009/test_tasks | /src/library_tables/table_navigation.py | 2,352 | 3.90625 | 4 | from src.utils import PostgreSQLStarter
def most_popular_author(year: int) -> tuple:
"""
Calculates the most popular author within a year
:param year: a year to search the most popular author in
:return: a tuple of the most popular author and the number of times
his/her books were taken b... |
52f53dfdf3cba5838d059cbb666cbe9a5701f8c1 | adrianotelecom/BlueInicio | /14-05-21/whihe2-14-05-21.py | 821 | 3.640625 | 4 | #for cout in range(1,61,2):
#print(cout)
"""
cont = -1
while cont <58:
cont+=2
print(cont)"""
"""
cont = 0
while cont < 60:
if cont % 2 != 0:
print(cont)
cont += 1"""
opc = 1
while opc == 1:
num = 1
cont = 1
numeros = []
numeros_solicitados = int(input('Quantos numero... |
fa462042336915fd8f96f1b402f9bb00e3fc63eb | vitthalpadwal/Python_Program | /hackerrank/preparation_kit/search/kittys_calculation_on_tree.py | 4,686 | 3.6875 | 4 | """
Kitty has a tree, , consisting of nodes where each node is uniquely labeled from to . Her friend Alex gave her sets, where each set contains distinct nodes. Kitty needs to calculate the following expression on each set:
where:
denotes an unordered pair of nodes belonging to the set.
denotes the number of ed... |
e92350fdc06b475cacf0390ffdf2653ccffa0796 | YigitAras/Crypto_Assignments | /TermProjectII/DS.py | 3,680 | 3.96875 | 4 | #!/home/yigitaras/anaconda3/envs/cryptoenv/bin/python3
from Crypto.Util import number
# the generation of the prime number is done by PyCrypto library
import math
import os
import random
import string
from Crypto.Hash import SHA3_256
def random_string(size=6, chars=string.ascii_uppercase + string.ascii_lowercase+ str... |
7761f018f0af7ebe184be4c0ec44ac4efdb26791 | gdh13/firedata | /statistics.py | 4,230 | 3.8125 | 4 | """
Compute daily statistics from fire data.
"""
class Statistics:
def __init__(self):
pass
def verify_ids_unique(self, incidents, get_unique_id):
"""
Make sure fire ids are unique. Don't trust your data sources!
Raises an Exception on duplicate
:param incidents:
... |
fad922f2db89b2efc0d2d5b23d2e7f4b678b2f37 | YangZeCN/PythonLearningCenter | /function_global.py | 904 | 4.25 | 4 | '''
Name: function_global.py
Author: Yang Ze
Created: 2018.01.30
Last Modified: 2019.04.02
Version: V1.1
Description:
# An example to define function and compare the
# difference between the global and local variable.
'''
global a
a = 10
def global_variable1():
'''Decalre a global variable, and as... |
470ac662552f8e3e788541aea2a226f8bd64e25c | perry-xy/SF | /Interview/twonumbers_sum.py | 325 | 3.53125 | 4 | # @Time : 2021/2/23 10:01 下午
# @Author : Xingyou Chen
# @File : twonumbers_sum.py
# @Software: PyCharm
def twonumbersum(li, target):
map = dict()
for i , num in enumerate(li):
if target - num in map:
return([i, map[target-num]])
map[num] = i
return []
print(twonumbersum([1,2,3... |
e970d23166156c647f1588661189414850aea0ec | rupeshchintakayala/Metrics-in-Python | /metrics in python.py | 2,478 | 3.734375 | 4 | import csv
def rmse():
with open('mae.csv') as f:
csv_reader = csv.reader(f, delimiter=',')
s=0
count=0
for row in csv_reader:
# print(f'{row[0]}\t{row[1]}\t{row[2]}')
s=s+abs(float(row[1])-float(row[2]))**2
count=count+1
print("Root Mean Square Error is", (s/count)**0.5)
def n... |
40c3fcf9796f02e517b626e74363030525a92ef6 | MaherBouidani/CrackTheCoding_InPython | /Chapter8/problem_1.py | 305 | 3.890625 | 4 | def count_ways(steps, dicti={}):
if steps < 0:
return 0
elif steps == 0:
return 1
if steps not in dicti:
dicti[steps] = count_ways(steps-1) + count_ways(steps-2) + count_ways(steps-3)
print(dicti)
return dicti[steps]
print(count_ways(10)) |
19f65c92ad8a8090ef2af577cf4a16ee7d105340 | dbulka/aircompany_repo | /core/models/flight_settings/flight.py | 637 | 3.578125 | 4 | class Flight:
"""
control of flight's setting
"""
def __init__(self, *args, **kwargs):
"""
initialize new flight's setting
:param id_order: order's indeficator
"""
def choose_class(self, *args, **kwargs):
"""
make choice between flight's classes
... |
d3f7fddad30ae44b4866d077b95dff8dc5a6753c | MirekPz/Altkom | /a/petle_listy/PE2.py | 464 | 3.75 | 4 | """
PE2 Wykorzystując instrukcje sterujące (break, continue) stwórzmy pętlę, która która dla zmiennej
(np. i) zmieniającej się od 0 do 1000 wyświetli wartość i, ale:
a) jeśli wartość jest podzielna przez 3 to nie wyświetli tej wartości
b) jeśli wartość jest podzielna przez 77 to przerwie działanie pętli
"""
i = 0
whi... |
4a067cdb3fac406ad16c4ab82c4dfe278038cd7c | Meaguileraa/flask-intro | /server.py | 3,412 | 3.765625 | 4 | """Greeting Flask app."""
from random import choice
from flask import Flask, request, render_template
# "__name__" is a special Python variable for the name of the current module
# Flask wants to know this to know what any imported things are relative to.
app = Flask(__name__)
AWESOMENESS = [
'awesome', 'terrifi... |
3347c8ec0a57de1027a6deaed043547b75a98af2 | vishnuvishnuvishnu/test | /typebased.py | 335 | 3.734375 | 4 | class Point():
#x = (a,b)
def __init__(self,a=0,b=0):
self.a = a
self.b = b
print self.a
print self.b
def __add__(self,other):
obj = Point()
if isinstance(other,Point):
obj.a = obj.a + self.a + other.a
obj.b = obj.b + self.b + other.b
return obj.a , obj.b
start = Point(9,4)
dur = Point(4,5)
pri... |
936854e309e037e704fdb67685d01b98a57eb99b | IlfatGub/Coursera-Phyton | /week4/Сложение без сложения.py | 172 | 3.78125 | 4 | # Сложение без сложения
def summa(a, b):
if a == 0:
return b
return summa(a-1, b+1)
a = int(input())
b = int(input())
print(summa(a, b))
|
4ca6b15282c74c99453b8ca82e6e92b8e5331eec | venuvasuu21/UNT-Search-Engine | /Crawler/Tokeniser.py | 1,985 | 3.8125 | 4 | #Author: Venugopal Gonela
#ID:11081500
#This code creates dictionary of words with or without stemming based on "stemFlag"
#by reading documents from the path specified and answers the questions in assignment1.
import os
import re
import platform
from porter_stemmer import PorterStemmer
class Tokeniser:
#Pat... |
0d120b7d3fb7807533573c721dc8f8672f4f7894 | jriall/leetcode | /easy/merge_two_binary_trees.py | 1,247 | 4.40625 | 4 | # Merge Two Binary Trees
# You are given two binary trees root1 and root2.
# Imagine that when you put one of them to cover the other, some nodes of the
# two trees are overlapped while the others are not. You need to merge the two
# trees into a new binary tree. The merge rule is that if two nodes overlap,
# then su... |
0ddd7b5b176ac42032e55881f94f823be4a778b3 | sungwoncho94/SWexpert | /intermediate/day_06/5105미로의거리.py | 1,432 | 3.5625 | 4 | def isOK(x, y):
return 0 <= y < N and 0<= x < N and (matrix[y][x] == 0 or m[y][x] == 3)
# 내가 방문한 이력과 거리를 동시에 바꾸면서 계속 길탐색
# Q를 사용하여 앞으로 갈 곳 탐색
T = int(input())
dx = [-1, 0, 1, 0] # 상, 우, 하, 좌
dy = [0, 1, 0, -1]
for t in range(1, T+1):
N = int(input())
distance = [[0] * N for _ in range(N)]
matrix ... |
9cade182b3ddf8c84185f2dbd7bc97edf452ec51 | Anirudh-Muthukumar/Python-Code | /0-1 BFS.py | 1,828 | 3.78125 | 4 | # Given a graph of binary weights, find the shortest path from source vertex to every other vertex
# Time complexity: O(V+E)
# Implemented using double ended queue: append vertices with weight 0 to left while others to right
from collections import deque
class node:
def __init__(self, to, weight):
self.... |
c9edd7ce3e1be5b16399cbc6e89e7bb602a213ea | NobodyIsThere/TP-G-Spring-Project | /Keplers law proof.py | 1,601 | 3.734375 | 4 | #Skeleton code starting point for Yr 1 Theory Group Project
from visual import *
dt = 0.00001 # timestep # the time step can be decreased to decrease the approximation
step = 1 # loop counter
# Define the star, planets and constants
M = 1000 # mass of star (G == 1)
m1 = 1 # mass of planet 1
initpos1 = vec... |
6a9185f485a1871d3150b65cc0c188decfdf359b | tolgakisin/python_mini_projects | /geometrik_sekiller.py | 1,623 | 3.75 | 4 | """
GEOMETRİK ŞEKİLLERİN HESAPLANMASI
"""
pi = 3.14
def kare(kenar):
return print(kenar * kenar)
def dikdortgen(kisa_k, uzun_k):
return print((kisa_k * uzun_k))
def yamuk(alt_t, ust_t, y):
return print(((alt_t + ust_t) * y) / 2)
def paralel_kenar(alt_t, y):
return print(alt_t * y)
def cembe... |
aab2345321873dd57af7f74689ebaa611f85c740 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/00bce8793591412b94cbfea0d116f802.py | 272 | 3.953125 | 4 | def distance(str1, str2):
'''Returns the hamming distance given two dna strands'''
if len(str1) != len(str2):
raise ValueError('Strands must be of equal length.')
dist = 0
for a, b in zip(str1, str2):
if a != b: dist += 1
return dist
|
ef2fbbcc983281f815aca2f2aef076defe4d7dbe | abi255/linear-regression | /SIMPLE LINEAR REGRESSION FOR BEGINNER.py | 3,385 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# In[2]:
df = pd.read_csv(r"C:\Users\Lenovo\Documents\1 PT Pos Indonesia (... |
84249c589e8541194c3173ef0220c72184d0f4e7 | SiriP05/simpleProjects | /palindrome.py | 146 | 4.25 | 4 | def palindrome(str)
rev=str[::-1]
if(rev == str)
print("palindrome")
else
print("not palindrome")
str = input("enter string")
|
1b67fbdac00852721f13fcce1848f56f33adcc19 | Louise-900/lecture_regression | /try_kfold_logistic.py | 1,785 | 3.53125 | 4 | import pandas
from sklearn import linear_model
from sklearn.model_selection import KFold
from sklearn import metrics
dataset = pandas.read_csv("dataset_3_outputs.csv")
target = dataset.iloc[:,2].values #column 1#
data = dataset.iloc[:,3:9].values
kfold_object = KFold(n_splits = 4) #chop our dataset into 4 parts
... |
3a31bdec01066c1d486a4058f48690ffad9a2bba | ttoso/python3_tutorial | /assets/format_methods.py | 184 | 3.5 | 4 | >>> miString = "soy UNA cadena"
>>> miString.capitalize()
Soy una cadena
>>> miString.lower()
soy una cadena
>>> miString.upper()
SOY UNA CADENA
>>> miString.swapcase()
SOY una CADENA
|
12b1a975279cb565fa139fad52203b3dcea90443 | mani5348/Python | /Day1/fifth.py | 137 | 3.796875 | 4 | a=int(input("Enter a Number by which we want find divisibilty: "))
for i in range(1,51):
if(i%a==0):
print("no.are ",i)
|
7ca4387e0e9fd844560714e100eb861afdcfebd0 | gokulrameshd/epai_session12 | /calculator/log.py | 437 | 3.703125 | 4 | import math
from scipy.misc import derivative
__all__ = ['log']
def log(args):
"""
This function returns the log value for the given input
"""
ret = math.log(args)
return ret
def get_derivative(fn,x):
der = derivative(fn,x,dx=1e-9)
return der
def log_derivative(x):
"""
This fun... |
814466579438e79cdd41209d36be5925c2a3cbf5 | aambrioso1/Miscellaneous_Python_Programs | /Dictionary for Cards.py | 847 | 3.8125 | 4 | #The dictionary Cards serves as a data structure for a deck of cards. A tuple (denomination, suit) serves as the key.
#This structure attempts to capture the way a person thinks of the cards.
Dens = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
Suits = ['... |
15cd035b623bb3e58e17b156a648bf349ef423b1 | Ni2Be/African-Swallow | /hello_world.py | 865 | 4.125 | 4 | import math
first = 'Python " '
last = 'test ""'
x = 3
y = 3.2
full = f"{first} new"
print(full)
print(x / y)
print(x // y)
print(2 ** 10)
print(2 + 4j, " + ", 2 + 44j, " = ", (2 + 4j) + (2 + 44j))
v = input("x: ")
print(float(v) + 33)
if float(v) <= 22 or float(v) > 44:
print("wtf")
else:
print("lol... |
60aba1db9aa2c31cc0b81d28a267938d1d580b09 | jeffreyongley/Machine-Learning-Project | /main.py | 4,071 | 3.65625 | 4 |
import pandas as pd #To read in file
import numpy as np #To use arrays that work well in python
import math #To use sqrt()
from collections import Counter #to count occurences of particular Y's in the KNN
import random #To use random when there are ties
filename = 'Data/Absenteeism_at_work.xls'
data = pd.read_excel(... |
5636d060b1985975c91e7b963bd4bc56557bf393 | YashK1299/LeetCode | /Sort an Array.py | 1,696 | 4.15625 | 4 | """
912. Sort an Array
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Constraints:
1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
"""
import random
class Solutio... |
f74729081f0c28d3f4319624fdfbc5d6aba8a1f5 | rmccampbell/PythonProjects | /fixtable.py | 824 | 3.671875 | 4 | #!/usr/bin/env python3
import sys, argparse
def print_table(arr, pad=2):
widths = [max(len(r[i]) for r in arr if i < len(r))
for i in range(max(map(len, arr)))]
enc = sys.stdout.encoding
for r in arr:
l = (' '*pad).join(s.ljust(widths[i]) for i, s in enumerate(r))
print(l.enco... |
e48680b249815fe60367ff5626ff0722e9892805 | algoRhythm10/StudentScorePrediction | /Student_%_prediction/student.py | 1,824 | 3.53125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#read data
data_load = pd.read_excel("C:\\Users\\Rhythm\\OneDrive\\Desktop\\Student_%_prediction\\rawdata.xlsx", engine='openpyxl')
print("\nSuccessfully imported data into console\n" )
data_load.head(6)
# Plot the dist... |
fde5ed00e73f3a056f2d7c7e8a54b3acc4451d40 | Skipper609/python | /Sample/ran.py | 238 | 3.5625 | 4 | '''
gen 100 random nums 1-1000
get only divisible by 3,6 but not 9
'''
import random as rn
num = []
for i in range(100):
num.append(rn.randint(1,1000))
for number in num:
if num % 6 == 0 and num % 9 != 0:
print(number) |
549188c0e6582ec77e31459bb83aca42845ac172 | klasdq222/ai_course | /check_cross.py | 2,859 | 3.984375 | 4 | # 区域编码
LEFT_BIT_CODE = 1
RIGHT_BIT_CODE = 2
BOTTOM_BIT_CODE = 4
TOP_BIT_CODE = 8
def convert_pos(pos):
'''
convert coordinate
pos is a list which length is 4.
pos[0] is the start x of rectangle
pos[1] is the start y of rectangle
pos[2] is offset in x,width of rectangle
... |
72b38f83e488da4f0ea4c379ab2fa47baaa41ecf | hksoftcorn/Algorithm | /2005_파스칼의 삼각형/sol2.py | 714 | 3.625 | 4 | import sys
sys.stdin = open('input.txt')
def solution():
def factorial(k):
if k == 0 or k == 1:
return 1
return k * factorial(k-1)
def rev_factorial(n, k):
count = 1
if k == 0:
return count
else:
for i in range(k):
co... |
9f77dd3424e78a1d1f00abfd0623ca40c48c8d23 | mereszd/aoc2019 | /01_01_sol.py | 185 | 3.609375 | 4 | input_array = []
sum = 0
with open("01_01_input.txt", "r") as f:
for x in f:
input_array.append(int(x.strip()))
for x in input_array:
sum = sum + (x//3 - 2)
print(sum) |
45a859956243e959013fdfc4928b84f440cb569b | FerFabbiano/Algoritmos-I | /Clase 15-05 (corte_control_uno).py | 2,883 | 3.65625 | 4 | """ Corte de control: UN CORTE """
"""
* El formato del archivo de ventas es:
* CSV: fecha, vendedor, monto
* Ordenado de menor a mayor por fecha y luego por vendedor
"""
# constantes
MAX_DIA = "9999-99-99"
MAX_REG = MAX_DIA + ",xxx,0"
# funciones ==============================================... |
9913010ce223db8fa955aa4c8eb95ec1f041c63f | yim0sook/Python-Exp01 | /contacts2.py | 1,170 | 3.90625 | 4 | import sqlite3
db = sqlite3.connect("contacts.sqlite")
new_email = 'new@email.com'
#phone = 56456
phone =input("Please enter the phone number")
#update_sql = "UPDATE contacts SET email = 'anotherupdate@email.com' WHERE contacts.phone = 56456"
# sql1: update_sql = "UPDATE contacts SET email = '{}' WHERE phon... |
9f0f48e6a8620d06b93583157a57607fd2c0905c | deamoraes/gama-academy | /circle.py | 368 | 4.09375 | 4 |
class Circle():
def __init__(self, radius):
self.radius = radius
def get_area(self):
return 3.14 * (self.radius ** 2)
def get_circumference(self):
return self.radius * 2 * 3.14
radius = float(input("Digite o radius:"))
circle = Circle(radius)
print(f'Área = {circle.get_area():.2f}')
print(f"Circunferênc... |
45e84cea6eed4904b5505cb5e2abc28499971238 | qureshiowais91/REST-API-with-Flask | /Google Script app/mix/main.py | 674 | 3.859375 | 4 | # def squar(x):
# return x*x
# def multiply(func, arr_args):
# result = []
# for i in arr_args:
# result.append(func(i))
# return result
# total = multiply(squar,[1,2,3,4,5])
# print(total)
# def logger(msg):
# def inner_logger():
# print('log :', msg)
# return inner_logger
... |
d3b1388ae2ef42b2e28dcf8af0ca20d2f7d798f0 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/JonathanMauk/Lesson01/comprehensions.py | 857 | 3.53125 | 4 | import pandas as pd
music = pd.read_csv("featuresdf.csv")
song_list = [x for x in zip(music.danceability, music.loudness, music.name, music.artists)
if x[0] > 0.8 and x[1] < -5]
quiet_and_danceable = sorted(song_list, reverse=True)
print("Type five songs by danceability with loudness less than -5:\n")
... |
7877e19b19ac0fc762feed10116eed4722a4a407 | ricaenriquez/intro_to_ds | /project_5/riders_per_station/riders_per_station_reducer.py | 775 | 3.84375 | 4 | import sys
def reducer():
'''
Given the output of the mapper for this exercise, the reducer should return one row
per unit, along with the total number of ENTRIESn_hourly over the course of may.
You can assume that the input to the reducer is sorted by UNIT, such that all rows
corresponding ... |
acda90c1d83b74db7cfb6aa11194a702d5b188d9 | mhiloca/PythonBootcamp | /OOP_exercies/products.py | 1,465 | 3.671875 | 4 | def decor(n):
print('- ' * n)
class Bill(list):
def __init__(self):
super().__init__()
while True:
decor(5)
self.append(Product())
while True:
ans = input('Register another product? ').strip().upper()[0]
if ans not in 'NY':
... |
507ea9581095a5ce2120b959e9b00f04c94eb806 | dtmahony/Learning-python | /divisors.py | 329 | 3.859375 | 4 | #!/usr/bin/python
i = 0
while i == 0:
num = int(input("Please enter a positive integer between 2 and 65535: "))
if 1 < num <= 65535:
i += 1
else:
print(num, "is outside the specified range")
j = 2
while 1 < j <= (num / 2):
if (num % j) == 0:
print(j, end=' ')
j += 1
pri... |
803ed60755596b6a4d63ee76a3185626c3793f74 | JianghaoPi/LeetCode | /1-100/54.py | 1,107 | 3.5 | 4 | class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
if len(matrix) == 1:
return matrix[0]
if len(matrix[0]) == 1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.