blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
26c57e4c586f37e462950c0bab4d57ba62412fc4 | amirdharaja/sarah | /fact.py | 196 | 3.6875 | 4 | # by Amirdharajan
try:
def fact(n):
fact=1
for i in range(1,n+1):
fact=fact*i
print(fact)
n=int(input())
fact(n)
except:
print("invalid input")
|
0c5daa1d895769ac46181645ac90cf11374bc586 | IamWilliamWang/Leetcode-practice | /2020.9/搜狗-2.py | 1,248 | 3.5 | 4 | #
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 返回能创建的房屋数
# @param width int整型 要建的房屋面宽
# @param data int整型一维数组 已有房屋的值,其中 x0 a0 x1 a1 x2 a2 ... xi ai 就是所有房屋的坐标和房屋面宽。 其中坐标是有序的(由小到大)
# @return int整型
#
class Solution:
def getHouses(self, width, data):
centerPotential = []
for i in range(0, len(data), 2):
... |
b7d0035e98565f306b2d70b9af400a33b0a606db | daanyaanand/ConnectFour-Game---Winter-2017 | /overlapping_functions.py | 3,363 | 3.625 | 4 | import connectfour
import collections
GameStateAndMove = collections.namedtuple('GameStateAndMove', ['GameState','move'])
def print_welcome_message() -> None:
''' Prints welcome message '''
welcome_message = 'Welcome to Connect Four!\nPlay by choosing column number to drop or pop (remove) your piece in or ... |
249aca9540d7298b182131de0d812956d9448955 | johnnzz/foundations_python | /module4/scratch/assignment4-list-of-tupples.py | 2,404 | 4.1875 | 4 | '''
Module 4 Assignment
Foundations of Programming: Python
13 July 2016
Instructor: Randal Root
Student: John Navitsky
Description:
Program that asks the user for the name of a household item, and
then asks for its estimated value. Ask the user for new entries
and store them in the 2 dimensional Tu... |
cbe9c4e60e4fffc2c84de038504a4d111f158c95 | sagivmis/Casino | /war.py | 2,362 | 3.546875 | 4 | def replay():
again = input("Another game? y or n")
while again != "y" and again != "n":
again = input("Another game?")
if again == "y":
return True
else:
return False
def count_cards(cards_list):
count = 0
for _ in cards_list:
count += 1
retur... |
5d9e071c456a242d5648d9ae5ad222e947283dcd | lazzarine/LMS-OFC | /OFC-LMS/firetek/firetek/funçoes.py | 329 | 3.640625 | 4 | count = print
class printTest(object):
def test (self):
a = 5
count(a)
pt = printTest()
pt.test()
#def contar(A):
# return [len(x) for x in A]
lst = ['teste de python']
#print (contar(lst))
print ('Com lambda')
contar = lambda lst: [len(x) for x in lst]
print (contar(lst))
teste = list(map(lambda x: x*... |
fb0523aa501cf6abe46f29976ecb0c9b3774bc80 | mtyton/SkyTask | /skyphrase/shyphrase.py | 784 | 3.640625 | 4 | def read_file():
"""
Simplyb reads the file
:return:
"""
container = []
file = open("skychallenge_skyphrase_input.txt", "r").read()
lines = file.split("\n")
for line in lines:
phrases = line.split(" ")
container.append(phrases)
return container
def che... |
46710e021657795e54522f6820ae99429b93b0bb | DinoSubbu/SmartEnergyManagementSystem | /backend/gasBoiler/hot_water_demand_api.py | 3,911 | 3.65625 | 4 | from datetime import datetime
import config
import csv
import os
############################################### Formula Explanation ##############################################
# Formula to calculate Heat Energy required :
# Heat Energy (Joule) = Density_Water (kg/l) * Specific_Heat_water (J/Kg/degree Celsius)... |
a374a6044fc3d896da1bf7b3a533a78f09700c1f | AnkusManish/Machine-Learning | /Week4/Pandas/Program_2.py | 327 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 19:30:13 2019
@author: ankusmanish
"""
# Write a Python program to convert a Panda module Series to Python list and it's type
import pandas as pd
data = pd.Series(data = [1,2,3,4,5,6,7,8,9,10])
print(type(data))
data = list(data)
print(type... |
368358b20c77b6b4005559a5853e57f2e87a8b64 | ahernot/UE11-equations-differentielles | /legacy/code_anatole.py | 5,438 | 3.65625 | 4 | from typing import Callable
import numpy as np
def solve_euler_explicit(f: Callable, x0: float, dt: float, t0: float, tf: float):
"""
This function applies an explicit Euler scheme to numerically calculate the points of a function x defined by its first
derivative function f, using a set time step, on a se... |
f51a87c5d2d47c61268cbd355f84e68b233e5e91 | ma-shamshiri/Mosh | /Sentence.py | 1,008 | 3.859375 | 4 | from pprint import pprint
sentence = "This is a common interview question"
dictionary = {letter: sentence.count(letter) for letter in sentence}
# print(dictionary)
# sorted_dictionary = sorted(key=lambda item: item[1], dictionary)
# sorted_dictionary = dictionary.sort(key=lambda item: item[1])
# my = dict(("a"=1), ("b... |
ebd0753e540e27e54cc19a3adc3bc95f5e4303de | DraperHXY/PythonLearning | /com/draper/generate_def/first/field2.py | 532 | 3.75 | 4 | """
内嵌函数不起作用
因为嵌套作用域中的变量被调用才查找,所以实际上指向了相同的值
"""
def count():
fs = []
for i in range(1, 4):
def f():
return i * i
fs.append(f)
return fs
f1 = count()
for i in f1:
print(i())
def count1():
fs = []
for i in range(1, 4):
def f(i):
def g():
... |
4dc7c796604ecc3472ba65ba13421ddad8aca943 | inwk6312winter2019/classroomtask1-Mavullu-Surya-Raghava-Nallamatti | /lab3/l3t10.py | 170 | 3.609375 | 4 | def histogram(string):
d=dict()
for c in string:
k=d.get(c,0)
print(k)
''' if c not in d:
d[c]=1
else:
d[c]+=1
return d'''
histogram('hello how are you')
|
63c48f5a3fe36522cd955d20ee56f9c10ff63d51 | berinhard/forkinrio_exercises | /exercicios/parte_1/parte_1_1_test.py | 877 | 3.71875 | 4 | #-*- coding: utf-8 -*-
import unittest
from parte_1_1 import fahrenheit_to_celsius
from parte_1_1 import celsius_to_fahrenheit
class TestConversaoEscalas(unittest.TestCase):
def test_fahrenheit_to_celsius_one(self):
self.assertEqual(fahrenheit_to_celsius(68), 20)
def test_fahrenheit_to_celsius_one(s... |
573a4b16b922499c5051225c4f2b072f808d6a32 | matheusfelipeog/jogos-terminal | /Jogo do Numero Magico/jogoDoNumeroMagico.py | 1,625 | 3.9375 | 4 | # Importando seletor aleatório em determinado intervalo
from random import randrange
# Importando modúlo que manipula o sistema
from os import system
system('cls||clear') # Método sendo usado para limpar a tela do prompt/terminal
# passando como parâmetro cls (Limpa no windows) e clear (linux)
#... |
4b130db9066095299381ee5ba3baff79f4105dcc | jiankangliu/baseOfPython | /PycharmProjects/02_Python官方文档/一、Python初步介绍/02_Python核心对象、变量、输入和输出/2.4编程项目.py | 1,024 | 4.09375 | 4 | #1找零钱
strMoney=input("Enter amount of change:")
money=int(strMoney)
Quarters=money//25
money=money%25
Dimes=money//10
money=money%10
Nickels=money//5
money=money%5
Cents=money
print("Quarter: ",Quarters,"\t","Dimes: ",Dimes,"\n","Nickels: ",
Nickels,"\t","Cents: ",Cents,sep="")
#2汽车贷款
loan=float(in... |
7ecdfbeb5539e013a4e9aa29f584932fe3542344 | AM0511-kee/workspace | /namespacing.py | 562 | 4.1875 | 4 | """name spacing means unique name for every object in python"""
"""there are three types of name spacind they are build in name spacing,local namespacing,global name spacing"""
var=10
def name_spacing():
global var
var=var+1
print(var)
name_spacing()
var="string"
def name_spacing():
var=11
pri... |
55f52e412cd94524c305db13967811ae0556e672 | HanPong/PythonPractise | /LottoNumbers.py | 929 | 3.875 | 4 | #编写一个程序决定输入的数字是否涵盖了1到99之间的数
isCovered=99*[False]#创建了99个初始化为false的布尔类型列表
endOfInput=False
while not endOfInput:
#Read numbers as a string from the console
s=input("Enter a line of numbers separated by spaces: ")
items=s.split()#把字符串s按照空格分开
lst=[eval(x)for x in items]#将item中的元素转换成数字并储存在1st数组中
for num... |
d9d8579a52a70607e42aa35aa9797232e1fb5dd6 | minus9d/programming_contest_archive | /agc/003/b/b.py | 272 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
N = int(input())
ans = 0
carry = 0
for n in range(N):
a = int(input())
if carry and a > 0:
ans += 1
a -= 1
ans += a // 2
if a % 2 == 1:
carry = 1
else:
carry = 0
print(ans)
|
f84cb4f84081acf104912f7da38bf02c20a20467 | vcaitite/hangman | /read_txt_archive.py | 441 | 3.625 | 4 | from pathlib import Path
import random
path = Path('./word_list.txt')
def archive_lines():
if path.is_file():
with open(path, 'r') as f:
lines = (f.readlines())
return lines
else:
raise Exception("Word list archive doesn't exist 😞")
def read_random_word():
line... |
b45908acb4df26a763550a31843fe69743ba7e3d | theangi/hackerrank | /security/02_inverse_function.py | 155 | 4 | 4 | def print_inverse_function():
_ = input()
values = input().split()
for i, _ in enumerate(values):
print(values.index(str(i + 1)) + 1)
|
fcaba3cde5e08bdc5368596f20cef04524249506 | AdhwaithMenon601/Resource-Allocation-Bot- | /envs/custom_env/ResourceAlloc.py | 2,234 | 3.875 | 4 | import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib import style
import gym
from gym import utils
from gym.envs.toy_text import discrete
"""
The actions are as follows -
0 : Add to M1
1 : Add to M2
2 : Add to M3
3 : Do nothing
"""
#Render is not required for the given function
class Resourc... |
ca716ace666d02529d8e0a99fafbb19e47bafcf4 | zhanjw/leetcode | /codes_auto/543.diameter-of-binary-tree.py | 799 | 3.734375 | 4 | #
# @lc app=leetcode.cn id=543 lang=python
#
# [543] diameter-of-binary-tree
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def diameterOfBinaryTree(self, root):
... |
c3bcbe95d793d9ee9d48513ec17a661258e792a7 | kschultze/Learning-Python | /Assignment_2/diaphantine3_rev1.py | 860 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
07/26/16
@Schultze
Script to calculate chicken nuggets combinations
Using an iterated version of diaphantine2_rev1.py, this code finds the largest
value for n for which no combination of A, B, and C exist.
"""
A = 6
B = 9
C = 20
isPossible = ()
for n in range(1,200):
maxA = n//A
... |
a73ad754dcd74111852714e6533bb3ef9fc60baa | Jens2/Similarity-and-Symmetry | /final/fastgraphs.py | 2,525 | 3.53125 | 4 | from final.basicgraphs import vertex, graph, GraphError, edge
class FastVertex(vertex):
def __init__(self, graph, label=0):
self._graph = graph
self._label = label
self._inclist = []
self._colornum = 1
def getLabel(self):
return self._label
def setLabel(self, n):... |
173746433e541bc580cc10572d649b72b8194cd5 | kmcgrady/streamlit-example | /streamlit_app.py | 652 | 3.59375 | 4 | import streamlit as st
import pandas as pd
with st.echo("below"):
st.write(
"Once a single column is selected, there is no going back. You can add a second in the multiselct, but it won't change anything. Rerunning does not help. Your only hope is to refresh the page."
)
df = pd.DataFrame... |
9a41c9a514d61a35306de193da9bb97ada3153cb | FelixWessel/SimpleSnakeGame | /SimpleSnakeGame.py | 5,653 | 4.0625 | 4 | # This is a work in progress - not finished and not working yet
import pygame
import sys
from random import randint
pygame.init()
#Definition of variables for the game
run = True # As long as run equals true the game runs
screen_width = 600 # Setting the widt... |
f8b786347bd9afac79a0cc913b628390bd564aa1 | wcsodw1/Computer-Vision | /CV_Pyimage/Module 1 CV Basic Technical/chp_1_4_Image preproccesing/David_1_4_4_flipping.py | 900 | 3.71875 | 4 | # python David_1_4_4_flipping.py --image "../../../CV-PyImageSearch Gurus Course/Dataset/data/girl.JPG"
import argparse
import cv2
# 1.Preprocessing
# 1.1 construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image"... |
170811c5bdbe01274b4a31432d9e3e6ee8794717 | SPK44/Weekly-Programming-Challenge | /december2016/ddides.py | 239 | 3.828125 | 4 | #!/usr/bin/env python
def missing_num(nums):
return list(filter(lambda x: x not in nums, range(1, max(nums)+1))).pop(0)
if __name__ == '__main__':
assert missing_num([7,8,10,3,6,5,1,2,9]) == 4
assert missing_num([1,3]) == 2
|
cb5c87f24300a2dcc9e8c14c2470ccb543566c74 | athul-santhosh/Leetcode | /202 Happy Number.py | 893 | 3.5 | 4 | def getDigits(self, n: int) -> list:
res = []
while n:
d, m = divmod(n, 10)
res.append(m)
n = d
return res
def isHappy(self, n: int) -> bool:
s = set()
while 1:
s.add(n)
get_sum = sum(map(lambda x: x*x, self... |
2daeec9789ebd793d1b2af379a0628132f92b84f | OutJeck/tic-tac-toe | /game.py | 1,584 | 3.953125 | 4 | """Realizes main module for the tic tac toe game."""
from board import Board, IncorrectPosition
from btree import BTree
def main():
"""Realizes tic tac toe game."""
board = Board()
print(draw_example())
print("Enter a pair of coordinates separated by space from 0 to 2 "
"(Example of input... |
b9f52c9599ac280a6011464b904bb622891cada3 | Nmewada/hello-python | /60_practice.py | 181 | 3.875 | 4 | '''
Write a python function to print the first n lines of the following pattern.
***
**
*
#For n = 3'''
n = 3
for i in range(n):
print("*" * (n-i)) # Prints * n-i times |
c948e89a119a922303357a3a55c9b375f3d6758c | venkatkorapaty/MultiSetSkipList | /multiset.py | 10,893 | 4 | 4 | from skiplist import *
class MultiSet():
def __init__(self):
'''
Initiates the MultiSet with a SkipList
'''
self.sl = SkipList()
def __contains__(self, e):
'''(MultiSet, Object) -> bool
Takes in an element and a MultiSet, checks if the element is contained
... |
373384c8242147b888a0974c925f8f40eb34966f | weightedEights/projectEuler | /weightedEights/prob20/projectEuler.prob20.py | 818 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
"""
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
"""
"""
... |
5b18f8f04839a1f608bc08a93cad91f53bd38873 | Abhipanda4/PyTorch-Examples | /regression.py | 1,337 | 3.59375 | 4 | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
torch.manual_seed(0)
# Dummy training data
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + 0.1 * torch.randn(x.size())
x, y = Variable(x), Variable(y)
# print(x)
# print(y)
# a 1 hid... |
05e489475d96fd2432943b150c099329360bd2c0 | aadityamp01/mathpy | /Sequence generation/Traingular sequence.py | 313 | 3.890625 | 4 | class Mathematics :
def __init__(self,n):
self.n=int(n);
def triang(self):
i=1;
while i<(self.n+1.0):
t=(i*(i+1))/2;
if i!=self.n:
print(t,end=", ");
i=i+1;
else:
print(t);
return;
|
d48176c5f2ec54bfbd56968a494750c987cdc7b0 | vertocode/python-course-challenges | /Mundo 1/desafio05.py | 151 | 4.03125 | 4 | print('Calculador de antecessor e sucessor')
n = int(input('Número: '))
print('O antecessor de {} é {} \nO sucessor de {} é {}'.format(n,n-1,n,n+1)) |
1c7896d1455482a825a93034df4520a35d05dd82 | gopikm/chainercv | /chainercv/evaluations/eval_pck.py | 1,497 | 3.546875 | 4 | import numpy as np
def eval_pck(pred, expected, alpha, L):
"""Calculate PCK (Percentage of Correct Keypoints).
This function calculates number of vertices whose positions are correctly
pred.
A pred keypoint is correctly matched to the ground truth if it lies
within Euclidean distance :math:`\\alp... |
4a194dd2ecbfb72ac09cd2b146442e896063b93e | avivko/pythonWS1819 | /practiceFromWorksheet.py | 2,777 | 3.734375 | 4 | import random
def part_one_one(n):
for i in range(0, n):
print(2 ** i)
def part_one_two_version_one(n):
biggest = 0
for i in range(0, n):
if biggest <= n:
biggest = 2 ** i
else:
biggest = biggest / 2
return round(biggest)
def part_one_two_ver... |
f82005125b24817fde62d458cb6817f7aae27d6b | BenTildark/sprockets-d | /DTEC501-Lab8-2/lab8-2_q1.py | 1,146 | 4.53125 | 5 | """
Write a program to ask the user to enter their first and last names and mobile number.
Store the user entered data in a dictionary and display as below.
Hint.
Treat the mobile number as a string.
Example
Please enter your given name: dave
Please enter your surname: bracken
Please enter your mobile number: 022555... |
3458b8f1a8806d078d221482e7eb47f20ecdf88f | guangyi/Algorithm | /step_recursive.py | 1,251 | 3.640625 | 4 | '''
Created on Mar 9, 2013
@author: zhouguangyi2009
'''
import sets
def step_count(n):
dic = {}
if n == 1:
steps = ['1']
dic[1] = steps
return steps
if n == 2:
steps = ['11','2']
dic[2] = steps
return steps
if n == 3:
steps = ['111','12','21'... |
da5aa11146cdd6601b9b40b4ad3fe76d7f824e9c | prem-pratap/Python-Tkinter-Tutorial | /tkinter6.py | 362 | 4.0625 | 4 | #Binding functions to button
from tkinter import *
start=Tk()
def callme():
print("Hey Dude!!!!")
def second(event):
print("Second Method")
button=Button(start,text="Click me",command=callme)
button2=Button(start,text="SecondMethod")
button2.bind("<Button-1>",second)#Function is called on left mouse click
butto... |
215a0fb36f83b54fc7476b6224d8ca22e931a7e3 | DaniGodin/LeafModeling | /AlgoLeaf/particle_transportation/leaf_object.py | 2,373 | 3.640625 | 4 | """
This module implement the class Leaf and Venation Point
"""
import numpy as np
from pylab import *
from matplotlib import collections as mc
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
class Leaf:
"""
This object decribe the leaf shape
attributes:
shape: parametric... |
01b66278d10fc883ea9f752ada16b78c8ab9993e | jGallicchio/HW8 | /binarytree.py | 4,406 | 3.609375 | 4 | from fractions import Fraction
import itertools
import sys
ops = ['+', '-', '*', '/']
d = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13}
class BNode:
def __init__(self, element):
self.element = element
self.left = None
self.righ... |
ba1175394d2562d42e4d73631debba07c4ab18b7 | Beardocracy/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/tests/test_models/test_rectangle.py | 6,769 | 3.609375 | 4 | #!/usr/bin/python3
''' This module tests the rectangle class '''
import unittest
import sys
from models.rectangle import Rectangle
from models.base import Base
class TestRectangle(unittest.TestCase):
''' This is a unittest for class rectangle '''
def setUp(self):
''' Resets the class variable'''
... |
8d62f6cba3d5e6b98efa51103b27414b93c721f3 | tbhall/DFAs | /src/minimizing-DFA.py | 4,733 | 3.546875 | 4 | #!/bin/python
# -*- coding: utf-8 -*-
###############################################################################
### ###
### Description: Read the description of a DFA from a text file, and write ###
### (to standard output) the description... |
fba8f796a41c43d442b43240179a28ee8763ed64 | broepke/GTx | /part_3/4.5.4_modify_dict.py | 1,955 | 4.53125 | 5 | # Write a function called modify_dict. modify_dict takes one
# parameter, a dictionary. The dictionary's keys are people's
# last names, and the dictionary's values are people's first
# names. For example, the key "Joyner" would have the value
# "David".
#
# modify_dict should delete any key-value pair for which the
# ... |
b3a71e83873a8a34dc8bed1002952f818855e5b0 | cauegonzalez/cursoPython | /listaDeExercicios/ex065.py | 844 | 4.1875 | 4 | # coding=UTF-8
# Crie um programa que leia vários números inteiros pelo teclado.
# No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos.
# O programa deve pergutnar ao usuário se ele quer ou não continuar a digitar valores
numero = soma = i = menor = maior = 0
continua... |
fc4c29c1a674e2be4a0e91e9a06ba2be4d68fa6f | friedlich/python | /19年7月/7.23/垃圾分类.py | 3,873 | 3.578125 | 4 | # 首先,导入所需要的相关模块。
import requests
from bs4 import BeautifulSoup
from urllib.request import quote
import tkinter
from tkinter import Tk,Button,Entry,Label,Text,END
# 接着,请求爬取网页。
def crawl(word):
# -------------加了requests headers
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.3... |
dedf504b214dab71077788aea97ede0f75b0e41b | ChrysWillians/exercicios-python3 | /ex040.py | 467 | 3.890625 | 4 | print('/' * 30)
print('Calcule a média de suas notas:')
print('/' * 30)
n1 = float(input('Primeira nota: '))
n2 = float(input('Segunda nota: '))
print('/' * 30)
media = (n1 + n2) / 2
print('A média de {:.1f} e {:.1f} foi: {:.1f}'.format(n1, n2, media))
print('/' * 30)
if media >= 7:
print('PARABÉNS, você ... |
ab9cd49686a7c169a638d9d9a2c7d667a8d9db08 | jakemiller13/School | /MITx 6.00.1x - Introduction to Computer Programming Using Python/Problem Set 2_1.py | 1,522 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 26 06:23:17 2017
@author: Jake
"""
def yearlyBalance(balance, annualInterestRate, monthlyPaymentRate):
'''
Given a balance, annual interest rate, and monthly payment rate,
will calculate credit card balance at end of one year
... |
f097bfece015d0746248c7aa3c5a4a0d42f1ce58 | CDivyaPrabha/CP1404Practicals | /prac_02/Do-from-scratch exercises/files.py | 580 | 4.03125 | 4 | #First program
name = input("Enter your name: ")
out_file = open('name.txt', 'w')
print(name, file=out_file)
out_file.close()
#Second Program
in_file = open('name.txt', 'r')
name = in_file.read().strip()
print('Your name is', name)
in_file.close()
#Third program
in_file = open('numbers.rtf', 'r')
number1 = int(in_f... |
b1ac105fc041929780978f18f74079696d2dc897 | katcreardon/PythonCrashCourse | /Ch09/orderedDict_rewrite.py | 894 | 3.875 | 4 | from collections import OrderedDict
glossary = OrderedDict()
glossary['dictionary'] = 'a collection of key-value pairs'
glossary['key-value pair'] = 'a set of values associated with each other'
glossary['conditional statement'] = 'a statement that evaluates to either true or false'
glossary['for loop'] = 'allows you ... |
bdc9657ff6bec9bb87bb066b6d6c4640ff6549c7 | DarrRayr/1_1 | /game1.py | 424 | 3.53125 | 4 | import time
import math
print("Welcome to battle sim")
print("")
time.sleep(2)
bag = [""]
health = 100
def wolf_battle():
print("You have ran into a wolf!")
wolf_health = 100
descision = 1
if descision == 1:
print("Bag | Battle | Run")
descision1 = input(" ")
if descision1.lower == ("bag"):
... |
1241826d3bc71b88f9d325cd60d551dd9c4730f5 | kacou12/les_scripts_cours | /fonction/function4.py | 789 | 3.921875 | 4 | from math import pi,sqrt
a=(input("demi grand axe a = "))
b=(input("demi axe moyen b = "))
c=(input("demi petit axe c = "))
d=(input("densité d = "))
def volMasseEllipsoide(a=10,b=8,c=6,d=1):
volume = float((4/3)*pi*a*b*c)
e=sqrt((a**2-c**2)/a)
masse=d*volume
return e, volume, masse
try:
... |
6d43e0845c603d3da0a851bd1dea18620ee7414d | klakor/nauka_pythona | /slownik.py | 322 | 3.90625 | 4 | samolot = {'name': 'boeing',
'przebieg': 10000,
'typ': 'pasazerski'}
#in python3 samolot.items()
for key, value in samolot.items():
print("{0} : {1}".format(key, value))
print(samolot['name'] + " jest samolotem " + samolot['typ'] + "m.")
#
for key in samolot:
print("{0}:{1}".format(key, value)... |
01221f7657f0139ee04c038a8d8a5104d030124a | Purnima124/if-else.py | /num greater than.py | 166 | 4.1875 | 4 | num=int(input("enter the number"))
if num>=50:
print("num greater than 50")
elif num%2==0:
print("it is even number")
else:
print("it is odd number")
|
250a5df623a7dadac0b75ce3dcb64cd3291daa4d | taehwan920/Algorithm | /baekjoon/2193_i-chin-num.py | 178 | 3.625 | 4 | n = int(input())
cache = [0] * 3
cache[0] = 1
cache[1] = 1
for i in range(2, n):
cache[2] = cache[0] + cache[1]
cache[0], cache[1] = cache[1], cache[2]
print(cache[1])
|
be17627607362bef4b85efd9d9075fabca591209 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_97/485.py | 738 | 3.859375 | 4 | import string
def int_input():
return int(raw_input())
def list_int_input():
return [int(i) for i in raw_input().split()]
def count_higher_pairs(num, a, b):
num_str = str(num);
count = 0;
counted_number = {}
for i in range(1, len(num_str)):
new_num = int(num_str[-i:] + num_str[:-i])
if a <= new_num and new... |
e023c2df1882592401c96db5b8908efd6569e07c | jtenhave/AdventOfCode | /2019/Day6/c.py | 956 | 3.5 | 4 | import re
orbitPattern = re.compile("(\w*)\)(\w*)")
# Class that represents an orbiting object.
class Object:
def __init__(self, id):
self.id = id
self.parent = None
# Total number of orbits this object has around the central mass.
def totalOrbits(self):
if not self.parent:
... |
a20b9d2eac3837b4cc41cf686c73bb4c7d221d7d | ellynnhitran/Fundamentals_C4T4 | /Session01/polygon.py | 243 | 4.03125 | 4 | from turtle import *
speed(-1)
shape("turtle")
color("purple")
# number = int(input("How many polygons you need?"))
# ans = 0 + int(number)
# print("I want", ans)
n = 5
for i in range(n):
forward (100)
left(360//n)
mainloop() |
41635d13e0adeff19398a884b00fc4e7256bcc6c | madhav06/LazyBear_for_DS | /Trees/Implement-binary-heap.py | 3,307 | 4.40625 | 4 | # This is a python program to implement a binary heap.
# The program creates a binary max-heap and presents a menu to the user to perform various operations on it.
# Strategy:
# Create a class BinaryHeap with an instance variable items set to an empty list.
# This empty list is used to store the binary heap.
# Def... |
6d585d8785caac2d276a1e1705e37367f3f7c76e | eronekogin/leetcode | /2020/lexicographical_numbers.py | 616 | 3.703125 | 4 | """
https://leetcode.com/problems/lexicographical-numbers/
"""
from typing import List
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
rslt = [1]
while len(rslt) < n:
nextNum = rslt[-1] * 10
while nextNum > n:
nextNum //= 10
ne... |
cfe9875e3cd55911eeb26813e0b1bbe14fb7b452 | RevanthR/SHC | /linear_reg.py | 579 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error,r2_score
np.random.seed(0)
x=np.random.rand(100,1)
y=2+3*x+np.random.rand(100,1)
regression_model=LinearRegression()
regression_model.fit(x,y)
y_predicted=regression_... |
94ea9a4d02007b71bb72a00377ca547fb07f41e0 | caiocotts/ics2017 | /Lesson4/8-PoundsToKilos.py | 125 | 3.84375 | 4 | pounds = float(input("Enter the value in pounds: "))
kilos = pounds * 0.454
print(pounds, "pounds is", kilos, "kilograms") |
9ad1b861e6aebbddb8a2b9cbee7f0fb2f61eafc5 | natarajanct/Leetcode | /28_Implement_strStr()_v1.py | 257 | 3.671875 | 4 | def strStr(self, haystack, needle):
if len(needle)==0:
return 0
elif needle in haystack:
for i in range(len(haystack)):
if(haystack[i:i+len(needle)]==needle):
return i
else:
return -1
|
9c5ffb4ac3710b761c246654ed1e30802ad8f103 | ScaredTuna/Python | /BinaryConverter.py | 806 | 4.0625 | 4 | def binary():
num = ""
while num == "":
print("-----------------------------------------------")
num = input("Enter a Binary Number:")
i = 0
while i < len(num):
if ord(num[i]) != 48 and ord(num[i]) != 49:
print("----------------------------------------... |
c20e24440cbf9126130008a7fecf84f07eed9618 | Randdyy/Myfirst-Codes | /zuoye/001/guess.py | 1,076 | 3.65625 | 4 | import random
print("我在一百内想了一个数,你猜猜看啊")
count=0
ran=random.randint(1, 101)
print(ran)
while(1):
count+=1
user_input=input("please input a number,input q to quit")
try:
if isinstance(int(user_input),int):
if ran < int(user_input) :
print("大了,请重新猜")
... |
3cd313ae5f5436d447edd59f3e86b0b349109ef1 | famaxth/Way-to-Coding | /MCA Exam Preparations/Python/LAB/greaterthan 100 store as over in a list.py | 175 | 4 | 4 | N = int(input("Total numbers : "))
listed=[]
for i in range(N):
num = input("Enter integers")
if int(num)>100:
num="over"
listed.append(num)
print(listed)
|
58340c8c687d2430ce5b6254d42a8011e47ca052 | tatmil-99/digitalcrafts-03-2021 | /week2/day2/classWork.py | 2,410 | 4.5625 | 5 | # 1
# Create a User class, that has the ability to print the users name
# the ability to print the users age
# Create a TempUser class, that has the ability to only print his name.
# Create a function that as you to give the user a name, and give the user an age, and will then create the user for you, and print it to ... |
42b781d8cf9cdddb0fdbd3d70abe502e9c5f243c | qaalib101/SqliteLab | /hello_db.py | 472 | 4.03125 | 4 | import sqlite3
db = sqlite3.connect('my_first_db.db')
db.row_factory = sqlite3.Row
cur = db.cursor()
cur.execute('create table if not exists phones (brand text, version int)')
brand = input('Enter brand of phone')
version = int(input('Enter version of phone (as an integer)'))
cur.execute('insert into phones values ... |
957bb8066849af5c8eddbd946dfdc116ac1fce87 | Jimbiscus/Python_Dump | /Exo10.py | 137 | 3.65625 | 4 | from random import randint
number = randint(1, 6)
if number == 3 or number == 4:
print("BOOM")
else:
print("Rien ne se passe")
|
787ee025dfc80f312770c890c074dedfad764b1e | elhadjmb/fivedd | /app/core/file.py | 523 | 3.53125 | 4 | """
file: file class (if there are files as features or just to store the file)
"""
import os.path
class File:
def __init__(self, path="/"):
self.path = r"{}".format(path) # if Checker.path(path) else Exceptions.flag(type=Dictionary.Internal())
self.file_name = os.path.basename(self.path)
... |
4036fbdb185cfca1e76032fa50733b9bacffa10c | td-dana/data | /dictpt3.py | 860 | 3.640625 | 4 | import json
survey = ["What is your name?", "What is your favorite programming language?"]
keys = ["name", "language"]
list_of_answers = []
done = "No"
while done == "No":
answers = {}
for x in range(len(survey)):
response = input(survey[x]+" ")
answers[keys[x]] = response
... |
25b1479b423c65c29f467d046327580254501dde | jh-lau/leetcode_in_python | /01-数据结构/哈希表/706.设计哈希映射.py | 3,119 | 3.875 | 4 | """
@Author : liujianhan
@Date : 2020/12/24 20:10
@Project : leetcode_in_python
@FileName : 706.设计哈希映射.py
@Description : 不使用任何内建的哈希表库设计一个哈希映射
具体地说,你的设计应该包含以下的功能
put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
remove(key):如果映射中... |
db9b4ac44fac4bce239013b475d05f47ffc1163e | ehizman/Python_Projects | /src/practice/python iterators.py | 1,905 | 4.03125 | 4 | def reverse_string_generator(string):
for i in range(len(string) - 1, -1, -1):
yield string[i]
def all_even(x):
n = 0
while True:
if n <= x:
yield n
n = n + 2
else:
break
def generator():
""" A simple generator"""
n = 1
print("Thi... |
540c27f85f263bdf8f1fa064fe8cd1675754c042 | bestchanges/hello_python | /sessions/2/oleg_baluev/anagrams.py | 2,274 | 4.09375 | 4 | # The algorithm uses a prefix tree data structure. Each node of the tree is array of two values:
# [final_letter, children], where final_letter is a flag telling that there is a word which ends with this node,
# children is a dictionary if child nodes identified by the next character in the word.
# Check if a specifie... |
ad766408b5d3f7bc095c184e36b6856faa6a9f21 | keiti93/Programming101-1 | /week0/Problem-40.py | 267 | 3.9375 | 4 | def char_histogram(string):
histogram = {}
for ch in string:
if ch not in histogram:
histogram[ch] = 1
else:
histogram[ch] += 1
return histogram
print(char_histogram("Python!"))
print(char_histogram("AAAAaaa!!!"))
|
d36418203c08c5dd8a4f91e7aec0dc98d950b975 | cclauss/Ten-lines-or-less | /bit_filpper.py | 444 | 3.546875 | 4 | # https://forum.omz-software.com/topic/2943/trying-to-make-an-encrypted-message-system
# a poor man's encryption
def bit_flipper(s, salt=1):
return "".join([chr(ord(x) ^ salt) for x in s])
salt = 1 # try 1, 6, 7
# for instance, salt = 2 gives you an encrypted string with no printable chars
# (disappearing ink)... |
954208c88ee4518b1d71aa98fd0a40536cf8a481 | Racso1993/EjerciciosCondicionales | /supermercado (1).py | 350 | 3.78125 | 4 | #Ejercicio 2 - Supermercado
precio = int(input("Escribe el valor total de la compra: "))
numeroescogido = int(input("Digita el numero que escogio: "))
if numeroescogido >= 74:
total = precio * 0.20
else:
total = precio * 0.15
print(f"El descuento a favor es: ${total}")
print(f"El total por pagar incluyendo el d... |
c799de4c6e0010fcd34d28631d0e0b6093b4b698 | ChrisMusson/Problem-Solving | /Project Euler/026_Reciprocal_cycles.py | 1,685 | 3.984375 | 4 | '''
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring... |
fd56d025f9736e9194cd3397ca44a7dd9afb622b | lirlia/AtCoder | /aizu-online-judge/ITP1_6_B.py | 404 | 3.546875 | 4 | n = int(input())
cards = []
v = ["S", "H", "C", "D"]
number = list(range(1,14))
for i in v:
for num in number:
cards.append("{} {}".format(i, num))
my_cards = []
if n == 52:
exit(0)
for i in range(n):
my_cards.append(input())
# https://qiita.com/Toitu_Prince/items/222b50594b4bb7b189ee
resul... |
48c50b5b9afad877b867d0cb1a0f044abb639129 | lliradev/Programacion-con-Python | /1. Principios basicos POO/hello.py | 350 | 3.703125 | 4 | songs = ["Red Lights", "Hey Brother", "Don't you worry child", "Gold Skies"]
print(songs)
print(songs[1])
print(len(songs))
songs.append("Congratulations")
print(songs)
songs.sort()
print(songs)
songs.insert(5, "Closer")
print(songs)
songs.append("Complicated")
songs.sort()
print(songs)
s = "Re... |
8015b7dfba6d3fc46191d56e8deef8a3185ea5fa | da-ferreira/uri-online-judge | /uri/2906.py | 467 | 3.578125 | 4 |
quantidade = int(input())
emails = set()
for i in range(quantidade):
email = input()
email = list(email.partition('@'))
primeira_parte = ''
for j in range(len(email[0])):
if email[0][j] != '.' and email[0][j] != '+':
primeira_parte += email[0][j]
else:
... |
81633adb55a7c22aba8fffe6d05d34f8eb9f17e4 | NishadSoney/Class---99 | /removefiles.py | 397 | 3.53125 | 4 | import time
import shutil
import os
path = input("Enter the folder path")
days = 30
days = time.time()
doesExist = os.path.exists(path)
if(doesExist == True):
flcheck = os.path.exists(path)
folwalk = os.walk(path)
crtime = os.stat(path).st_crtime
if(crtime >= days):
os.r... |
8a7f0546ee1706a6aeed8651e46e7b4646cd9615 | niezhenchao/Adb_Bat | /class03/example06.py | 584 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
@Time : 2020/10/19 21:38
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :字典的遍历
"""
height = {'youmi': 166, 'will': 185, 'roy': 180, 'tufei': 170, 'kaka': 185}
# 需把每个人身高都减1
# # 键的遍历
# for key in height.keys():
# height[key] += 1
# print(height[key])
# #... |
b74360aaed9d44d705d74f18f9785b9e62a6a861 | Sophorth/mypython_exercise | /ex4.py | 681 | 3.953125 | 4 | print " ------Start Exercise 4, Variable and Name ------"
print " "
cars = 100
space_in_car = 4.0
drivers = 30
passengers = 90
car_not_driven = cars - drivers
car_driven = drivers
carpool_capacity = car_driven * space_in_car
average_passenger_per_car = passengers / car_driven
print "There are ", cars, " cars availabl... |
dc1f0085bea6d00ca495d994dead22baa93bf46b | lecagnois/pyrobotlab | /home/kwatters/DHParamsIK3D.py | 2,590 | 3.59375 | 4 | ##################################################
# Inverse Kinematics
# This is an example to build up a robot arm
# using (modified?) DH parameters
# then use the InverseKinematics3D service to
# compute the forward and inverse kinematics for
# the arm.
##################################################
fro... |
cc5fc2ea309e09d7c60b46a69753a9675e197a91 | Coobeliues/pp2_py | /midsummer/d.py | 352 | 3.515625 | 4 | for i in range(int(input())):
cnt = 0
s = input().split()
if len(s) % 2 == 0 and s[0].istitle() and s[-1].count('3') == 2:
for j in range(len(s)):
if (j % 2 == 0 and len(s[j]) % 2 != 0) or (j % 2 != 0 and len(s[j]) % 2 == 0):
cnt += 1
print('Wow! That is perfect' if c... |
0688164d99613e2e3f7b0a979dadcc07962615ad | tamycova/Programming-Problems | /Project_Euler/3.py | 712 | 3.53125 | 4 | # # The prime factors of 13195 are 5, 7, 13 and 29.
# # What is the largest prime factor of the number 600851475143 ?
def divisible(num, divisor):
if num % divisor == 0 and num != divisor:
return True
def prime(num):
divisor = 2
while num > divisor:
if divisible(num, divisor):
... |
499179d2284a5945c2593c830f3ddc111f52c7e6 | Mikhail713-xph/exp | /calculator.py | 821 | 4.09375 | 4 | a = float(input('Введите значение №1: '))
b = float(input('Введите значение №2: '))
operation = input('Выберите операцию: +, -, /, *, mod, pow, div: ')
if operation == '+':
print(a + b)
elif operation == '-':
print(a - b)
elif (operation == '/') and (b != 0):
print(a / b)
elif operation == '/' and b == 0... |
29e18a77024091c8ad965a217855de9b1e292699 | aizhansapina/BFDjango | /week1/informatics/While loop/CWe.py | 76 | 3.515625 | 4 | n = int(input())
num = 1
k = 0
while num < n:
num *= 2
k += 1
print(k)
|
a6ec4005fe3c1c871deb5f3206ef3194233413db | idealblack/labs | /utils.py | 10,967 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Some potentially useful functions you can optionally use in your COMP0088
coding assignments.
You are not required to use these functions. If you prefer to write these things
your own way, you are welcome to do so.
"""
import numpy as np
import numpy.random
import matplotlib
import matplo... |
e60e4e6a08507f0343e641deba221bc79cb2944f | himmannshu/Tic-Tac-Toe-AI | /tictactoe.py | 3,657 | 3.890625 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who h... |
cd14b77946e673202f64c7befa6d7e4706e4d5eb | wmentzer/Python-Programs | /userInput.py | 183 | 4.28125 | 4 | # Asks user for input and prints to console
name = input("Please enter your name: ")
print("Your name is: " + name)
print(4 * "name")
print(str(5) + "name")
print(4 * name)
|
316bacbc2f868d9f288c12f32426ad9954b26e16 | ECESeniorDesign/lazy_record | /lazy_record/typecasts.py | 166 | 3.59375 | 4 | """Functions to convert objects to a type"""
def date(datetime):
# may get more complexity later
return datetime
def datetime(datetime):
return datetime
|
5bd43106071a675af17a6051c9de1f0cee0e0aec | abhaj2/Phyton | /cycle-2/3_c.py | 244 | 4.125 | 4 | wordlist=input("Enter your word\n")
vowel=[]
for x in wordlist:
if('a' in x or 'e' in x or 'i' in x or 'o' in x or'u' in x or 'A' in x or 'E' in x or 'I' in x or 'O'in x or"U" in x):
vowel.append(x)
print(vowel)
|
d31440ca53d5c511853301b66e838875974e66eb | arunvijay211/pypro | /numberofdigitsofint.py | 113 | 3.640625 | 4 | count=0
N=input()
print("Input:")
print(N)
while N>0:
N=N/10
count=count+1
print("Output:")
print(count)
|
357ac7d71898d8bbd4d3384d59e60834757505e6 | sodamodo/cs_exercises | /bf_interpreter.py | 2,423 | 4.15625 | 4 |
"""
> increment the data pointer (to point to the next cell to the right).
< decrement the data pointer (to point to the next cell to the left).
+ increment (increase by one) the byte at the data pointer.
- decrement (decrease by one) the byte at the data pointer.
. output the byte at the data pointer.
, accept ... |
b9a82797402387d45a6651895c23810ecda57201 | Gasangit/primeras-pruebas-python | /cualquiera.py | 1,731 | 3.8125 | 4 | archivo = open("abrir archivos.txt" , "r")
####
lista_nom0 = archivo.readline() #se recuperan los datos de la primera línea del archivo
lista_nom0 = lista_nom0.rstrip(",") #se quita la última coma del STRING para poder armar la LISTA
lista_nom0 = lista_nom0.split(",") #se divide el STRING por comas par... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.