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 |
|---|---|---|---|---|---|---|
e0f971ff852be442b84445bddc4058e32e7f340e | HamaguchiKazuki/nlp100 | /chap1/06.py | 1,363 | 3.71875 | 4 | # "paraparaparadise"と"paragraph"に含まれる文字bi-gramの集合を,
# それぞれ, XとYとして求め,XとYの和集合,積集合,差集合を求めよ.
# さらに,'se'というbi-gramがXおよびYに含まれるかどうかを調べよ.
def str2cl(src):
# return [list(w) for w in [''.join([c for c in w if c.isalnum()]) for w in src.split()]]
# 文章を分ける
word_list = []
for word in src.split():
# 単語を整形す... |
21570acb75474207349f9f6afb107f564345f84c | comicxmz001/LeetCode | /Python/136_SingleNumber.py | 555 | 3.640625 | 4 | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Using XOR to find the single number.
#Because every number appears twice, while N^N=0, 0^N=N,
#XOR is cummutative, so the order of elements does not matter.
... |
779c2e05f0e05ea77fca10f01bb326f99848c7cd | Matt-the-Marxist/schoolStuff | /docs/classwork/python/lessons/7.1.8.py | 281 | 3.78125 | 4 | author_name = ("Martin", "Luther", "King, Jr.")
def citeAuthor(authorNameTuple):
result = []
result.append(authorNameTuple[len(authorNameTuple)-1])
for i in range(len(authorNameTuple)-1):
result.append(authorNameTuple[i])
return(tuple(result))
print(citeAuthor(author_name)) |
ae542976955ed6870d8c39a220ce61add09ec324 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2449/60700/283544.py | 706 | 3.59375 | 4 | def search(l: list, s: str):
if s >= l[0]:
return binarySearch(l[0: l.index(max(l))], s)
else:
return binarySearch(l[l.index(min(l)): len(l)-1], s)+l.index(min(l))
def binarySearch(l: list, s: str):
index = -1
lp = 0
rp = len(l)-1
while True:
t = (lp + rp) // 2
... |
88db0fde524dd4304e9753d398fa99a84835c81b | Mudasirrr/Courses- | /MITx-6.00.2x/weighted-graph-problem.py | 3,626 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
@author: salimt
"""
# -*- coding: utf-8 -*-
"""
@author: salimt
"""
class Node(object):
def __init__(self, name):
"""Assumes name is a string"""
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.... |
f902d5e9b15377319406c871c08771579782abc1 | Muhammad5943/Data-Science | /Importing_file/11.HTTPRequeststoImportFilesfromWeb.py | 325 | 3.671875 | 4 | from urllib.request import urlopen, Request
import requests
""" url = "https://www.wikipedia.org/"
request = Request(url)
response = urlopen(request)
html = response.read()
response.close()
# print(html)
print(response)
print(request) """
url = "https://www.wikipedia.org/"
r = requests.get(url)
text = r.text
print(... |
fd5273ff91085b226fbfb637b400fba81e9f080f | EvgeniiGrigorev0/home_work-_for_lesson_2 | /lesson_5/hw_1_lesson5.py | 646 | 4.15625 | 4 | # 1. Создать программно файл в текстовом формате,
# записать в него построчно данные, вводимые
# пользователем. Об окончании ввода данных свидетельствует пустая строка.
my_file = open('первое задание.txt', 'w', encoding="utf-8")
line = input('Введите текст \n:')
while line:
my_file.writelines(line)
line = inp... |
c5b42e41613571b2a9f7a71fa25ff94ecbcad882 | mrhota/cs373 | /examples/FunctionPolymorphism.py | 815 | 3.90625 | 4 | #!/usr/bin/env python
# -----------------------
# FunctionPolymorphism.py
# -----------------------
# parametric run-time polymorphism
class A (object) :
def __init__ (self, n) :
self.n = n
def __lt__ (self, other) :
return self.n < other.n
class B (A) :
pass
def my_max (x, y) :
if... |
e29e11cb05e97bf9f49024d6fcc6facbebfe8cdc | omnidune/ProjectEuler | /Files/problem12.py | 1,001 | 3.84375 | 4 | # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1, 3
# 6: 1, 2, 3, 6... |
6443588692765b3ae8e704ce4aa5c0dfb7b0e061 | wangsanshi123/tutorial | /python_basic/lesson1.py | 1,426 | 3.96875 | 4 | def hello():
print("hello world!")
pass
def genre_test():
"""基本数据类型"""
a = 1
b = "hello"
c = True
d = [1, 2, 3, 4]
e = (1, 2, 3, 4)
f = {"name": "jack", "age": 10}
print("type of a is:", type(a))
print("type of b is:", type(b))
print("type of c is:", type(c))
print(... |
5b2275c4ddd061fee0b422f87ac61f5988e64db2 | park950414/python | /第九章/pySum.py | 224 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 09:06:16 2017
@author: park
"""
import numpy as np
def npSum():
a = np.array([0,1,2,3,4])
b = np.array([9,8,7,6,5])
c = a**2 + b**3
return c
print(npSum())
|
9c349d006dbebc09125d94f97ee554cde773579f | AristidisKantas/HackerRank-Codes | /Counting-Valleys.py | 569 | 3.75 | 4 | def countingValleys(steps, path):
levelArr = [0]*steps
level = 0
isInValley = False
valleyCounter = 0
for i in range(steps):
if path[i] == 'U':
level += 1
elif path[i] == 'D':
level -= 1
levelArr[i] = level
for j in range... |
1ae7d95629dcd2611779348c3e5dc418f0b8c82b | Zylophone/cracking | /is_present.py | 399 | 3.59375 | 4 | class Node:
__init__(self, value):
self.value = value
self.left = None
self.right = None
def isPresent (root, val):
if root is None:
return 0
if root == val:
return 1
eight = new Node(8)
thirty = new Node(30)
ten = new Node(10)
twenty = new Node(20)
eleven = new Node(11)
... |
94d7c6a9a3bfa818028ed34552ddbddbd25fb016 | neelamy/Algorithm | /Graph Theory/Spanning Tree/Prim_Algo_Adj_List.py | 2,311 | 4.1875 | 4 | # Python program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency list representation of the graph
#Complexity : O(V(V+E))
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.V= vertices #No. of vertices
self.graph = def... |
39df42f8dfb68a99210e7ed245bbfbe781b38483 | Esentur/Python_course | /Base/lesson_19.py | 326 | 3.875 | 4 | #отладка
# a=0
# while True:
# a+=0.1
# # print(a)
# if (a>=1):
# exit(0)
# print('Hello')
#exercise
list=[3,5,-2,-8,0]
def findNegativeNum(arr):
negs=[]
for n in arr:
if n<0:
negs.append(n)
return negs
print(findNegativeNum(list))
print('Basic part completed')
|
6ab9604b28ab5a8a17af8c3e32a070dd0ce3d842 | larsnohle/57 | /31/thirtyOne.py~ | 805 | 3.96875 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
... |
94f3f859ba8ebe4c91a5a933fe028a2a81771b2a | sidv/Assignments | /Lekshmi_Pillai_185386/August_18/binary.py | 358 | 3.859375 | 4 | #4.Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are #divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
binary = [1000,1111,1101,1010]
lst= []
for i in binary:
a = int(str(i),2)
if ... |
0d1d7f377969b6f2330d018e3c2e9baef6cfc448 | xzha0006/Leetcode | /Python/0547_FriendCircles.py | 790 | 3.59375 | 4 | class Solution:
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
if not M:
return 0
n = len(M)
id = [i for i in range(n)] #Initial id list. All nodes' parents are themselves.
count = n
def find(node):... |
0d6a863f61cd82830d55f5aed1be43d1660cdfe9 | turamant/mySOLID | /4_Interface_segregation.py | 1,592 | 4.3125 | 4 | ##################################################################################
# Interface Segregation Principle (Принцип разделения интерфейса).
#
#
##################################################################################
class Creature:
def __init__(self, name):
self.name = name
class Sw... |
25ed420d94940060c00a010dbe2689457bca14c0 | ArkaprabhaChakraborty/Datastructres-and-Algorithms | /Python/stackusingqueuemodule.py | 976 | 3.953125 | 4 | #using LifoQueue from queue module
from queue import LifoQueue as lfq
#maxsize – Number of items allowed in the queue.
#empty() – Return True if the queue is empty, False otherwise.
#full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() nev... |
ebdb64aecf14a3c44f2f5526abcffded71f25240 | eltondornelas/curso-python-lom | /secao3_python_intermediario/calculos.py | 567 | 3.859375 | 4 | import math
PI = math.pi
def dobra_lista(lista):
return [x * 2 for x in lista]
def multiplica(lista):
r = 1
for i in lista:
r *= i
return r
if __name__ == '__main__':
# perceba que se não fizer isso e rodar o aplicativo.py, todos esses prints serão mostrados lá também
# então quant... |
9f6b66a6fe7cf8a20c748d34d082759face7821d | kumibrr/2DAM | /Sistemas de Gestión de Empresas/003_Examen/Ejercicio1.py | 302 | 3.5 | 4 | def Ejercicio1():
ingreso = input("Introduzca sus ingresos")
ipi = 0
if ingreso < 85528:
ipi = ingreso * 18 / 100
ipi = ipi + 0.2
elif ingreso > 85528:
ipi = 14839.2
ipi = ipi + (ingreso - 85528 * 32 / 100)
else:
ipi = 0
print(round(ipi)) |
95ea9cb86663b5f9e12f5ac815c6c10e3c049088 | chemxy/MazeRunnerAI | /versions/1.0/src/Player.py | 463 | 3.5625 | 4 | from Object import Object
class Player(Object):
def __init__(self,x ,y):
# character's width and height in pixels
#self.player_size = 50
# iniitial character x-y coordinates in pixels
self.x = x
self.y = y
#print("player initial location: " + str(self.x) + " " +str(... |
a8026a974f1ec48d977f28a92878ce6bdccc7c52 | TopskiyMaks/PythonBasic_Lesson | /lesson_9/task_1.py | 965 | 4.21875 | 4 | print('Задача 1. Календарь')
# Мы продолжаем разрабатывать удобный календарь для смартфона.
# Функцию определения високосного года мы добавили,
# но забыли ещё много разных очевидных вещей.
#
# Напишите программу,
# которая принимает от пользователя день недели в виде строки и выводит его номер на экран.
#
# Пример:... |
634894165cc9b8e7d2a24d0e11ec0c863def7dd7 | mkawserm/PyOp | /src/example_one.py | 1,510 | 4.09375 | 4 | """
* Module : example_one
* Author : Kawser
* Website : http://kawser.org
* Git : https://github.com/mkawserm
*
* Date : 12/04/2014
* Time : 11:18 PM
*
*
* Objective : We shall calculate resistance (R1 and R2) of a voltage divider using Rational class
*
* Input :: V - Source Volt
* V2 - Desired... |
97874269af88d987683e0aeaa1e7f8d39f626864 | backman-git/leetcode | /sol49.py | 710 | 4.09375 | 4 |
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
key points:
1.善用 for k,v in dTlb.items():
2. sorted(“cba”) 回傳['a','b','c']
class Solution(object):
def groupAnagrams(self, strs... |
2a1f7273a5110ab20cc8ccb1a81e53931a877a28 | jstocks/dungeon | /dungeon_adventure.py | 36,321 | 3.78125 | 4 | from adventurer import Adventurer
from dungeon import Dungeon
import webbrowser
"""DungeonAdventure holds the logic of playing the game. Re/starts game, creates
adventurer and dungeon through respective classes, controls user input/options &
movement, and logic for winning/losing game"""
"""Hidden menu it... |
24bc0c8cf9cca3c13724d0ca33d2f18951af3f56 | Mariia-Kosorotykova/python-education | /python_HW1/calculator/calc.py | 928 | 4.3125 | 4 | """This module works as a simple calculator."""
class Calculator:
"""This class performs 4 simple operations on numbers."""
@staticmethod
def addition(first_number, second_number):
"""This function takes 2 arguments and returns their sum"""
return first_number + second_number
@static... |
c7ee997189ad5dd9b43f2eec0a0670f978c5f6e4 | EricWord/PythonStudy | /10-dict/dict_demo5.py | 264 | 4.375 | 4 | # 字典推导式
dict1 = {"a": 100, "b": 200, "c": 300}
dict2 = {}
for k, v in dict1.items():
dict2[v] = k
print(dict2) # {100: 'a', 200: 'b', 300: 'c'}
# 字典推导式
dict3 = {v: k for k, v in dict1.items()}
print(dict3) # {100: 'a', 200: 'b', 300: 'c'}
|
f11524d94e0dd5412f0fe8c1b49485e7a793a773 | prachi-bindu/Leetcode | /BinArraySorting.py | 632 | 3.90625 | 4 | class BinArraySorting:
def __init__(self):
self.arr = []
def showArray(self):
print(self.arr)
def fillArray(self):
n = int( input("Enter the size of the array-") )
print("Enter the elements in the array-")
for i in range(n):
el... |
e449cf2818caa792dc8172e54b966abc4d57962a | pianowow/projecteuler | /138/138.py | 1,636 | 3.671875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: CHRISTOPHER_IRWIN
#
# Created: 28/11/2012
from math import sqrt
from time import clock
clock()
BHLs = []
halfb = 1.5
max = 2000000000
squares = set()
##for x in range(m... |
f437c155abe33882321282af57961b88241f19d2 | preston-scibek/Python | /calculate_pi.py | 375 | 3.6875 | 4 | from __future__ import division
from decimal import Decimal
def calculate_pi(n=1000):
""" calculate pi to n places
negative = False
pi = 0
for i in range(0, n):
if negative:
pi -= 4/(2*i + 1)
negative = False
else:
pi += 4/(2*i + 1)
negat... |
e945332f179b2d16530a652651b102e6395c1755 | predatory123/byhytest | /python_practice/python0603/test.py | 1,052 | 3.9375 | 4 | with open('cats.txt', 'a') as file_object:
print ('If you want to quit , please entert "q".')
while True:
cats_name = input('Please enter your cat\'s name:')
if cats_name == 'q':
break
file_object.write(cats_name + '\n')
with open('dogs.txt', 'a') as file_object:
print (... |
52f647b3f234618345407beab2301d006f53b2a3 | behrom/wprowadzenie_do_jezyka_pythona | /laboratorium/Przygotowanie do koła/generatory_iteratory_wyjatki/zad3.py | 221 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def fib_gen():
x, y = 1, 1
while True:
x, y = y, x + y
yield x
fib = fib_gen()
summ = 0
for _ in xrange(30 + 1):
summ += fib.next()
print summ |
90a6f8adc2e33ff423366198e378d600de628c8e | martinazaki/Uni-Work | /COMP1531/20T1-cs1531-lab05/encapsulate.py | 402 | 3.859375 | 4 |
import datetime
class Student:
def __init__(self, firstName, lastName, birthYear):
self.name = firstName + " " + lastName
self.birthYear = birthYear
def name(self):
return self.name
def age(self):
return datetime.datetime.now().year - self.birthYear
if __name__ == '__main__':
... |
909c637bf2f4d7b70329526febebf36d50abd841 | jaehui327/PythonProgramming | /Lab0320/Lab03_TurtleGraphic.py | 329 | 4.03125 | 4 | import turtle
t = turtle.Pen()
while True:
direction = input("왼쪽은 left, 오른쪽은 right, 멈추려면 stop을 입력하세요: ")
if direction == "left":
t.left(60)
t.forward(50)
elif direction == "right":
t.right(60)
t.forward(50)
elif direction == "stop":
break
|
a2cb187ec0bb6490006bd8eea196dbb55b4a71e2 | vicb1/python-reference | /code/spark/python-spark-tutorial-master/sparkSql/StackOverFlowSurvey.py | 2,185 | 3.703125 | 4 | from pyspark.sql import SparkSession
AGE_MIDPOINT = "age_midpoint"
SALARY_MIDPOINT = "salary_midpoint"
SALARY_MIDPOINT_BUCKET = "salary_midpoint_bucket"
if __name__ == "__main__":
session = SparkSession.builder.appName("StackOverFlowSurvey").getOrCreate()
dataFrameReader = session.read
responses = data... |
893a9268161d88603f63ca9a6f7393b319bbc055 | bobmwaniki/Andela_BootCamp_Labs | /Week_1/Day_2/http_and_web_lab.py | 1,265 | 4.375 | 4 | import requests
import json
# This short program is a simple command line python application that takes the name of a city and prints out the current weather of the city
# It uses an API from http://openweathermap.org/
api_key = '92f135e73e13bdd8f59b57347820f8af'
def get_weather(city):
r = requests.get('http://api.... |
326287c1f68cb6f394e0b053f7053a14b0a52e04 | BabitaAnandKrishna/SumArray | /Mini_Project.py | 373 | 3.703125 | 4 | PRICE = 200
discount_10 = ['STUDENT10','SPRING10','MEMBER123']
buyer_code = input("Please type your discount code: ")
print('processing....\n')
if buyer_code in discount_10:
final_price = PRICE * 0.9
print("10% discount applied \n")
else:
final_price = PRICE
print("No discount applied \n")
print("... |
e6556ab4f636904a0e19c578791001dd9e5aaa4a | rzolotarev/Graphs | /Graph/adjacencyMatrixGraph.py | 1,545 | 3.546875 | 4 | import numpy as np
from .abstract import Graph
class AdjacencyMatrixGraph(Graph):
def __init__(self, numVertices, directed=False):
super(AdjacencyMatrixGraph, self).__init__(numVertices, directed)
self.matrix = np.zeros((numVertices, numVertices))
def add_edge(self, v1, v2, weight = 1):
... |
3c3d9f1da15f6ac04cbe07a7431e9c35479af91e | ShishirNanoty/Homework9 | /HW9.py | 1,824 | 3.71875 | 4 | class Vehicle():
def __init__(self,make = 'NA',model = 'NA',year = 1900,weight =0, maint = False,trips = 0):
self.make = make
self.model = model
self.year = year
self.weight = weight
self.maint = maint
self.trips = trips
def setMake(self, make):
... |
6244198908f10747599c4894761768753922010e | the-brainiac/twoc-problems | /day6/program_3.py | 256 | 3.5625 | 4 | l = list(map(int,input('Enter elements of list: ').split()))
print('List is : ',l)
l.sort()
print(l)
l1=[]
for i in range(len(l)):
if l[i]>0:
l1=l[i:]
break
print(l1)
for i in range(len(l1)):
if l1[i]!=i+1:
print('missing number is :',i+1)
break
|
ca983200c69927a9548932dd9aa7b16d1a3ede9e | DesireeMcElroy/time-series-exercises | /prepare.py | 1,955 | 3.640625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import acquire
import requests
import os
from datetime import timedelta, datetime
def prep_items(df):
'''
This function takes in dataframe and drops unnecessary columns, adds a month, weekday and sales_total column
'''
# drop ext... |
89d6f31d2aa048f900e56f8a1c17c45f1d9ea403 | smitches/Python | /CS 303/DNA.py | 1,388 | 3.75 | 4 | # File: DNA.py
# Description: This program finds longest similar strand
# Student Name: Brian Smith-Eitches
# Student UT EID: bts867
# Course Name: CS 303E
# Unique Number: 51195
# Date Created: October 26, 2016
# Date Last Modified: October 26, 2016
def main():
in_file=open("./dna.txt","r")
... |
8f7cb00da84973464271784ab92c370afc2fcc3b | phongluudn1997/leet_code | /three_number_sum.py | 793 | 3.875 | 4 | def usingTwoPointer(array, target):
sorted_array = sorted(array)
result = list()
for index in range(0, len(sorted_array) - 2):
current_number = sorted_array[index]
left = index + 1
right = len(sorted_array) - 1
while left < right:
current_sum = current_number + so... |
e5a09ab05f465a7c2f28a81eb7085729f4479de7 | DeanHe/Practice | /LeetCodePython/StoneGameII.py | 1,766 | 3.75 | 4 | """
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first. Initially, M = 1.
On each player... |
b1bfe69687432cb7e9a0cf91a6a74057e5c8cb20 | JunyoungJang/Python | /Introduction/01_Introduction_python/07 Data container type/1 Data container type - List/9 List methods/append, insert, remove.py | 164 | 3.625 | 4 | x = [2, 3]
x.append(4)
print x # [2, 3, 4]
x.insert(2, 'Wow')
print x # [2, 3, 'Wow', 4]
x.remove('Wow')
print x # [2, 3, 4]
|
42ffbdd7004ec2295fd34d7198e88f0b1f741d8e | Zohu0/Python-Codes-For-Beginners | /Sum of its preevious digit.py.py | 147 | 4.09375 | 4 | num= int(input("Enter Any Number: "))
add= 0
for i in range(0, num+1):
add= add+i
print(f"The Sum Of Previous Numbers Of {num} is {add}") |
060f1649a97fa59e835904ebe93198aa64348c18 | simiss98/PythonCourse | /UNIT_1/Module3.2/Required_Code_MOD3_IntroPy.py | 854 | 4 | 4 | # [ ] create, call and test
# then PASTE THIS CODE into edX
def order_price(weight):
# set values for maximum and minimum order variables
maximum = 1000.000
minimum = 0.100
# set value for price variable
price = 7.99
# check order_amount and give message checking against over maximum under minim... |
e2bf022866960850ddd933b60f7cbadcf5a234fe | mo7amed115/Titanic | /Titanic.py | 5,903 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
conda --version
# ### Overview
# The data has been split into two groups:
# * training set (train.csv)
# * test set (test.csv)
# The training is set used to build The machine learning models.
#
# The test set is used to see how well The model performs on unseen data... |
69f42481a13f1168453670063c73d595d11fefa3 | KeleiAzz/Project-Euler | /4.Largest palindrome product.py | 377 | 3.578125 | 4 | def ispalindrome(x):
digit=[]
t = 1
while t<x:
digit.append(x/t%10)
t*=10
temp=digit[::-1]
#print digit
#print temp
if temp == digit:
return True
else:
return False
result=[]
for i in range(100,1000,1):
for j in range(100,1000,1):
if ispal... |
7fbf954d989e1b67e7ea8730ae76f09f578ec3a4 | wangyijie11/pypractice | /base/数据类型-字典2.py | 239 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
dic = {"num": "1001", "account": "wangyj", "username": "小何", "age": "20"}
dic["age"] = 22
print(dic)
del dic["age"]
print(dic)
dic["sex"] = "male"
print(dic)
len(dic)
str(dic)
type(dic) |
d6350124e2f8417990b3db7add58ff87a76ab10e | espresso6615/myPy | /qe.py | 582 | 3.78125 | 4 | import math
a = float(input("a?"))
b = float(input("b?"))
c = float(input("c?"))
while a==0:
print("2차방정식이 아닙니다!!!")
a = float(input("a?"))
b = float(input("b?"))
c = float(input("c?"))
if a!=0:
print("2차방정식이 맞습니다^^")
D = b*b-4*a*c
if D > 0:
x1 = -b+math.sqrt(D)/2*... |
fcbc41299a56e8c91fcc0148399fe63c1df12bb7 | dobby-dobster/random-log-line-printer | /main.py | 523 | 3.546875 | 4 | #!/usr/bin/env python
import random
def GenerateRandomNumbers():
RandomNumbers = [n for n in random.sample(range(1, 11), 5)]
print("Random line numbers: {}").format(RandomNumbers)
return RandomNumbers
def main():
RandomNumbers = GenerateRandomNumbers()
count = 0
for line in open("log.txt"):
... |
9f60d3d310f4955763cf150a8e840053857c7c65 | vickiedge/cp1404practicals | /prac_01/electricity_bill_estimator.py | 285 | 3.96875 | 4 |
cents_per_kWh = int(input("Enter cents per kWh: "))
daily_use = float(input("Enter daily use in kWh: "))
billing_days = int(input("Enter number of billing days: "))
estimated_bill = cents_per_kWh / 100 * daily_use * billing_days
print("Estimated bill: ${:.2f}".format(estimated_bill)) |
67c784919e77d5990f0124e4c68c5b1d2975a593 | Santhosh-23mj/Simply-Python | /EXIF Extract/02_DwnldImage.py | 601 | 3.578125 | 4 | #!/usr/bin/python3
"""
A EXIF data extracter from images in a website
Module 2 - Download all images and store to a file
"""
import urllib
from os.path import basename
def downloadImage(imgTags):
try:
print("[+] Downloading Image......")
imgSrc = imgTags['src']
imgReq = urllib.r... |
1517e1f8d01f6b79b812bc93ef8df385f6d5466b | iopkelvin/Leetcode-problems | /frequencySort.py | 399 | 4 | 4 | def frequencySort(nums):
record_dict = {}
for i in nums:
if i not in record_dict:
record_dict[i] = 1
else:
record_dict[i] += 1
print('dict ', record_dict)
print('nums ', nums)
print('sort ', sorted(nums, key=lambda x: (record_dict[x], -x)))
return
if __... |
a240b0974995afc3d2266022e035cdf2ce8c4c88 | pdezonia/space-game | /code/enemy_ai.py | 712 | 3.78125 | 4 | """
|<-------------------------------------------------------------------------->|
|<------------------------------------------------------------------->|
enemy_ai.py is a class definition for the computer controller of
enemy ships. It takes the its own pose and velocity and the postion of
the player, civilian ships, a... |
201b569e282db399f18e1564e984f137c9361af1 | OwenPriceSkelly/ProjectEuler | /p9_pythagoreanTriples.py | 502 | 4.1875 | 4 | #!/usr/bin/env python3
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
# i.e. find a triple that sums to n, and return the product
def pythagoreanTriple(n):
triples = []
# generate pythagorean triples:
for c in range(n):
for b in range(c):
... |
522a6c548c9fd679ae6a8f0c2591023895bb4c5c | RipeFruit08/orienteering | /orienteering.py | 13,503 | 3.546875 | 4 | from PIL import Image
import Terrain
import State
import heapq
import time
import sys
import Pixel
pix = None
elevations = []
"""
Generates successors for a given state.
In this situation, a state represents a cell on the map and therefore will have at most
8 different successors. This function calls MakeSuccessor wh... |
690d9f99a2ec2fbd896cce76ffb23e7385071634 | matt23177/Simple-Python-Game | /game.py | 709 | 3.828125 | 4 | import random
def start():
print('Hello! The objective of the game is to collect money')
a = input("Do you want to play?")
if a.lower() in ('y', 'yes'): #If user inputs one of the following, game starts with 0 money.
Game(0)
def Game(money):
number = random.randint(1,51) #generate a random number
pic... |
d53fe0c76a81aaeea46a5a7d62437546adcea2aa | ArBond/ITStep | /Python/lessons/lesson10_function/main5.py | 940 | 4.59375 | 5 | # 5. Напишите функцию capitalize(), которая принимает слово из маленьких латинских букв
# и возвращает его же, меняя первую букву на большую. Например, print(capitalize('word')) должно печатать слово Word.
# На вход подаётся строка, состоящая из слов, разделённых одним пробелом. Слова состоят из маленьких латинских б... |
29efaa4cb0c7adbd42c7c7a258b46114f10faa6e | lloyd108/python_start | /09-Coroutine/myIter.py | 603 | 3.921875 | 4 | from collections import Iterable, Iterator
l1 = [i for i in range(10)]
print(isinstance(l1, Iterator))
print(isinstance(l1, Iterable))
s1 = "This a simple string."
print(isinstance(s1, Iterator))
print(isinstance(s1, Iterable))
s1_iter = iter(s1)
print(isinstance(s1_iter, Iterator))
print(isinstance(s1_iter, Itera... |
6bdb955d481d3363c175b9c490ec40c0b09890d6 | cuberisu/College | /2021-1/4.py | 473 | 3.703125 | 4 | #casting
print("안녕" + "잘 지내니")
# print("너 혹시 몇 살이니?" + 19 + "살이야") # 형식에러: 문자형만 문자형에 연결 가능.
#"문자열과 숫자형은 연결할 수 없다."
print("너 혹시 몇 살이니?"+ str(19) + "살이야") # 숫자형 19를 문자형으로 변환
x = 19 # 숫자형
y = "19" # 문자형
print(str(x) + y) # x를 문자형으로 변환 (캐스팅)
print(x + int(y)) # y를 숫자형으로 변환 |
03f8adb98b68d7dc9119f11281b93f8af806bc6a | camillevidalpy/algorithmie-data | /tp/TP3_COLLECTIONS_correction.py | 5,207 | 4.09375 | 4 | """
Structures de données Listes, Tuples et dictionnaires
"""
"""
Exercice 1
"""
t = [1, 2, 3, 4, 5]
a = t[0] + t[3] # 1 + 4 ==> 5
b = t[-1]
c = t[3:]
a = a + t[-2]
print(type(t)) # t est une liste
# Afficher les valeurs de a, b et c:
print(a)
print(b)
print(c)
# Soit `i` un entier quelconque: t[-i] renvoie les ... |
37acf7b7bcf8fea745a7c1fc8dd6ec8c782d68f4 | frnkvsk/python100days | /day22_pong/draw_number.py | 8,056 | 3.640625 | 4 | from turtle import Turtle
class DrawScore:
def __init__(self, num, x, y):
self.segments = [[] for _ in range(5)]
self.create_segments(x, y)
self.draw_number(num)
def create_segments(self, x, y):
for i in range(0, 5):
for j in range(0, 3):
... |
b7a6532244f11867a266a56fba683a190cd841d2 | jemtca/CodingBat | /Python/String-1/make_abba.py | 232 | 4.03125 | 4 |
# given two strings, a and b, return the result of putting them together in the order abba
def make_abba(a, b):
return a + b + b + a
print(make_abba('Hi', 'Bye'))
print(make_abba('Yo', 'Alice'))
print(make_abba('What', 'Up'))
|
f4913d81f2eced840f9ac8402fc0d450cb66451b | cgoeke/python-crash-course | /exercises/chapter-10/programming_poll.py | 471 | 4.34375 | 4 | # 10-5. Programming Poll: Write a while loop that asks people why they like
# programming. Each time someone enters a reason, add their reason to a file
# that stores all the responses.
filename = 'programming_poll.txt'
while True:
print("\nEnter 'q' to exit the program.")
reason = input("Why do you like progr... |
94fd5b32d4186917f525f24f55db37e3390f7e92 | TheLunchtimeAttack/matasano-challenges | /python/matasano/set1/c2.py | 950 | 3.75 | 4 | from matasano.util.converters import *
from matasano.util.byte_xor import xor
def hex_string_xor(hex1string, hex2string):
"""
A complete function for reading in two hex strings and outputting a string of the xor of the two inputs
:param hex1_string: a string of ASCII encoded hex characters
:param... |
76b2c73047d70c101b74139d2410078c4ef3b0e6 | Richarjw/Rose-Hulman-CSSE120 | /Tkinter_ttk/src/m99.py | 857 | 3.78125 | 4 | """
Try out Tkinter and ttk!
"""
import rosegraphics as rg
import tkinter
from tkinter import ttk
def main():
# Make a window.
# Put a Frame on it.
# Put a Button on the frame.
# Make your Button do something simple.
# Add a Label and an Entry.
# Make your Button do something with the Label an... |
f4acbb13817bb6f1c1f98881894fe5b10aeb7e56 | minhnhoang/hoangngocminh-fundamental-c4e23 | /session2/homework2/serious_exc1.py | 384 | 4.15625 | 4 | height = int(input("Your heith (cm): "))
m = int(input("Your weight (kg): "))
h = height/100
bmi = round(m / (h*h),1)
print("Your BMI:", bmi)
if bmi < 16:
print("You are severely underweight!")
elif bmi < 18.5:
print("You are underweight!")
elif bmi < 25:
print("You are of normal weight!")
elif bmi < 30:
... |
03a61844f6dce5cc05d3a8132436288bc6375519 | wertqyuio/leetcode-problems | /1374_generate_string_with_odd_counts.py | 1,227 | 3.765625 | 4 | class Solution:
def generateTheString(self, n: int) -> str:
# note there are a few cases
# first case is when n == 1
# second case is when n is divisible by 2
# third case is when n is not divisible by 2
# there is easy solution where there's odd or even
# also learne... |
e41abfb54dd192eb8e6850aba9a8cac7ef69b921 | Boombarm/onlinejudge | /Python/src/uri_beecrowd/ADHOC/P3408_Ignore_the_Letters.py | 170 | 3.75 | 4 | import re
n = int(input())
answer = 0
for i in range(n):
text = input()
nums_arr = re.findall("[0-9]+", text)
num = int("".join(nums_arr))
answer += num
print(answer) |
f1730811a404b9b297d7e9df28884eb8124f6a21 | chix08/Code | /countingsort.py | 495 | 3.671875 | 4 | '''
k = Range
n = length
arr = array
'''
arr = [9,8,7,6,5,4,3,2,1,0]
def sortarray(acount, actualarr, n):
a = [0 for i in range(n)]
for i in actualarr:
a[acount[i] - 1] = i
acount[i] -= 1
return a
def countnum(k, arr):
a = [0 for i in range(k)]
for i in arr:
a[i] = a[i]... |
07f98d8fbaa787454ef49e996fe16725e02ace45 | Rahul4269/Django | /Django Day3.py | 276 | 4.09375 | 4 | '''s="this is python"
for x in iter(s):
print(x)
s = "this is python"
itr=iter(s)
print(next(itr))
print(next(itr))'''
s="this is python"
for x in iter(s):
print(x)
s = "this is python"
itr=iter(s)
for i in range (0,len(s)):
print(next(itr))
|
97a32b150f4a8c39a393e8e0014b8ca7f4178c8e | lewis-munyi/MSOMA-Boot-camp | /exponentials.py | 385 | 4.03125 | 4 | key = 0
while key == 0:
choice = int(input("1. Proceed\n2. Exit\n"))
if choice == 1:
base = input("Enter the base:\n")
exponent = input("Enter the exponent:\n")
output = int(base) ** int(exponent)
print(str(base) + " to the power of " + str(exponent) + " is " + str(output) + "\n\... |
595f927878c79c94ca67f5c12aea0ae914948786 | ShirleyMwombe/Training2 | /higher order functions.py | 1,248 | 4.3125 | 4 | # Higher Order Function = a function that either:
# 1. accepts a function as an argument
# or
# 2. returns a function
# (In python, functions are also treated as objects)
def loud(text):
return text... |
29789cbecc3d5f4ed6f2fbd576a8d4182cf89fb3 | underseatravel/AlgorithmQIUZHAO | /Week_06/557_reverse_words_in_a_string3.py | 239 | 4 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/22 10:54
# @Author : weiyu
# @File : 557_reverse_words_in_a_string3.py
class Solution:
def reverseWords(self, s):
return " ".join(c[::-1] for c in s.split())
|
f169abf6d2d27314309212942368889b20a54a25 | tzpBingo/github-trending | /codespace/python/tmp/piecewise.py | 292 | 3.953125 | 4 | """
分段函数求值
3x - 5 (x > 1)
f(x) = x + 2 (-1 <= x <= 1)
5x + 3 (x < -1)
Version: 0.1
Author: 骆昊
Date: 2018-02-28
"""
x = float(input('x = '))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x + 3
print('f(%.2f) = %.2f' % (x, y))
|
f87f6a605e6c2ae6dc83035abdce201272733b2b | tdnzr/project-euler | /Euler145.py | 1,147 | 4.125 | 4 | # Solution to Project Euler problem 145.
# The following solution works, but it's glacially slow.
# It got the correct result after ~1250s on my machine.
def all_digits_odd(n):
"""Returns True if n contains only odd digits, False otherwise."""
# Because we have to turn n into a string to loop over it,
# ... |
8eca0f4c31bd309ac87bf7217baccd322373eb37 | dvardoo/randdict4 | /randdict4.py | 1,241 | 3.71875 | 4 | import random
import string
# -*- coding: utf-8 -*-
#Function for getting a random passphrase
#Choses 4 random words from wordlist and concatenates as passphrase.
def passwd():
with open('/usr/share/dict/american-english', 'r') as allWords:
wordList = allWords.read()
wordList = wordList.split()
... |
b75e0de3aafbebffbfd21b3ddaa53ad467eaf885 | ymzkd/LearningFlask | /Response/kakezan.py | 930 | 3.734375 | 4 | from flask import Flask, request
# Flaskオブジェクトの生成
app = Flask(__name__)
# ルート( / )へアクセスがあった時 --- (*1)
@app.route("/", methods=["GET", "POST"])
def root():
if request.method == "GET":
return """
<html><body>
<form action="/" method="POST">
<input type="text" name="a"> ×
<inp... |
396dd6af844be9e77e766d909fb121c96c3fef87 | lucasjct/python_curso_em_video | /Mundo_2/if_elif/ex42.py | 576 | 4.125 | 4 | l1 = int(input('Digite um número: '))
l2 = int(input('Digite outro número: '))
l3 = int(input('Digite só mais um número: '))
if l1+l2 >= l3 and l2+l3 >= l1 and l3+l1 >= l2:
print('Estas três medidas formam um triângulo ', end='')
if l1 == l2 == l3:
print('EQUILÁTERO (todos os lados iguais).')
elif ... |
66f5c870c701539f707199ae62e9174946ed66f7 | pratikbubne/Python | /logicalPython.py | 3,296 | 3.75 | 4 | # name = "A2D3"
# #AADDD
# newString = ""
# for item in name:
# if item.isalpha():
# x = item #x = D
# else:
# newString = newString + int(item) * x
# print(newString)
# name = "4D3C"
# #DDDDCCC
# blank = " "
# for char in name:
# if char.isnumeric():
# x = int(char)
# else:
#... |
c15d3dfe2f878d9b8e4d7d738f469f529e71f761 | alirezamzh/number-game-app | /numberGameapp.py | 1,332 | 3.890625 | 4 | # limit the number of guesses
# catch when someone submit a non-integer value
# print "too high" or "too low" messages for bad guesses
# let peaple play again
# generate a random number between 1 to 10
import random
secret_number = random.randint(1, 10)
# get a number guess from the player
def run_gmae():
guesse... |
f1c54f234b47b962339c32273c451e44445008aa | ANKITPODDER2000/LinkedList | /21_merge_list.py | 736 | 4.25 | 4 | from LinkedList import LinkedList
from LinkedListHelper import CreateLinkedList
def merge(head1 , head2):
l1 = LinkedList()
while head1 or head2:
if not head1:
l1.insert_end(head2.val)
head2 = head2.next
elif not head2:
l1.insert_end(head1.val)
hea... |
44d7bfe2918ba5cbd2657b9ef00812c7c098baa2 | confi-surya/pythonicPracto | /GeeksforGeeks/divideAndConquor/calculatePower.py | 388 | 3.65625 | 4 | def powern_in_orderof_n(x,y):
if y==0:
return 1
elif (y%2==0):
return powern_in_orderof_n(x,y/2)*powern_in_orderof_n(x,y/2)
else:
return x*powern_in_orderof_n(x,y/2)*powern_in_orderof_n(x,y/2)
def power_in_orderof_logn(x,y):
if y==0:
return 1
temp=power_in_orderof_logn(x,y/2)
if (y%2==0):
return temp*t... |
29aee72d39417900fbaf697f5cba134673027e01 | afsanehshu/tamrin | /practice 5/key/1.py | 122 | 3.65625 | 4 | import datetime
time = datetime.datetime.today().minute
if (time%7)%2 == 0:
print("Even")
else:
print("odd")
|
76f128a9aeb0da9a2889e732dbdf34881fc50581 | xiaosean/leetcode_python | /Q88_Merge-Sorted-Array.py | 634 | 3.75 | 4 | class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
if n == 0:
return
offset1, offset2 = m-1, n-1
while offset1 >= 0 and offset2 >= 0:
num1,... |
3902fb27bba0c2270a9cfc51e53a670254109057 | TanyaKHughes/BasicPythonPractice | /exception.py | 323 | 4.03125 | 4 | # exception.py - just some basic exception practice
n = int(input("Enter a number and I'll divide 100 by your number: "))
try:
dividend = 100/n
except ZeroDivisionError:
print("I can't divide by zero!")
else:
print(f"I did it! The answer is {dividend:.2f}, or {dividend:.1%}")
print(f"Your number was: {n}... |
74b11461ee87d679bf5abc41d2577473132a1e6e | yiyueya/random-time | /My_random.py | 1,258 | 3.796875 | 4 | import time
import matplotlib.pyplot as plt
import random as R
# ---------------------------------------------------------------------
# 获取当前时间(秒)小数点后第n个数字作为随机数,默认范围为0~9,可通过w改变
def get_random_time(n = 3):
while True:
now = time.time() * (10**(n-1))
diff = int((now - int(now)) * 10)
return... |
1fe9a1a32bde8d5baf249c6a949eecda0422841b | Sigrud/lesson1 | /vat.py | 589 | 3.859375 | 4 | price=100
vat_rate=18
vat=price/100*vat_rate
print(vat)
price_not_vat=price-vat
print(price_not_vat)
def get_vat(price,vat_rate):
vat=price/100*vat_rate
price_not_vat=price-vat
print(price_not_vat)
price1=100
vat_rate1=18
get_vat(price1,vat_rate1)
price2=500
vat_rate2=10
get_vat(price2,vat_rate2)
get_vat(50,int... |
4962112c971ca2037c131b26c37302edd5f2915a | matteocodogno/python_course | /tkinter/script1.py | 871 | 3.890625 | 4 | from tkinter import *
from tkinter.font import names
def convert():
kilos = float(kg_value.get())
grams = kilos * 1000
pounds = kilos * 2.20462
ounces = kilos * 35.274
grams_txt.insert(END, grams)
pounds_txt.insert(END, pounds)
ounces_txt.insert(END, ounces)
window = Tk(baseName='Grams P... |
bc88183d5632e1e6260e4246490272e2b63cdbff | chris6037/guvitask | /looptillQ.PY | 150 | 3.96875 | 4 | a=str(input("enter the file:"))
while (1):
if(a!="q"):
print("invalid file")
else:
print("valid file")
|
16437c1956d2527406bd376ba53e59dedf4a71df | samuelrothen/advent_of_code_2020 | /src/aoc_day06.py | 833 | 3.578125 | 4 | # Advent of Code Day 6
def count_anyones_yes(answers_all):
n_yes = 0
for answers_group in answers_all:
answers_group = answers_group.replace('\n', '')
n_yes += len(set(answers_group))
return n_yes
def count_everyones_yes(answers_all):
n_yes = 0
for answers_group in answers_all:
... |
ff13c555276bfd2b04ea0f31e3fe026ea051c6a8 | PlabonKumarsaha/Python_Open_CV_Practice | /RGB2GraySCALE.py | 382 | 3.546875 | 4 | # package for opencv
import cv2
# read image from path
# stored the image in 'img'
img = cv2.imread("Resrouces/ironman.jpg")
# Convert to grayScale image
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# first parameter is window name..second is the image name
cv2.imshow("Gray Image", imgGray)
# must adda ... |
789643484a71602d2389e8f557bbbc54e704de34 | antomin/GB_Algorithms | /lesson_1/task_1_5.py | 794 | 4.375 | 4 | """
Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.
"""
x, y = input('Введите две буквы.\nОт: '), input('До: ')
if 65 <= ord(x.upper()) <= 90 and 65 <= ord(y.upper()) <= 90:
print(f'{x.upper()} - {ord(x.upper()) - 64}-я буква алфавита.')
prin... |
97cfc2468e699bf8bf9e5358fd652912601cc80e | jbial/daily-coding | /dailycoding038.py | 1,727 | 3.875 | 4 | """
This problem was asked by Microsoft.
You have an N by N board. Write a function that, given N,
returns the number of possible arrangements of the board
where N queens can be placed on the board without threatening each
other, i.e. no two queens share the same row, column, or diagonal.
solution: https://dailycodin... |
f9f1c89271c969c9f1be83d7712a79eadb7aad9d | HumgTop/DataStructure-Algorithm | /LeetcodeForPython/leetcode/editor/cn/[剑指 Offer 59 - I]滑动窗口的最大值.py | 2,467 | 3.6875 | 4 | from typing import *
from queue import Queue
import collections
import itertools
# 给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
#
# 示例:
#
# 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
# 输出: [3,3,5,5,6,7]
# 解释:
#
# 滑动窗口的位置 最大值
# --------------- -----
# [1 3 -1] -3 5 3 6 7 3
# ... |
2f050dc9beece895a63a8baa6199f6901cd24b70 | bernease/A2DD13-hrwc | /hrws_survey.py | 3,515 | 3.625 | 4 | #! /usr/bin/env python
# Import python modules that will do useful stuff for us
import collections, csv
# code written for use by/for the Huron Valley Watershed Council (A2 DataDive 2013)
# Looks at the species table in the database, and outputs a file describing whether or not a given species is at a given site
# (v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.