blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
714924c482de8f664305ee5dea26cf62a231bcd0 | ErdemOzgen/leetcode | /python/252-Meeting-Rooms.py | 416 | 3.5625 | 4 | class Solution:
"""
@param intervals: an array of meeting time intervals
@return: if a person could attend all meetings
"""
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda i: i[0])
for i in range(1, len(intervals)):
i1 = intervals[i - 1]
i2... |
24e85fbd12f4cdd2d89d404677ae0fa4c11a7498 | EyJajb/tutorial_site | /family.py | 2,102 | 4.09375 | 4 | # code here
from typing import Any
import json
# some dictionaries
p1 = { "name":"Father (Angelo)", "occupation":"Computer Engineer", "residence":"San Diego", "color":"orange"}
p2 = { "name":"Mother (Simona)", "occupation":"Stay at home mom", "residence":"San Diego", "color":"pink"}
p3 = { "name":"Me (Luca)", "occupa... |
96dc855725503ac12dfcde74cfbb2e79b472b7dd | tdrv90/softuni-courses | /06. Python Essentials/04. For Loops/06. Vowels Sum.py | 351 | 3.84375 | 4 | string = str(input())
string = string.lower()
sum_of_vowels = 0
for char in string:
if char == 'a':
sum_of_vowels += 1
elif char == 'e':
sum_of_vowels += 2
elif char == 'i':
sum_of_vowels += 3
elif char == 'o':
sum_of_vowels += 4
elif char == 'u':
sum_of_vow... |
5a7a1afa8b7a25d2222913ae48d2ed8584995791 | tdrv90/softuni-courses | /06. Python Essentials/08. Multidimensional Lists/01. Sum Matrix Elements.py | 412 | 3.6875 | 4 | def read_matrix():
(rows_count, _) = map(int, input().split(', '))
return [list(map(int, input().split(', '))) for _ in range(rows_count)]
def sum_matrix(matrix):
sum_of_matrix = 0
for row in range(len(matrix)):
for col in range(len(matrix[row])):
sum_of_matrix += matrix[row][col]... |
edfd564ce3714e139102de5dcb6653ccde3857f9 | tdrv90/softuni-courses | /06. Python Essentials/05. Lists Basics/03. Lists Statistics.py | 311 | 3.84375 | 4 | n = int(input())
negatives = []
positives = []
for i in range(n):
current = int(input())
if current >= 0:
positives.append(current)
else:
negatives.append(current)
print(positives)
print(negatives)
print(f'Count of positives: {len(positives)}. Sum of negatives: {sum(negatives)}') |
d59342bb36164ee61e7f016afaf2c2553e9e6ae8 | shubhamdhoot333/pythonProgram | /MultiplicationOfTable.py | 92 | 3.6875 | 4 | a=int(input("enter number which you want table"));
for i in range(1,11):
print( i*a); |
46c5419a9ec99c8c6d74e161b196ef4aceb7698e | shubhamdhoot333/pythonProgram | /SwapTwoVariable.py | 205 | 3.90625 | 4 | a=int(input("Enter value of first variable"))
b=int(input("Enter value of second variable"))
print("before swapping value")
print(a)
print(b)
a,b=b,a
print("after swapping value")
print(a)
print(b) |
9534d76588f2df565296caf9e0159b798550504a | shubhamdhoot333/pythonProgram | /LeapYear.py | 135 | 4.09375 | 4 | year=int(input("enter year name which you want to know leap or not"))
if year%4==0:
print("leep")
else:
print(" not leap") |
3ff0ca0371d826a300cc7328b587a969b394929c | tkillestein/trm-doppler | /trm/doppler/scripts/makedata.py | 7,530 | 3.515625 | 4 | import argparse, os, configparser
import numpy as np
import pylab as plt
from astropy.io import fits
from trm import doppler
def makedata(args=None):
"""makedata creates a blank data file that can be used as a template for
creating data files, e.g. using comdat. Like makemap it is driven by a
configuration... |
23ba937dd9cf209da56ade6ede1a9584c6b22438 | loredana-stirbu/Instructiunea-IF | /if_strl_11.py | 999 | 3.703125 | 4 | print("Se dau trei numere. Să se afişeze aceste numere unul sub altul, afişând în dreptul fiecăruia unul dintre cuvintele PAR sau IMPAR.")
a=int(input("Dati primul numar: "))
b=int(input("Dati al doilea numar: "))
c=int(input("Dati al treilea numar: "))
if ((a%2==0)and(b%2==0)and(c%2==0)):
print("Toate num... |
1c890091bb05d3b6828e3c6de1bd3dc86021c563 | loredana-stirbu/Instructiunea-IF | /if_strl_3.py | 239 | 3.953125 | 4 | print("Să se verifice dacă o literă introdusă este vocală sau consoană.")
l=input("Dati o litera:")
if ((l=="a")or(l=="e")or(l=="i")or(l=="o")or(l=="u")or(l=="ă")or(l=="î")):
print("Vocala")
else:
print("Consoana") |
dce052d4bde28a865995a97406df1a9dcc0008b3 | pisomnia/LeetCode | /Algorithms/Linked List/143_Reorder List.py | 1,057 | 3.953125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
... |
62954f2160ba4fc399fc0c824e9a63f0a011863d | pisomnia/LeetCode | /Algorithms/Tree/572_Subtree of Another Tree.py | 817 | 3.875 | 4 | # 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 isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"... |
2e8af718e713a42c4a3a5a8c84454e671a10d38c | Reynazhang2014/DataCamp | /HW3/PyPoll/main.py | 1,232 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 19:50:58 2018
@author: zhangyufei
"""
import os
import csv
path = os.path.join('election_data.csv')
total_vote = 0
election = {}
with open(path,newline = '', encoding = 'utf-8') as file:
reader = csv.reader(file, delimiter = ',')
header... |
33f3962ca4f97ee37785b894672da365e2321f0c | nitin-cherian/LifeLongLearning | /Web_Development_Python/RealPython/sql/05_sql.py | 462 | 3.625 | 4 | # INSERT command with error handler
# import the sqlite3 library
import sqlite3
# create the connection object
conn = sqlite3.connect("new.db")
# get a cursor object to execute the commands
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO populations VALUES('New York City', 'NY', 8400000)")
conn.c... |
ddb15fe09b67da5aae4879ccc252b63060773f02 | nitin-cherian/LifeLongLearning | /Web_Development_Python/RealPython/flask-hello-world/app.py | 1,179 | 3.6875 | 4 | # ---- Flask Hello World ---- #
# import the Flask class from the flask package
from flask import Flask
# create the application object
app = Flask(__name__)
# error handling
app.config["DEBUG"] = True
# use the decorator pattern to link the view function to a url
@app.route('/')
@app.route('/hello')
# define th... |
5fbc21600fc9ea53a5e16fa3a00389efecc8be91 | nitin-cherian/LifeLongLearning | /Web_Development_Python/RealPython/flask-blog/sql.py | 684 | 4.125 | 4 | # sql.py - Create a sqlite3 table and populate it with data
# import sqlite3 library
import sqlite3
# create a new database if the database already does not exist
with sqlite3.connect("blog.db") as connection:
# get a cursor object to execute sql commands
c = connection.cursor()
# create the table
... |
b70018a393d272324b542a0d6bc40ce0e1a5a23e | nitin-cherian/LifeLongLearning | /Python/Experiments/ITERATORS/Polyglot.Ninja/why_iterables.py | 494 | 4.75 | 5 | # why_iterables.py
print("""
Iterator behaves like an iterable in that it implements the __iter__ method. Then why do we need iterables?
When StopIteration is raised from an iterator, there is no way to iterator over the iterator again, because
iterator maintains the state and return self when iter is invoked on it. ... |
83b8306a533237034ce55d980ee49b44d9ba0f78 | nitin-cherian/LifeLongLearning | /Python/Experiments/ITERATORS/Polyglot.Ninja/iterators_should_be_iterable.py | 2,400 | 4.40625 | 4 | # iterators_should_be_iterable
print('''
According to the official doc:
*********
Iterators should implement the __iter__ method that returns the iterator object itself,
so every iterator is also iterable and may be used in most places where other iterables
are accepted.
*********
{code}
class HundredIterator:
... |
0f71e8dda38aec28b954dfbbdc7ade8acc99356b | zdrbats/python-basics-solutions | /Simple-Conditions/Time + 15 Minutes.py | 327 | 3.625 | 4 | hour = int(input())
minets = int(input())
addMinets = minets + 15
addHour = hour
if addMinets > 59:
addHour = hour + 1
addMinets = addMinets - 60
if addHour >= 24:
addHour = addHour - 24
if addMinets < 10:
print(str(addHour) + ':0' + str(addMinets))
else:
print(str(addHour) + ':' + str(addM... |
b9fbadca8a1d242c5ad86eaabb75262c20e353d2 | JulianOsorio15/IA241 | /Lab2.py | 395 | 3.828125 | 4 | #3.1
my_name = "Tom"
print(my_name)
#3.2
my_id = 123
print(my_id)
#3.3
#_123=my_id
my_id = your_id=123
print(my_id)
print(your_id)
#3.4
my_id_str = "123"
print(my_id_str)
#3.5
# print(my_name + my_id)
#3.6
print(my_name + my_id_str)
#3.7
print(my_name*3)
#3.8
print('hello world. This is my first python... |
95a6b16d5819c0711522c61f24c8a7c2a5a9a5e7 | PlumpMath/SICP-CS61A | /chapter02/2.7.py | 3,240 | 3.875 | 4 |
##########################################################
from math import atan2,cos,sin,pi
#面向对象中的设计模式-实现复数和分数的运算
#首先定义一个数的抽象类
class Number():
def __add__(self, another):
return self.add(another)
def __mul__(self, another):
return self.mul(another)
#############
#这是后期实现
#############
def add... |
d0c3eee3504d0e0fb919e97c9396080bb70719b9 | indra-singh/Python | /prime_number.py | 350 | 4.125 | 4 | #Write a program to print if a number is a prime number *
n=int(input("Enter lower number :"))
m=int(input("Enter upper number :"))
print("Prime numbers between",n,"and",m,"are:")
for num in range(n,m+1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
els... |
d71afbf08a4088e3770dc46957e7b9e45a6d3e03 | aniGevorgyan/python | /math_util.py | 1,194 | 4.1875 | 4 | #!/usr/bin/python
# 1. Math simple actions
"""
:input a, b
:output: a+b, a-b, a*b, a/b
"""
def mathActions(a, b):
add = a + b
minus = a - b
mult = a * b
div = a / b
return ('Addition is ' + str(add), 'Subtraction is ' + str(minus),
'Multiplication ' + str(mult), 'Division is ' + str(div))
# 2. ... |
80e0c282f6308995f82cceac020e613a503fa073 | aniGevorgyan/python | /third.py | 1,435 | 4.09375 | 4 | #!/usr/bin/python 3.7.2
countOfNumbers = 0
countOfLetters = 0
countOfSpecialChars = 0
countOfVowels = 0
matchCount = 0
vowels = 'aeiou'
sentence = "For instance, if a bank receives $500 as demand deposits and $200 as time deposits during the given period" \
" and the reserve requirement ratio is 10%. The r... |
f9f544b284038311e935918af87d8d6633dc0a6b | RayFFH/File_readandwrite | /project3.py | 599 | 3.703125 | 4 | import random
List_1 = ["What is your age?\n",
"When were you born?\n",
"What is your mothers name?\n",
"What is your favourite sport?\n",
"What is your favourite colour?\n"]
file = open("Questions.txt","w")
file.writelines(List_1)
file.close()
with open("Questions.txt") as my_file:
array = my_file.readlines()
... |
4c7173d644078932261cf2f33aa568baf85671f1 | imaaduddin/TreeHouse-Data-Structures-And-Algorithms | /recursion.py | 297 | 4.125 | 4 | # def sum(numbers):
# total = 0
# for number in numbers:
# total+= number
# return total
# print(sum([1, 2, 3, 4, 5]))
# Recursive Function
def sum(numbers):
if not numbers:
return 0
remaining_sum = sum(numbers[1:])
return numbers[0] + remaining_sum
print(sum([1, 2, 7, 9]))
|
9e01e277f765d81ac1481f465d92dc5c0f34a9db | Mphumutseng/Learning-Python- | /Mpho.py | 581 | 4.09375 | 4 | print("Hello World")
activity = "Python tutorial"
print("Today I will be doing a " + activity + " for beginners")
print("My end goal for today is to know the basics of python")
phrase = "Python for Beginners"
print(phrase + " tutorial")
print(phrase.upper().isupper())
print(len(phrase))
print(phrase[0], phras... |
b4069afe2fa9e83c4021b796526d8739c2ef337f | vikasjain1402/Hackerrank-Solutions | /Hack_marks_percentage.py | 398 | 3.59375 | 4 | if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for name,value in student_marks.items():
if name==query_name:
... |
58c4ba141d64d2ab207d9267dd2ab9a3e5c562e1 | vikasjain1402/Hackerrank-Solutions | /hack_Mutables.py | 384 | 3.9375 | 4 | def mutate_string(string, position, character):
string1 = ""
for i in range (len(string)):
if i == position:
string1 = string1 + character
else:
string1 = string1 + string[i]
return string1
if __name__ == '__main__':
s = input()
i, c = input().sp... |
a588ed72ec0170db56de8711f2b335c2ab4a38c2 | jhudson1239/project | /Python Scripts/Classifiers/Text Blob Classifier.py | 1,198 | 3.515625 | 4 | #This script is the classification script for Textblob that was used for its final sentiment analysis results.
import csv
from textblob import TextBlob
predicted_labels = []
tweets = []
def sentiment(file, proFile):
with open(file, 'r', encoding="utf-8") as csvFile:
reader = csv.reader(csvFile, delimite... |
982a4745310040ddffe85c7d87423460c4d84e51 | luqiang21/small_useful_tools | /csv2xml.py | 1,047 | 3.5625 | 4 | '''Read csv and output xml'''
import csv
csvFile = 'alerts.csv'
# csvFile = 'test.csv'
def csv2xml(csvFile):
name = csvFile.split('.')[0]
xmlFile = name + '.xml'
csvData = csv.reader(open(csvFile))
xmlData = open(xmlFile, 'w')
xmlData.write('<?xml version="1.0"?>' + "\n")
# there must be only ... |
717d142fe11b023100c069b5eea549c6092917f5 | neineihao/chatroom_practice | /base.py | 252 | 3.625 | 4 | from abc import ABC, abstractmethod
class socket_base():
def __init__(self, ip_address, port):
self.ip_address = ip_address
self.port = port
def init(self):
if __name__ == '__main__':
print('Hello World')
|
88891cba26521787b2d7eeecd1f2e558baf8f0fd | orhanyagizer/Python-Code-Challange | /count_of_wovels_constants.py | 549 | 4.3125 | 4 | #Write a Python code that counts how many vowels and constants a string has that a user entered.
vowel_list = []
constant_list = []
word = input("Please enter a word: ").lower()
for i in word:
if i in set("aeiou"):
vowel_list.append(i)
count_vowel = len(vowel_list)
else:
constant_list.append(... |
b0c5415f9e001e616f9dc4f97bb1838884c669df | mobilereal/workshop-2 | /if_else/if_else4.py | 97 | 3.625 | 4 | a = 200
b = 33
if b > a:
print("b is greator than a")
else:
print("a is greator than b") |
1f3fe2be8398eca9a938431c288ec7abd8ab906a | vaishhhhhhh/github_demo | /src/pallindrome_number.py | 307 | 3.703125 | 4 |
# TODO: Find all one digit to 10 digit numbers for which abcd * 4 = dcba
def find_all_palindrome():
for number in range(1000,10000):
number=str(number)
num_rev = int(number[::-1])
number=int(number)
if number*4==num_rev:
return number
x=find_all_palindrome()
print (x)
|
b34df86f80ad10b1de3c234de1a8291d5bba45ac | WMeijbeek/DEVopdrachten-periode-1 | /Leerjaar 1 (2016-2017) PERIODE 1/Assignment IV/absolute.py | 170 | 4.09375 | 4 | def abs_1():
value = int(input("Please enter a value: "))
if value <= 0:
value = value * -1
else:
value = value * 1
print(value)
abs_1()
|
b15238b1d1e81c54b3cf52354d9d2c6e3773d328 | jobiaj/My-Sample-Codes | /10.py | 474 | 3.875 | 4 |
class reverse_iter:
def __init__(self, n):
self.n = n
self.count = len(self.n)
def __iter__(self):
return self
#def reverse1(self):
#for i in self.n[::-1]:
# return i
def next(self):
for i in self.n[::-1]:
if self.count>0:
return i
self.count = self.count -1
i... |
857dca126132f8fe85edf8589a1de8992f338755 | asa-leholland/SudokuSolver | /consoleSudoku.py | 11,547 | 4.3125 | 4 | # filename: consoleSudokuUI.py
# author: Asa Holland
# Import random to randomly select which puzzle is chosen
import random
# import regex to match validity for user-provided input
import re
# import json to read and handle the Sudoku puzzle library (which is stored in a .json format)
import json
# perform a loca... |
031eba1c8374aad620307078113bae3e8e668a54 | OskarBun/Game | /src/oskar/door.py | 1,192 | 3.5625 | 4 | '''
Created on 26 Nov 2013
@author: Oskar
'''
from oskar.interactable import Interactable
class Door(object):
'''
creates a door
'''
def __init__(self, room1, room2, lock):
'''
Constructor
'''
self.lock = lock
self.keys = []
self.connection = {
... |
6b667cef8a716c8131fadcd85acd17770908ac6a | xenicus57/Deletrear-cualquier-numero-entero | /num_char.py | 13,775 | 3.65625 | 4 | """
ANTECEDENTES
-------------
La primera version de numeros a letras se construyó en 1993 en clipper para ayudar a mi amigo Paulino para transferir las notas de los alumnos de la Escuela de Enseñanza de Automoción del EA a la Direccion de Enseñanza que pedia las mismas, aparte de en su valor numerico, como cadena de ... |
2e67edfe9adbdeede8e981fa1c67a8d15ef9996c | ashurek-m/git-course | /Линейные алгоритмы/task_3.py | 677 | 3.9375 | 4 | import math
a = input('Введите длину катета a: ')
b = input('Введите длину катета b: ')
a2 = int(a)
b2 = int(b)
def hypotenuse(katet_1, katet_2):
c = math.sqrt(katet_1 ** 2 + katet_2 ** 2)
return c
def perimeter_of_the_triangle(a, b, c):
p = a + b + c
return p
def area_of_the_triangle(a, b):
s ... |
65e063be364a170aa9d9bcd56ecabb723ed2abb2 | ashurek-m/git-course | /Ветвления/task_15.py | 705 | 4.03125 | 4 | # Определить, принадлежит ли точка с координатами (x; y) кругу радиуса R
# с центром в начале координат. Пользователь вводит координаты точки и
# радиус круга.
import math
def info_task():
info_ = {}
info_['x'] = float(input('x = '))
info_['y'] = float(input('y = '))
info_['r'] = float(input('r = '))... |
5534713328dda88b5ec93556d172c2d5c04b5a62 | Gagnavinnsla/hopaverk_3 | /RQ.py | 5,661 | 3.859375 | 4 | def Quiz():
def getAnswer (answer, counter):
if len(answer)!=1:
return counter,True
elif answer == 'a':
counter += 1
return counter,False
elif answer == 'b':
counter += 2
return counter,False
elif answer == 'c':
counter += 3
return counter,False
elif answer == 'd':
counter += 4
ret... |
ff2685fda29e483a20639a47c43bfd5ba1266568 | fcfalmeida/iart-bblast | /src/utils.py | 5,014 | 4.09375 | 4 | from src.bubble import Bubble
from src.bubble_types import BubbleTypes
from copy import deepcopy
import glob
# Creates a board with the specified height and width (cells)
# and fills it with empty bubbles
# Returns a matrix instead of a Board object
def create_empty_board(height, width):
board = []
for i in range... |
42c32c100700552f7ed911986e28ba21d75267c8 | harshbordhansingh/larger_python_files | /dictionary.py | 210 | 3.6875 | 4 | d1={"harsh":"genius","set":"elephant","jeng":"jui","pulwama":"very bad https://download-cf.jetbrains.com/python/pycharm-community-2019.3.4.exe"}
print("enter the word : ")
inpnum=input()
print(d1.get(inpnum))
|
61d41e260f47d110ec242bed8df5e40b54820d1f | harshbordhansingh/larger_python_files | /object oriented programming.py | 311 | 3.828125 | 4 | class Dog:
def __init__(self, name, age):
self.age = age
self.name = name
print(name)
print(age)
'''def __add__(self, x):
return x+1
def bark(self):
print("bark")
d.bark()
print(d.__add__(5))
print(type(d))'''
d = Dog("Tim", 32)
d2 = Dog("Bill", 31) |
18a44f08f399a020aa08514243c7a660cc00309e | tknight97e/python | /number_guessing/python/functions.py | 1,851 | 4 | 4 | """
* Author: Tyler Knight
* Date: 1/28/2019
* Purpose: Stores the functions for main.py
"""
import random
def generate_random():
"""Generates a number 1-100"""
return random.randint(1, 101)
def generate_attempts(random_number):
"""Generates user attempts based on random_number value"""
... |
b1c6c93cec436efeb23806aaf39d856c707d421f | FrankXie05/python-note | /xl_18_模块.py | 649 | 3.6875 | 4 | """
模块 是python 程序架构的一个核心概念
模块 就好像一个工具包,要想使用这个工具包的工具是,就需要 import 来导入这个模块
每一个以扩展名 py 结尾的 python 源代码文件都是一个模块
在模块中第一的 每一个 全局变量、函数 都是模块能够提供给外界直接使用的工具
模块名:也是一个标识符
命名规则与标识符一样
注意: 如果在 python 起名时,以数字开头 的话,是无法在 pycharm 中导入该模块的
"""
import xl_17_函数的嵌套
xl_17_函数的嵌套.print_lines("-", 50)
print(xl_17_函数的嵌套.name)
|
73d832f7c1a34885c050f640f7961e34729039aa | FrankXie05/python-note | /xl_04_变量.py | 1,185 | 4.0625 | 4 | """
变量名 只有在 第一次出现时 才算定义变量
"""
qq_number = 123
qq_password = 456
print(qq_number)
print(qq_password)
"""
eg :超市买苹果
价格 8.5 元
买了 7.5 斤 苹果
计算付款金额
只要买苹果 就反5元
"""
price = 8.5
weight = 7.5
money = price * weight
money = money - 5
print(money)
"""
变量的数据类型
在python定义变量类型时 是不需要指定变量类型的;
在运行的时候python解释器会根据等号右边的内容来准确推导出... |
d731fa88e5dad1069edc1fabb9086a52ff60443b | fianamara/labpy02 | /main.py | 359 | 3.78125 | 4 | a = int(input("Masukan Nilai a : "))
b = int(input("Masukan Nilai b : "))
c = int(input("Masukan Nilai c : "))
if a > b and a > c:
maks = a
print("Bilangan terbesar adalah a = ", maks)
elif b > a and b > c:
maks = b
print("Bilangan terbesar adalah b = ", maks)
else:
maks = c
print("... |
208e468888f2ba972b618887c2c2f0dab02f1560 | sararibeiro/calendar-plugin | /week.py | 3,087 | 4.28125 | 4 | import datetime
from utils import date_generator
class WeekSpan():
numdays = 7
def __init__(self, numweeks=1, start=None):
self.numweeks = numweeks
self.start_date = start
if start:
self.set_week_starting_on(start)
def set_week_starting_on(self, date):
"""
... |
541d39fe2f6ef9cc7f86284554fc10a7fe0d7678 | JamesMcPeek/Python-100-Days | /Day 2.py | 342 | 4.125 | 4 | print("Welcome to the tip calculator!")
billTotal = float(input("What is the total bill? "))
percTip = int(input("What percentage tip would you like to give? "))
people = int(input("How many people will split the bill? "))
results = round((billTotal * (1 + (percTip / 100))) / people,2)
print("Each person should pay: " ... |
2054c2463104cf5cfba647949ffbe2b008c579ae | corey-garvin/jotto | /jotto_bot.py | 922 | 3.609375 | 4 | import random
class JottoBot(object):
"""A bot for playing Jotto"""
def __init__(self, name):
"""Bot receives a name and a copy of the word list"""
self.name = name
self.word_list = []
super(JottoBot, self).__init__()
def select_a_secret_word(self, word_list):
"""... |
11f6bdb9bbda9f527ac55f3deea458804a7f6e6b | iplay16/vscode | /leetcode/105.construct-binary-tree-from-preorder-and-inorder-traversal.py | 3,145 | 3.765625 | 4 | #
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def tranprelist(self):
self.li=[]
se... |
607fab2445744f7207164b671926eee50b34812e | shetsecure/3i005 | /battelship_game_proba/src/Ship.py | 1,526 | 3.921875 | 4 | from Direction import Direction
class Ship:
# all attributes are public for shorter code ( for now... )
def __init__(self, name, length, color, coord=None, direction=None):
assert(isinstance(name, str))
assert(int(color) > 0 and int(color) < 255)
if coord is not None:
... |
d661d8b56e853a1083942545a650365985dc1714 | iccowan/nasr_to_sector_file_converter | /raw_py/airport_converter.py | 2,934 | 3.875 | 4 | # NASR Subscription Information to Sector File Converter for VATSIM - Airports
# By Ian Cowan
# Python 3.7
# Import Packages
from functions import *
# Main function to be called from main.py
def run():
# Open all the NAV.txt file and create the output file
navaid = open('NAV.txt', 'r')
airports = open('AP... |
c44a37f819b3705b6832603ed4ac385e3750c0cc | storbukas/university | /INF237/set_1/sheep.py | 1,609 | 3.671875 | 4 | def adjacent(x,y,data):
neighbours = []
if(valid(x+1,y,data) and data[x+1][y] == "#"):
neighbours.append((x+1,y))
if(valid(x-1,y,data) and data[x-1][y] == "#"):
neighbours.append((x-1,y))
if(valid(x,y+1,data) and data[x][y+1] == "#"):
neighbours.append((x,y+1))... |
caf58ea2197a68273d5e5a8a7c2b85925ed42bb4 | Lucas-JS/Python_GeekUni | /loop_for.py | 1,107 | 4.21875 | 4 | """
Loop for
Utilizamos loops para iterar sobre sequencias ou sobre valores iteráveis
Exemplos de iteráveis:
- String
nome = 'John Wayne'
- Lista
lista = [1, 3, 5, 7, 9]
- Range
numeros = range(1, 10)
"""
nome = 'John Wayne'
lista = [1, 3, 5, 7, 9]
numeros = range(1, 10)
# Exemp... |
6e0006f481ad405217c63fb285df5f4570d1bdb9 | abevieiramota/book-fluent-python | /ch02/insort.py | 313 | 3.671875 | 4 | import bisect
import random
SIZE = 7
random.seed(1729)
my_list = []
for i in range(SIZE):
new_item = random.randrange(SIZE * 2)
# ? what's the implications of insort with hi/lo not default?
bisect.insort(my_list, new_item, lo=0, hi=min(2, len(my_list)))
print('%2d ->' % new_item, my_list) |
a5b0c5f8741798c0ac66138f3bbe7463fa715838 | NikkieS/Algorithm_practice | /ex.11720_sumofnums.py | 275 | 3.5625 | 4 | """
Date : 11/06/20
Author : GaRam Song
URL : https://www.acmicpc.net/problem/11720
Description : sum of numbers
"""
# My Answer
l = int(input())
num = input()
ans = 0
for i in range(l):
ans += int(num[i])
print(ans)
# Short Coding
input()
print(sum(map(int,input())))
|
8ff2e8443f4600b36fec305fd30aa13680094b87 | NikkieS/Algorithm_practice | /lecture_linkedlist_1031.py | 2,583 | 3.90625 | 4 | '''
Date : 10/31/20
Author : GaRam Song
Description : LinkedList study
'''
class Node:
def __init__(self, item):
self.data = item
self.next = None
class LinkedList:
def __init__(self):
self.nodeCount = 0
self.head = None
self.tail = None
def __repr__(self):
... |
9e3b1386d649a07b2cb408043d539844670ca2d0 | NikkieS/Algorithm_practice | /ex.1157_letteroccurence.py | 896 | 3.9375 | 4 | '''
Date : 10/23/20
Author : GaRam Song
URL : https://www.acmicpc.net/problem/1157
Description : find the letter that appears the most in a string
'''
# My Answer
from collections import Counter
word = input().upper() # input 자체를 대문자로 변환해서 저장
occurence = {}
for letter in word :
if letter in occurence: # 만약 딕셔너리... |
711366138f4c00a893c20f51fc897bde003f1053 | NikkieS/Algorithm_practice | /ex.9498_testscore.py | 390 | 3.59375 | 4 | """
Date : 10/21/20
Author : GaRam Song
URL : https://www.acmicpc.net/problem/9498
Description : test letter score
"""
score = int(input())
if score >= 60 :
ans = "D"
if score >= 70 :
ans = "C"
if score >= 80 :
ans = "B"
if score >= 90 :
ans = "A"... |
f0cb2e4429c81d6c525e7805617348640c18ccf5 | madiyar99/webdev2019 | /week10/hackerrank/18.py | 199 | 3.609375 | 4 | def split_and_join(line):
lis = list(line.split(" "))
lis = "-".join(lis)
return lis
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
|
070ef357203805da6cb6cb4bfb2fc50388ad891a | madiyar99/webdev2019 | /week10/informatics/циклы1/I.py | 109 | 3.5625 | 4 | a = int( input())
i = 2
count = 2
while i < a:
if a % i == 0:
count = count + 1
i = i + 1
print(count) |
d942d90e8bcd185673135e5ff933c8256d2e21e5 | madiyar99/webdev2019 | /week10/informatics/циклы1/C.py | 140 | 3.78125 | 4 | import math
a = int( input())
b = int( input())
y = 1;
y2 = 1.15;
while a <= b:
y2 = math.sqrt(a)
if(a % y2 == 0):
print(a)
a = a + 1 |
10b6b2a4770b63b18648ab4a637a4e8d1dd26b58 | PSauerborn/Traffic-Flow-Project | /Submitted Project/project_functions.py | 18,282 | 4.03125 | 4 | # Code Written by Pascal Sauerborn, 13/12/2018, Student ID: 4313894, University of Nottingham, School of Physical Sciences.
# the following code contains the functions used to gather data and analyse the basic model. See README file for details
from matplotlib.animation import FuncAnimation
import numpy as np
i... |
6638101a00da0a9f940d62a91b56038a28df19a7 | uwmisl/primo-similarity-search | /primo/tools/sequences.py | 3,603 | 3.75 | 4 | """A series of utilities for dealing with sequences.
"""
import numpy as np
"""
Note: DNA sequences are always stored from 5' end to 3' end by convention.
5'-AGGT-3'
||||
3'-TCCA-5'
sequence: 5'-AGGT-3'
complement: 3'-TCCA-5'
reverse complement: 5'-ACCT-3'
"""
# DNA bases (A, T, C, and... |
84dd40ae464a915772aa085001d966087c06d756 | chsejune/data_handler | /resize_image.py | 1,140 | 3.5625 | 4 | __author__ = 'Sejune Cheon'
## tested on Python3
# import libraries
import matplotlib.pyplot as plt
import cv2
# sample data path
data_path = "data_sample/images/000001.jpg"
## read image
img_rgb = plt.imread(data_path)
## resize image
resized_img = cv2.resize(img_rgb, (89, 109)) #(src=image_to_resize, dsize=(wi... |
ae2b3ce92f49fc6d228a85ecdb7b5892fea068d1 | lrobberl/Rotate_Image | /main.py | 1,340 | 3.78125 | 4 |
"""
We start from the outermost square, swapping in a cyclic motion all the elements
When proceeding inward, the squares get smaller and smaller
"""
def cyclicSwap(m, init_i, init_j):
matrixDim = len(m)
limit_y = matrixDim - 1 - init_j
limit_x = matrixDim - 1 - init_i
offset = 0
while offset < (m... |
7419e55dcfacf0eab400524d1fd3cc1cbe5f48c6 | srajamohan1989/aquaman | /StringSlicer.py | 392 | 4.59375 | 5 | #Given a string of odd length greater 7, return a string made of the
# middle three chars of a given String
def strslicer(str):
if(len(str)<=7):
print("Enter string with length greater than 7")
else:
middleindex= int(len(str)/2)
print(text[middleindex-1:middleindex+2])
text=in... |
804ef073849e2d22c2d7586472315feec5011096 | youngyanglu/Euler | /ps3.py | 654 | 3.578125 | 4 | import math
import collections
def prime_numbers(upto):
leftover= collections.OrderedDict()
for i in range(2,upto):
leftover[i] = i
num=2
prime=[]
while num<= math.ceil(math.sqrt(upto))+1:
for i in range(num*2,upto,num):
try:
del leftover[i]
except KeyError:
pass
if leftover.values()[0]==num:
... |
56355540241d3afa99f07e43768c664b860232c3 | youngyanglu/Euler | /ps9.py | 648 | 3.921875 | 4 | import math
def pythagoreantriplet(addition):
for c in range(addition/3,addition/2):
b=int((c+(c/math.sqrt(2)))/2)
y=True
n=0
ahatpast=0
atildepast=0
while y==True:
ahat=math.sqrt(c**2-b**2)
atilde=1000-c-b
if ahat>atilde and b<c:
if ahatpast>atildepast or n==0:
b=b+1
ahatpast=ahat... |
147fc6e4f605ea49c25e84786e771e7a8da2b480 | youngyanglu/Euler | /ps7.py | 553 | 3.703125 | 4 | import math
import collections
def prime_numbers(upto):
leftover= collections.OrderedDict()
for i in range(2,upto):
leftover[i] = i
num=2
prime=[]
while num<= math.ceil(math.sqrt(upto))+1:
for i in range(num*2,upto,num):
try:
del leftover[i]
except KeyError:
pass
if leftover.values()[0]==num:
... |
71b8ad9fb325cc2d3b9d0e26f10654903e91c0c2 | bhatanku1/python_basic | /map1.py | 81 | 3.5625 | 4 | def square(x):
return x*x
temp = (1,2,3,4,5,6,7,8,9)
print map(square, temp)
|
f94f92cde443d629ef03141506aa5f0857cad58c | soft9000/zTurtle | /Python3/ChessBoard.py | 2,865 | 3.796875 | 4 | '''
Part of an upcomming training offering on Turtle Graphics,
I thought that we would share ZBoard with our friends.
This ZBoard class is YA contribution to the Public Domain.
Feel free to use ZBoard in your own creations without care,
concerns, or constraint!
Enjoy,
Randall Nagy
r.a.nagy@soft9000.com
'''
import t... |
0f6c988be90a7970bad16799908821f03d671e0d | sagartatugade/WebServiceWithJango | /oddeven.py | 190 | 3.828125 | 4 |
def Oddeven():
list = [3,5,7,13,45,56,67,89]
for i in list:
if list.index(i)%2==0:
print(i)
else:
print(i*2)
Oddeven()
|
2d2c2f7ea670a516a2716d73a92d986b8498325e | joshl26/tstcs_challenge_solutions | /chapter14_ex1.py | 1,456 | 4.34375 | 4 | # This question actually does not make much sense
# because it is impossible to make a binary tree with no
# leaf nodes! My mistake!
class BinaryTree():
def __init__(self, value):
self.key = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if s... |
307578aa0d627f8e6dc22696c099b36343365f07 | joshl26/tstcs_challenge_solutions | /chapter14_ex2.py | 957 | 3.859375 | 4 | class BinaryTree():
def __init__(self, value):
self.key = value
self.left_child = None
self.right_child = None
def insert_left(self, value):
if self.left_child == None:
self.left_child = BinaryTree(value)
else:
bin_tree = BinaryTree(value)
... |
ea9228cc50d1fa6bb6a5757da447465341c4425b | invinciboy/Pong | /scoreboard.py | 712 | 3.609375 | 4 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Avery", 200, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.goto(0,-100)
self.l_score = 0
self.r_score = 0
self.color("gray")
self.update_sco... |
8053fdd5fed3a656f5e52ae6e66af9a62976500d | jnyryan/rsa-encryption | /p8_is_prime.py | 965 | 4.375 | 4 | #!/usr/bin/env python
"""
Implement the following routine:
Boolean fermat(Integer, Integer)
such that fermat(x,t) will use Fermat's algorithm to determine if x is prime.
REMEMBER
Fermat's theorm asserts that if n is prime and 1<=a<=n, then a**n-1 is congruent to 1(mod n)
"""
import p5_expm
import random
def i... |
e30df21a0f0b1dca737b959447ba95f10e377b80 | bugbuglou/hessian | /hessian_eigenthings/operator.py | 614 | 3.609375 | 4 | """ Basic linear operator abstractions """
class Operator:
"""
maps x -> Lx for a linear operator L
"""
def __init__(self, size):
self.size = size
def apply(self, vec):
"""
Function mapping vec -> L vec where L is a linear operator
"""
raise NotImplemented... |
45f89f31dea0fae85f687dd6f68efb701bffd757 | navokus/RiSk-S--FCode | /SAP/LAB/filter_document.py | 2,506 | 3.75 | 4 | def humanName(s):
ans = 0
i = 0
while i < len(s):
if(s[i].isupper()):
cnt = 1
for j in range (i + 2, len(s)):
if(s[j].isupper() and s[j-1] == ' '):
cnt += 1
if((s[j].islower() and s[j-1] == ' ') or (j... |
f079d7a6b06722989c65b9a493c6f0c9ee9453e8 | Zahari95/Soft-Uni_exam-exercises | /03-find_the_strongest_egg.py | 1,045 | 3.75 | 4 | def find_strongest_eggs(*args):
n = args[1]
sub_list = []
strongest_eggs = []
for i in range(n):
sub_list.append([])
for j in range(i, len(args[0]), n):
sub_list[i].append(args[0][j])
for i in range(n):
strong = False
for j in range(len(sub_list[i]) // 2):... |
1396eee8c97a48d33d307126ac08ebafe8ccf72b | AaronTR/SLU_Software_Engineering_Group_A | /Tools/sanders_corpora_extractor.py | 4,147 | 3.5625 | 4 | # Program that enables the user to sift through Niek Sander's tweet corpora. Useful for converting and condensing the corpora and outputting:
# A json file of positive, negative, and neutral or ALL sentiments.
# A text file of only positive, negative, and neutral tweets or ALL tweets.
import csv, os, json
from pprin... |
8a411eb7d31ca466c67f959c1c2233a40dda1106 | LiliaMudryk/Algotithms_lab_1 | /merge_sort.py | 826 | 3.625 | 4 |
import time
def merge_sort(lst: list):
counter = 0
current = time.time_ns()
if len(lst) > 1:
mid = len(lst) // 2
l = lst[:mid]
r = lst[mid:]
counter += merge_sort(l)[1]
counter += merge_sort(r)[1]
i = 0
j = 0
k = 0
... |
efa2dcde8d6fddbcbea0ce5b0defa790986396ef | martinpeck/broken-python | /mathsquiz/mathsquiz-step3.py | 1,822 | 4.15625 | 4 | import random
# this function will print a welcome message to the user
def welcome_message():
print("Hello! I'm going to ask you 10 maths questions.")
print("Let's see how many you can get right!")
# this function will ask a maths question and return the points awarded (1 or 0)
def ask_question(first_number, ... |
412d895331e8c051e3bed80c9d048b65b95c0abc | jeraas/Python | /somateste.py | 158 | 4.125 | 4 | equation = input('')
last = equation[-1]
print(last)
if type(last) == int:
print('Last index is a number')
else:
print('Last index is not a number')
|
fedd7649f7f8bdf08c39634b97ebea1a2cb6f4cd | akhilmd/btech-sem3 | /modules/pycla.py | 427 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
def get_arg(op_chr = None):
if op_chr == None:
return [sys.argv[i] for i in range(1,len(sys.argv)) if sys.argv[i].startswith("-")==False and sys.argv[i-1].startswith("-")==False]
try:
val = sys.argv[sys.argv.index("-"+op_chr)+1]
return val
except ValueError:
return None
... |
e2597fc532ae710f6c8c168f9637d19b9279fccc | sumitsrv121/parctice2 | /excercise13.py | 176 | 3.640625 | 4 | student={
'Ankit':{'score':90,'age':24},
'Akash':{'score':100,'age':24},
'Aniket':{'score':80,'age':24}
}
print(max(student,key=lambda item:student[item]['score'])) |
b66bf8a200e19fe87eb82eaf0667bca53f7fc8c3 | sumitsrv121/parctice2 | /Excercise3.py | 227 | 4.1875 | 4 | def reverse_string(arr):
new_list = []
for x in arr:
new_list.append(x[::-1])
return new_list
fruits = ['apple','mango','orange','pears','guava','pomegranate','raspberry pie']
print(reverse_string(fruits)) |
3d29395b7f2942b087be36bf4e7995c65a591276 | AtalGuzman/neuronales1 | /perceptron simple/xor.py | 1,319 | 3.984375 | 4 | from random import choice
from numpy import array, dot, random
import matplotlib.pyplot as plt
#tresh function
unit_step = lambda x: 0 if x < 0 else 1
#data to learn, column 2 is the bias
training_data = [ (array([0,0,1]), 1),
(array([0,1,1]), 1),
(array([1,0,1]), 1),
(array([1,1,1]), 0)]
w = random.rand(3)
pr... |
50d6d36e3672a3ecce39cacfe9ce2161123e09c3 | kyhau/small-coding-exercises | /leetcode/flipping-an-image.py | 630 | 3.828125 | 4 | """
https://leetcode.com/problems/flipping-an-image/
"""
class Solution(object):
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for r in A:
r.reverse()
for c in range(len(r)):
r[c] ^= 1
... |
5222ebae0ffdf4d89fd788e68538ca32d657cfe3 | kyhau/small-coding-exercises | /facebook/edit-distance.py | 1,742 | 4 | 4 | """
Write a function to return if two words are exactly "one edit" away, where an edit is:
- Inserting one character anywhere in the word (including at the beginning and end)
- Removing one character
- Replacing exactly one character
"""
def is_one_edit(w1, w2):
"""
Time complexity: O(n)
Auxiliary Space: ... |
a4fd8516cdb93151608b2d9e20df364b0ec65c79 | kyhau/small-coding-exercises | /codility/tests/test_cyclic_rotation.py | 806 | 3.796875 | 4 | import pytest
import cyclic_rotation
"""
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [... |
901f1f603434ee63d715b0c76def8a6188d9f577 | kyhau/small-coding-exercises | /hackerrank/euler003-largest-prime-factor.py | 771 | 4 | 4 | """
https://www.hackerrank.com/contests/projecteuler/challenges/euler003
"""
import sys
def is_prime(n):
if n == 2:
return True
p1, p2 = 2, n
while p1 < p2:
if n % p1 == 0:
return False
p2 = n // p1
p1 += 1
return True
def largest_prime_factor(n):
max_... |
5e4333b18c7dfd5348551c0a4b82bbe739f9ae8d | kyhau/small-coding-exercises | /algorithms_and_data_structures/insertion-sort.py | 1,147 | 3.859375 | 4 | """
Time: Best/Average/Worst O(n) / O(n^2) / O(n^2)
Space: O(1) extra space
Swaps: O(n^2)
Stable,Adaptive, In-place: O(n) when nearly sorted
Algorithm:
Iterate from leftmost to rightmost, for each element, compare backward one by one to the leftmost and swap with an
element if it is smaller than that element.
Go... |
86eb0e461943251a8b3a29725742b04a9f1369aa | Soarnsky/AoC | /2018/6/1.py | 1,457 | 3.5 | 4 | #!/usr/bin/python
import sys
def manhattan_distance(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
with open("input.txt", "r") as f:
coordinates = map(lambda x: map(int, x.strip('\n').split(', ')), f.readlines())
x_coords = []
y_coords = []
for coordinate in coordinates:
x_coords.append(coordinate[0])
... |
cf42255c7704cc3d9a58f858bb9cdcc50fac1c4f | R2333333/LearningPython | /Cp8.py | 462 | 3.53125 | 4 | #
# def displayMessage():
# print('Hello World!')
# displayMessage()
def show_magicians(magicians):
if magicians:
for magician in magicians:
print(magician)
def make_great(magicians):
if magicians:
for i in range(0, len(magicians)):
magicians[i] = 'the Great ' + mag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.