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 |
|---|---|---|---|---|---|---|
d7abc54564a49c5f74aca8e802c5480f667e884a | capac/python-exercises | /math/power.py | 541 | 4.1875 | 4 | import sys
powers_dict = {}
def exponential(number, exponent):
power = 1
for i, _ in enumerate(range(1, exponent + 1)):
power = power * number
powers_dict[i] = power
return powers_dict
if __name__ == '__main__':
base = int(input('Choose the base: '))
exp = int(input('Choose the e... |
c9c50110623da7270dd2c82de1263c9b0ae04eee | AdamZhouSE/pythonHomework | /Code/CodeRecords/2482/60785/273083.py | 115 | 3.625 | 4 | t=int(input())
for i in range(t):
n=int(input())
d=int(input())
if n%d==0 or d%n==0:
print(n/d) |
e52d519980302022aa43457c3c55e65559002480 | oisteinwind/trustpilot-code-challenge | /solver.py | 5,714 | 4.21875 | 4 | import hashlib
from random import shuffle
class TrieNode(object):
'''
A TrieNode is an object consisting of a specific character, a list of children (of TrieNode objects), and a flag stating whether the node represents the end of a word.
'''
def __init__(self, char: str):
self.char = ch... |
74904e7fecd8ed5ad4329fce53a7a7c00b78e040 | ritulsingh/CompetitiveProgrammingSolution | /CodeChef/FLOW010.py | 867 | 3.984375 | 4 | # Write a program that takes in a letterclass ID of a ship and display the equivalent string class description of the given ID. Use the table below.
# Class ID Ship Class
# B or b BattleShip
# C or c Cruiser
# D or d Destroyer
# F or f Frigate
# Input
# The first line contains an integer T, the total number of... |
12cf3bc17ccf0ea5732678fe2e51cd17a8b93430 | nakadorx/holbertonschool-higher_level_programming | /0x0B-python-input_output/14-pascal_triangle.py | 401 | 3.5625 | 4 | #!/usr/bin/python3
"""holbertontask"""
def pascal_triangle(n):
"""holbertontask"""
if n <= 0:
return []
res = []
lt = []
for i in range(n):
x = []
for j in range(i + 1):
if j == 0 or i == 0 or j == i:
x.append(1)
else:
... |
bc968f3c628521ad0448222770b3e750573aff20 | novayo/LeetCode | /AlgoExpert/coding_interview_questions/LinkedLists/Remove_Duplicates_From_Linked_List.py | 504 | 3.890625 | 4 | '''
main idea: linkedlist
time comp: O(n)
space comp: O(1)
- where n is number of nodes in the linkedlist
'''
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeDuplicatesFromLinkedList(linkedList):
# Write your cod... |
3ffef46be7c7e68769eab7c3f55eaf07db9388f5 | LolitaDias/Python-Financial-Data_Election-Result-Analysis | /PyBank/main.py | 3,657 | 4.09375 | 4 | # Code for Python Homework - PyBank data
# Read the csv
#Import modules
import os
import csv
#Define the path of the csv file
csvpath = os.path.join('..', 'PyBank','Resources', 'budget_data.csv')
#csvpath =os.path.join("..","/Users/lolitadias/desktop/Python-challenge/PyBank","PyBank_Resources_budget_data.csv")
#Open c... |
0c41ed0b693a7d22feaaacedb780f98eaceef853 | mmarar/Lessons3 | /Program2.py | 191 | 3.890625 | 4 | #coding: utf-8
print('Input x')
x = float(input())
print('Input y')
y = input()
z = x - y
if z == 0:
print ("Division by 0")
pass
else:
print '(x+y)/(x-y)=', ((x+y)/z)
|
cedadcb97f2d0a4d19b52be24a9906718d453487 | Audrius13/learn_python | /exercise6.py | 296 | 4.21875 | 4 | # Ask for a word
word = input('Please enter a word: ').strip()
# Check if word is not empty
if word:
if word == word[::-1]:
print('String {} is palindrome'.format(word))
else:
print('String {} is not palindrome'.format(word))
else:
print('Word should not be empty') |
dc3c8692434ae0468ca9f790755d6dd9cb3588ff | alexcatmu/CFGS_DAM | /PRIMERO/python/ejercicio88 Distancia.py | 1,578 | 4.0625 | 4 | import math
'''
2.11) Treball amb arrays com a paràmetres de funcions
Un punt a l’espai tridimensional es pot representar com un
array de double’s de 3 posicions, on cada posició conté la coordenada
x,y i z respectivament.
L’objectiu de l’exercici és construir una sèrie de funcions que ens
permetin treballar amb pun... |
e1e576ace737325f5bbfc1951744e1030ae07d30 | ramirodelgado/p_pito_the_movie | /scripts/render/test_read.py | 734 | 3.5 | 4 | #!/usr/bin/python
import MySQLdb
###############################################
basededatos='render'
tabla='test'
###############################################
# Open database connection
db = MySQLdb.connect("localhost","root","pepito1234",basededatos)
# prepare a cursor object using cursor() method
cursor = d... |
3e74933d2b19bbc8df49fb51200d8afbe4e34c74 | Nitesh101/Nitesh_old_backup | /Untitled Folder 2/newpython/comprehensions.py | 287 | 4.0625 | 4 | #!/usr/bin/python
mylist = range(10)
for val in mylist:
val = val**2
print val,
print ('/n')
mylist = range(10)
myset = [val ** 2 for val in mylist]
print myset
mylist = range(13)
for val in mylist:
val = 2**val
print val,
myvector = [2**val for val in mylist]
print myvector
|
d4e100d8db72d2fe1f46755128158b91afd0481e | Heansum/pythonStudy | /chapter3/ex9_ex3_ex).py | 216 | 3.875 | 4 | # 숫자를 입력 받아 var 변수에 저장하고
# 짝수면 True 홀수면 False 를 출력
var = int(input())
print((var % 2) == 0)
print("당신의 체온: ", end="")
body = float(input())
print(body >= 36.5) |
e1ec40e7c77161918e7796b20bafa0e877876fdc | yolish/leetcode | /letter_combination_of_a_phone_number.py | 3,426 | 3.6875 | 4 | #https://leetcode.com/problems/letter-combinations-of-a-phone-number/
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
'''
thoughts:
base case: one digit [2-9] -> ["a1","a2","a3"]
general case:... |
d7ae42d742504a2b4cd5920cf4731add9fab7357 | mailpraveens/Python-Experiments | /Project Euler Problems/2-sumOfEvenFibs.py | 227 | 3.703125 | 4 | def find_sum_of_fibonacci():
sum = 0
a , b = 0, 1
while True:
a , b = b , a + b
if b > 4000000:
break
if b % 2 == 0:
sum += b
print sum
def main():
find_sum_of_fibonacci()
if __name__ == '__main__':
main() |
899bac3720be21e7a27866b649dcdf871c641ca0 | mtan22/CPE202 | /labs/lab2/stack_nodelist.py | 2,093 | 4.125 | 4 | # Lab 2: Michelle Tan
# Instructor: Prof. Parkinson
from __future__ import annotations
from typing import Optional, Any
# Node list is one of
# None or
# Node(value, rest), where rest is reference to the rest of the list
class Node:
def __init__(self, value: Any, rest: Optional[Node]):
self.value = value... |
9c53a5fb8d1762e0fe83bc5fdae3d0395dacdcce | lupang7/coding_algorithm | /easy/字符串中的单词书.py | 692 | 3.78125 | 4 | #-*- coding:utf-8 _*-
"""
@author:lupang
@file: 字符串中的单词书.py
@time: 2021/01/19
"""
'''
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
'''
def countSegments(s: str) -> int:
#方法一
# l=s.split(" ")
# print(l)... |
ffbb613179b58cd04c4223593cd0e72f00df8aac | michodgs25/python-exercises | /exercises/object-oriented.py | 1,749 | 3.9375 | 4 | # OBJECT ORIENTED WORDS AND PHRASES
print("""
Python words and definitions:
* class - Tell Python to make a new type of thing
* object - has two meanings, the most basic type of thing, and any instance of some thing.
* Instance - what you get when you tell Python to create a class.
* def - how you define a functio... |
2b3c0252d3c8042ce1e085af5a2d3e58dd555e4a | eralamdar/python_class | /python_2_1.py | 413 | 4.03125 | 4 | nn=float(input("please enter first number\n"))
mm=float(input("please enter second number\n"))
o=(input("pleae enter your operation\n"))
if o=="+":
print(f"{nn}+{mm}={nn+mm}\n")
elif o=="*":
print(f"{nn}*{mm}={nn*mm}\n")
elif o=="/":
print(f"{nn}/{mm}={nn/mm}\n")
elif o=="-":
print(f"{nn}-{mm}={nn-mm}\n... |
f9e321b2e7b2f4a28ae3e4c0a93604f5c8aef2fc | kristendevore/tkinter-game-project | /ball.py | 897 | 3.875 | 4 | # A Ball is Prey; it updates by moving in a straight
# line and displays as blue circle with a radius
# of 5 (width/height 10).
from prey import Prey
import random
#import model
#import Prey from prey
class Ball(Prey):
radius_constant = 5
radius = 5
def __init__(self,x,y):
... |
65eaf47f8354fd519c168833cad38dbfe10c30ed | Adherer/Python-Learning | /ch2 - Python Advanced Features/Iterator.py | 1,755 | 4.40625 | 4 | # 可以直接作用于for循环的数据类型
'''
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generator function。
这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
'''
'''
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
可以使用isinstance()判断一个对象是否是Iterator对象:
isinstance((x for x in range(10)), Iterator)
输出: True
'''
# 生成器都是Iterator对象,但list、dict、str... |
0e85e7acb74b031ac1fdf55dfecc7be7459888d4 | luisarcila00/Reto1 | /Clase 4/ejercicio_4.py | 497 | 3.828125 | 4 | import math as f
def area_circulo(radio):
radio = float(radio)
area = f.pi * (radio**2)
return area
def volumen_cilindro(radio,altura):
radio = float(radio)
altura= float(altura)
area = area_circulo(radio)
volumen = area * altura
return volumen
area = input('Ingrese el radio del circulo:... |
f072a91c369362b690dac2eb4d948f66c1f582bc | Sabrina8198/Sabrina | /HW6/Dijkstra_06170119.py | 2,634 | 3.640625 | 4 |
# coding: utf-8
# In[2]:
import sys
from collections import defaultdict
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = []
self.graph_matrix = [[0 for column in range(vertices)]
for row in range(vertices)]
def addE... |
09e62c4fd1c85b261201062ad6b83cf712ff727c | sadernalwis/mc-dc | /utils_2d.py | 1,995 | 3.53125 | 4 | """Contains utilities common to 2d meshing methods"""
from settings import XMIN, XMAX, YMIN, YMAX
import math
class V2:
def __init__(self, x, y):
self.x = x
self.y = y
def normalize(self):
d = math.sqrt(self.x*self.x+self.y*self.y)
return V2(self.x / d, self.y / d)
def eleme... |
3105b789f6628a78aeb809dd2b9fb21a5517e85d | ISPritchin/Olympiad | /800/Оформлено/Suffix Three.py | 281 | 4.0625 | 4 | suf_dict = {
"po": "FILIPINO",
"desu": "JAPANESE",
"masu": "JAPANESE",
"mnida": "KOREAN"
}
n_sets = int(input())
for i in range(n_sets):
word = input()
for suf in suf_dict:
if word.endswith(suf):
print(suf_dict[suf])
break
|
09cbdde2b80b5d38d3407ed15ee994849f2e5bc3 | vicariousgreg/neurotransmissionModel | /hh/loc.py | 1,431 | 3.671875 | 4 | from sys import argv
import os
def count_loc(lines):
nb_lines = 0
docstring = False
for line in lines:
line = line.strip()
if line == "" \
or line.startswith("#") \
or docstring and not (line.startswith('"""') or line.startswith("'''"))\
or (line.startswit... |
b7b805f8375474ffecd1bfff3aff4eb57dc995d1 | Robertobappe/Introdu-o-Ci-ncia-da-Computa-o-com-Python-Parte-1 | /cadeia_caracteres.py | 296 | 3.953125 | 4 | c=int(input("digite a largura: "))
l=int(input("digite a altura: "))
i=1
j=1
largura='#'
#caracteres cheios
while i<=l:
while j<c:
j+=1
largura+='#'
print(largura, end="")
print()
i+=1
#última linha
print()
print(largura)
|
f3c49e87be3475c8015dd8b0b2b601af0578071b | caoxudong/code_practice | /hackerrank/008_angry_professor.py | 1,917 | 3.765625 | 4 | #!/bin/python3
"""
https://www.hackerrank.com/challenges/angry-professor
教授正在为一个包含N个学生的班级讲授离散数学。他对这些学生缺乏纪律性很不满并决定如果课程开始后,上课的人数小于K就取消这门课程。
给定每个学生的到达时间,你的任务是找出该课程是否被取消。
Input Format
输入第一行包含T,后面测试数据的组数。
每组测试数据包含2行。 每组测试数据的第一行包含两个空格分隔的整数N和K。
下一行包含N个空格分隔的整数,表示每个学生的到达时间。
如果一个学生的到达时间是非正整数(<=0),则该学生在上课前进... |
262e8023de98f33b313910bf096112c8a0bf9685 | o-henry-coder/python05_12_2020 | /univer/lesson03/task01.py | 266 | 3.8125 | 4 | #1.создайте массив, содержащий 10 первых нечетных чисел.
#Выведете элементы массива на консоль в одну строку, разделяя запятой
even = list(range(1,20,2))
print(even) |
233d96292eceb55899bceabf326edc342d0e22e3 | AshBT/HighPerformanceComputing | /sqrt.py | 144 | 3.78125 | 4 | s = 1
x = 4
for x in range(6):
print "Before iteration %s, s = %s" % (k, s)
s = 0.5 * (s * x/s)
print "After %s iterations, s = %s" % (s)
|
2e573e190cf8113bf7b0b12717767e7e35e5e45c | MiguelTeixeiraUFPB/Python-M1 | /tabuada.py | 548 | 3.953125 | 4 | num=int(input('digite um número para obter sua tabuada:'))
a=num*1
b=num*2
c=num*3
d=num*4
e=num*5
f=num*6
g=num*7
h=num*8
i=num*9
print('a tabuada de {} é :'.format(num))
print('=x='*4)
print('{} x {} = {}'.format(num,1,a))
print('{} x {} = {}'.format(num,2,b))
print('{} x {} = {}'.format(num,3,c))
print('{} x {} = {... |
570a24ca65094963160c1817f162c25c709ea3d9 | Dmitry-Kiselev/clb_tasks | /cluster_tasks/__init__.py | 588 | 3.8125 | 4 | __tasks__ = []
def register(f):
__tasks__.append(f)
return f
@register
def add(x: int, y: int):
print('Task add called with args: {}, {}'.format(x, y))
return x + y
@register
def mul(x: int, y: int):
print('Task mul called with args: {}, {}'.format(x, y))
return x * y
@register
def bubbl... |
f57aed9ba637f1a44b30a0ebed164a9d27c9e4a6 | insanekrolick/Embedded-Python-multi-thread-test | /pyemb1.py | 275 | 3.65625 | 4 | import time
import random
print('External Python Program started...')
counter = 0
limit = random.randrange(3, 10, 1)
print(" Limit: " + str(limit))
while counter < limit:
print('Python: counter = ', str(counter))
counter += 1
time.sleep(2)
print(': End of Py Program')
|
2d40aac936621d9b679fd2e20216be8b5019cf05 | endowp/Python101 | /10/10_P14.py | 824 | 3.71875 | 4 | def tiling(x, c): # คืนค่าจ้านวนวิธีการปูกระเบื้อง x แผ่น โดยที่แผ่นสุดท้ายเป็นสี c
# กรณีปู 1 แผ่น ได้ว่ามีวิธีการปูกระเบื้อง 1 วิธี
if x == 1: return 1
# กรณีปูมากกว่า 1 แผ่น ให้ค้านวณแบบ recursive
else:
way=""
ways={}
way=way[:]+c
if len(way)==N:
ways.add(way)
... |
6dee6ef35081523de54802f459c3bd8ff19989c7 | easmah/topstu | /Exercises/dictionary/dictexercise2.py | 706 | 3.921875 | 4 | rivers = {'nile': 'egypt',
'amazon': 'brazil',
'volta': 'ghana',
'yangtse': 'china'}
for river, country in rivers.items():
print(f"The {river.title()} runs through {country}")
print()
for river in rivers.keys():
print(river.title())
print()
for country in rivers.values():
pr... |
adf3c7924a9a4456c5ffd23b9f90d0cbe460ccb9 | kospek/listofUname | /ugen.py | 4,671 | 4.25 | 4 | """
This program generates a list of usernames using Forename, Middlename
and Lastname as parts of Username.
"""
__author__ = "Kostiantyn Pekarchuk <kospek11@gmail.com>"
__date__ = "15 june 2020"
import os, csv, sys, errno
def readFile(filePath):
"""
Reads file from path and returns its content... |
3ceb4bd86fc646d90c667180954c34e490cc1278 | Lingyu94/Foundation-Studies-of-Python | /运算符.py | 1,177 | 3.796875 | 4 | # 开发者:Lingyu
# 开发时间:2020/11/30 20:50
print('----------算术运算符-------')
print(11 // 2) # 整除运算符
print(11 % 2) # 取余运算符
print(2 ** 3) # 幂运算符
print(-11 // 2) # 一正一负,向下取整=-5.5-->-6
print(-11 % 2) # 余数=被除数-除数*商=-11-2*(-6)=1
print('----------赋值运算符-------') # 从右向左赋值,详见笔记
a, b, c = 12, 13, 16
print(a, b, c)
# ... |
4f53d103c5d5e8425d6b5806ba6c5d1be444c340 | dkout/6.s080 | /week1b/armean.py | 153 | 4 | 4 | numbers=[1,2,3,4,5]
if len(numbers)==0:
print('None')
else:
avg=0
for i in numbers:
avg+=i
avg=avg/(len(numbers))
print(avg)
|
03d0ae6db369d532ac08a0a8c587357ce3af51a2 | sputnikW/algorithm | /leetcode/530.py | 1,847 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
def findMaxNode(node):
if node.right != None:
... |
a29f6d06baaea2f924ed3f78b36b593bf88cd9b3 | KevinBollengier/AIChallenge | /Main.py | 4,290 | 3.859375 | 4 | import json
import sys
from typing import *
import nltk
def read_tweets(filename1: str, sentiment: str) -> List[Tuple[str, str]]:
"""
Function which reads a json file and returns a List of tuples with a tweet and sentiment.
:param filename1: Negative tweets (dataset)
:param sentiment: Postive tweets (... |
90261cc565f10d9088252cde427afa9611595d86 | drkarl/bitcoin_dealer | /exchange/exchange_abstract.py | 2,243 | 3.921875 | 4 | from abc import ABCMeta, abstractmethod, abstractproperty
#import settings as settings
class Order:
"""
This one is not abstract, but just base class for setting
exchange["blabla"].order.trades = exchanges["blabla"].get_order(trades)
"""
trades = None
sum_price = 0
sum_amount = 0... |
3a1282e2cbbc3c579dd332c46cb7d9a3131828ef | ThuanK42/HocPython | /Chapter03/Split&JoinString.py | 637 | 3.75 | 4 | ''' Thao tac noi va cat chuoi'''
chuoi = 'Bảo đao đồ long hiệu lệnh thiên hạ, Ỷ thiên kiếm diệt sát quần hùng'
# chuoi.split(): Cat chuoi dua vao khoan trang => result: mảng các chuỗi đã loại bỏ khoản trắng
print(chuoi.split())
# chuoi.split('a'): Cat chuoi dua vao ky tu a
print(chuoi.split('a'))
# chuoi.split('',n... |
38a2ed9979f81071a4cb8e9e9c9522a9a4ea1302 | giridhersadineni/pythonsrec | /03.Loops/while_list.py | 138 | 3.71875 | 4 | numbers=[1,2,3,4,6,4,3,5,6,7,8,923,3,54,67,89,7]
i=0
list_length=len(numbers)
while(i<list_length):
print(numbers[i])
i=i+1
|
f44e41d73d927b36d38143ef2dc4734c6eebd89f | funnyabc/LeetCodePractice | /LinkedList/python/LinkedList.py | 3,181 | 4.15625 | 4 | class LinkedListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
self.size = 0
def get(self, index: int) ... |
0825d16a919a861a95726c8e71589fa64ffa1bbd | vinayvasis/Python-Basics-Must | /DataTypeMethods/set_methods.py | 2,308 | 4.1875 | 4 | """
1.add() Adds an element to the set
3.2.clear() Removes all the elements from the set
4.copy() Returns a copy of the set
5.difference() Returns a set containing the difference between two or more sets
6.difference_update() Removes the items in this set that are also included in another, specified set
7.discard() Rem... |
adb199ec38bf4c9b25d363e290b293fe909cc11f | devopstasks/PythonScripting | /22-OOPS for Real Time/99-Polymorphism-and-inheritance-of-python-oops.py | 1,631 | 4.46875 | 4 | '''
======================================
Concept: Inheritance and Polymorphism
Polymorphism:
=> Polymorphism allows us to define same methods in different classes.
=> This process is also called as method overloading.
Inheritance:
=> Inheritance is a mechanism that allows us to create a new class - known as
child ... |
c9b40867d9181e16dc264891372606d1b89313d7 | pykili/py-204-hw1-EkaterinaVoit | /task_12/solution_12.py | 377 | 3.546875 | 4 | # your code here
string = input()
count1 = 0
count2 = 0
b = string[0]
c = string[0]
occured_twice = False
for i in string:
d = b + i
count2 = 0
count1 += 1
for a in string:
e = c + a
count2 += 1
if d == e and count1 != count2 and count1 != 1 and count2 != 1:
occured_t... |
b891bfdfd6e33160e094e2cece05cd36ad960197 | manideepa03/Tries-1 | /Problem3.py | 1,616 | 4 | 4 | # Time Complexity : O(nl) where n is the number of words and l is the average length of the words
# Space Complexity : O(nl)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
class TrieNode (object):
def __init__(self):
self.isword = False
self.child... |
afe0e6a9028bbd231778f7ab83cd00be117d5a7a | DWCamp/ChainWatch | /config/config.py | 6,169 | 3.8125 | 4 | import json
class Config:
def __init__(self, file_loc: str,
required_keys: dict = None,
autosave: bool = False,
delay_load: bool = False):
"""
Creates a Config object and loads the values in from the provided file path
:param file_loc: Th... |
70970c71941691d8b570eb287ccb4124c2e9c3dc | ikkaku1005/ML100Days-1 | /資料科學馬拉松/Day13.py | 3,813 | 4.09375 | 4 | #D13:Pandas Dataframe 的新增與刪除
#從 DataFrame 中插入或刪除資料
#對於一個 DataFrame 可以進行新增或刪除的操作,又可以分為行或是列的方向:
#1.= 可以用來增加行(欄)
#2.append() 可以用來新增列(資料)
#3.del 或 pop() 可以用來刪除行(欄)
#4.drop() 可以用來刪除列(資料)
#1.= 可以用來增加行(欄)
#可以利用指派運算(=)值些產生新的欄位:
import pandas as pd
df = pd.DataFrame([[1],[2]],columns = ['a'])
print(df)
# a
#0 1
#1 2
df['b'... |
2f43f33a8a3a6d43ea4333bdee2cbe8e7a9ce9be | CUGshadow/Python-Programming-and-Data-Structures | /Chapter 06/Ch_6_Project_05.py | 1,977 | 4.40625 | 4 | '''
(Binary to hex)
Write a function that parses a binary number into a hex number.
The function header is:
def binaryToHex(binaryValue)
Write a test program that prompts the user to enter a binary number and
displays the corresponding hexadecimal value. Use uppercase letters
A, B, C, D, E, F for hex digits.
'''
... |
55e226e6a706624418c97df93df7f202b0aded4e | JiahongHe/Data-Structures-and-Algorithms | /Data Structures/Assignment3/hash_substring.py | 764 | 3.828125 | 4 | # python3
def read_input():
return (input().rstrip(), input().rstrip())
def print_occurrences(output):
print(' '.join(map(str, output)))
def hash_func(s):
_multiplier = 263
_prime = 1000000007
ans = 0
for c in reversed(s):
ans = (ans * _multiplier + ord(c)) % _prime
... |
8f6dde0bdcadbdcee260f2b39ca855335adce451 | Cory240/BL_clone | /src/minigames/blackjack/card.py | 743 | 3.75 | 4 | class Card:
cards = {
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"jack": 10,
"queen": 10,
"king": 10,
"ace": 11
}
@staticmethod
def get_card_v... |
181d2cc5ccf318c3a5b64669151feda281637dc7 | robertlagrant/codeeval | /Moderate/101/solution.py | 1,741 | 3.578125 | 4 | import sys
def distance(c1, c2):
xdist = abs(c1[0] - c2[0])
ydist = abs(c1[1] - c2[1])
# Just keep it as squared dists, as this is just for comparisons
return xdist ** 2 + ydist ** 2
with open(sys.argv[1], 'r') as f:
for line in f:
line = line.strip()
if not line:
... |
4a481582a0cf5bff0382909e868b15316e95698e | Sakamotto/IFES_Prog2 | /Programas/Exercicio 8.py | 1,133 | 3.875 | 4 | """
Construa a função removeAcento(<texto>) que retorna uma versão de <texto> com os caracteres acentuados
substituidos por seus equivalentes não acentuados
"""
def removeAcento(pTexto):
strSemAcento = "aeiou"
strComAcento = "áàâãéèêẽíìîĩóòôõúùûũ"
novoTexto = ""; j = 0; i = 0
divisor = 4
while i < len(pTexto):
... |
752c717e4f63d7cb0526fcc5365ed3a6bb8f98d6 | kampetyson/python-for-everybody | /9-Chapter/Exercise5.py | 857 | 4.53125 | 5 | '''
This program records the domain name (instead of the
address) where the message was sent from instead of who the mail came
from (i.e., the whole email address). At the end of the program, print
out the contents of your dictionary.
python schoolcount.py
Enter a file name: mbox-short.txt
{'media.berkeley.edu... |
8a26f7edff97e5cbdba1e4fa5d156e34a31e61c5 | shahriarearaf/-play_with_snake_python_bootamp | /2.py | 150 | 4.15625 | 4 | print("Celsius : ")
celsius = float(input())
fahrenheit = celsius*1.8+32
print(str(celsius)+" Degree Celsius In Fahrenheit is " + str(fahrenheit)) |
1783d723dc6b8361d40981cd72fc058069959f7b | JessicaSteen/11.11-Data-Python | /data_presenter.py | 1,512 | 3.921875 | 4 | open_file = open("CupcakeInvoices.csv")
# print(open_file)
#loop through all the data and print each row
# for line in open_file:
# print(line)
#Loop through all the data and print the type of cupcakes purchased
# for line in open_file:
# values = line.split(',') #split(sepe... |
3989e3c90e28ee9c9010fd98ec8445dbf99fa3b8 | nampython/OOP-Python | /magic.py | 2,239 | 3.5625 | 4 | # Dunder methods
# __init__ , __add__, __mul__, __sub__, __eq__, __len__
class Fraction:
def __init__(self, nr, dr=1):
self.nr = nr
self.dr = dr
if self.dr < 0:
self.nr *= -1
self.dr *= -1
self._reduce()
def show(self):
print(f'{self.nr}/{self.dr... |
b9ae6181022438b1479e0d03cca48cda5b4f62c8 | PitiMonster/Studia | /semestr4/Algorytmy i Struktury Danych/Lista4/main.py | 3,274 | 3.625 | 4 | import binary_tree
import rb_tree
import hmap
import sys
import re
import time
struct = None
insert_num = 0
delete_num = 0
find_num = 0
min_num = 0
max_num = 0
greatest_elem_number = 0
curr_elem_num = 0
succ_num = 0
'''
remove not letter chars
from beginning and end of give string
'''
def fix_word(word):
is_let... |
b93dc9ede33b37e5e2b2b48110fe488c109182b2 | deepakswami2808/fsdp2019 | /day03/weeks.py | 461 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 16:14:41 2019
@author: lenovo
"""
tuple1 = list(input('enter days : '))
day = ('monday','tuesday','wednesday','thursday','friday','saturday','sunday')
for i in day:
if i in tuple1:
continue
elif i not in tuple1:
tuple1.append(i)
prin... |
746fe9660680472e38c079511daa7bd989386336 | saikirankondapalli03/pythonmath | /chapter 1/HW01-02.py | 593 | 4.125 | 4 | '''
@author Sai
File name: HW01-02.py
Date created: 7/10/2019
Date last modified: 7/10/2019
Python Version: 3.1
This file is for multiplier with number and limit for number of multipliers
'''
import sys
def multi_table(number,multiple_limit):
for i in range(1, multiple_limit+1):
print('{0} x {1} = {2}'.f... |
9e8c86c702adcb2e3e77f3adf85a4c62baa5353a | caojianfeng/py_pentagram | /t03_draw_pentagram_edge.py | 450 | 3.609375 | 4 | from turtle import *
from configs import *
edge_count = 5
angle = 144
angle_out = -72
def draw_pentagram_edge(size):
for n in range(edge_count*2):
forward(size*(1-GOLDEN_SECTION))
right(angle_out if n % 2 == 0 else angle)
if __name__ == "__main__":
setup (width=WINDOW_SIZE,height=WINDOW_SIZE)
... |
f7819fdf5b268f2106fd4a35196ed3c7ba836dce | Liansir/Python | /study3/lottery.py | 641 | 3.84375 | 4 | #!/usr/bin/env python
import random
lottery = random.randint(0, 99)
guess = eval(input("Enter your lottery pick (two digits): "))
lottery_1 = lottery // 10
lottery_2 = lottery % 10
guess_1 = guess // 10
guess_2 = guess % 10
print("The lottery number is", lottery)
if guess == lottery:
print("Exact match: you... |
9143a3585642c7d6d3b621fe3bc7fb748dd3bbc2 | judgementc/plantcv | /plantcv/shift_img.py | 2,143 | 3.65625 | 4 | # Crop position mask
import numpy as np
from . import print_image
from . import plot_image
from . import fatal_error
def shift_img(img, device, number, side="right", debug=None):
"""this function allows you to shift an image over without changing dimensions
Inputs:
img = image to mask
number = ... |
20ff1c96062ae5914cbc406420d01a5d62a15e2d | noushadkhan01/my_methods | /my_methods/transpose_of_matrix_without_numpy.py | 671 | 3.984375 | 4 | def create_empty_matrix(shape = (4, 4)):
rows = shape[0]
cols = shape[1]
matrix = []
for i in range(rows):
matrix.append([0 for i in range(cols)])
return matrix
def transpose_without_numpy(matrix):
'''it returns transpose of a matrix without any use of numpy'''
#get shape of matrix
rows = len(matrix... |
cce3a2776f96bff739ec8d9d06dedaea549c5896 | althafuddin/python | /learnpython_hardway/std_library.py | 353 | 3.75 | 4 | from time import localtime, strftime, mktime
start_time = localtime()
print(f"Timer started at {strftime('%X', start_time)}")
input("Press 'Enter' to stop the script")
stop_time = localtime()
differnce_time = mktime(stop_time) -mktime(start_time)
print(f"Timer stopped at {strftime('%X', stop_time)}")
print(f"Total... |
3a04830cb97cc5a7caee7ae1d480f6daea4b3a96 | SLYJason/Udacity_Intro_to_cs | /deep_reverse.py | 611 | 3.90625 | 4 | #!/usr/bin/env python
def is_list(p):
return isinstance(p, list)
def deep_reverse(input_list):
reversed_list = input_list[::-1]
for i in range(0, len(reversed_list)):
if is_list(reversed_list[i]):
reversed_list[i] = deep_reverse(reversed_list[i])
return reversed_list
def test():
... |
83f9529431dca92d7f95db4702057425f0720a61 | RayGuo-C/python_example | /class/student.py | 390 | 3.515625 | 4 | # create a class including the same attribution for various subject.
class student:
def __init__(self, name, age, gender,gpa):
self.name = name
self.age = age
self.gender = gender
self.gpa = gpa
# build a function to describe the value
def on_roll(student):
if student.g... |
94213ee6c42b3112ccc66a86ede0a11e2de6cda4 | zhengxuanxuan123/THDwebframe | /lianxi/shuzi.py | 240 | 3.859375 | 4 | A= range(101)
for a in A:
if a == 0:
print(a)
elif a%3 == 0:
if a%5 ==0:
print('FizzBizz',a)
else:
print('Fizz',a)
elif a%5 == 0:
print('Bizz',a)
else:
print(a) |
94a99146064e053205e864921f5b8b6388761e2c | AlterraDeveloper/ProgrammingBasics_python | /lab3/task_1-3-16.py | 1,361 | 3.546875 | 4 | # В отличие от гармонических чисел, сумма последовательности 1/12 + 1/22 + + ... + 1/п2 действительно сходится к
# константе при п, стремящемся к бесконечности. (Поскольку эта константа -тr2/6, данная формула используется для вычисления
# значения числа л.) Какой из следующих циклов for вычисляет эту сумму?
# Подр... |
d12b8473faffb0a556ef7f90290a6b3512826606 | tahe-ba/Programmation-Python | /serie/project-crypt/attack.py | 1,862 | 3.625 | 4 | import os.path
def find_word(file_name, string_to_search):
found =0
with open(file_name,'r') as file:
for line in file:
line=line.strip()
if line==string_to_search:
found=1
return (line)
if found == 0 :
return 0
f.close... |
b7f2135f6795d8870686f615b2909d84eb1a4a10 | usernamezzh/haha | /variable_demo.py | 1,594 | 4.21875 | 4 | # -*-coding:utf-8-*-
# 变量的引用
# 1.变量和数据都是保存在内存中的
# 2.在python中函数的参数传递以及返回值都是靠引用传递的
# 引用的概念
# 1.在python中,变量和数据是分开存储的
# 2.数据保存在内存的一个位置
# 3.变量保存着数据在内存中的地址
# 4.变量中记录数据的地址,就叫做引用 使用id()函数可以查看变量中保存数据所在的内存地址。
# 注意:如果变量已经被定义,当给一个变量赋值的时候,本质上是修改了数据的引用,变量不再对之前的数据引用,变量改为对新赋值的数据引用
# 在 Python 中,变量的名字类似于 便签纸 贴在 数据 上
# 定义一个整数变量 a,... |
89918517ad3fde01896a3cec96e5c802dd8eaed8 | daniel-reich/ubiquitous-fiesta | /hZi6AhWEzGASB7tWR_4.py | 211 | 3.890625 | 4 |
def check(lst):
if all([lst[i + 1] > lst[i] for i in range(len(lst) - 1)]):
return "increasing"
elif all([lst[i + 1] < lst[i] for i in range(len(lst) - 1)]):
return "decreasing"
return "neither"
|
acd9516771c9e385bcb75bb605c3f683ae8f7204 | briansu2004/data-masking | /mylibrary/mask.py | 2,953 | 3.921875 | 4 | # 04 May 2018 | Masking Routines Library
"""Masking Routines Library
Library that:
1. Masks strings by Character Substitution - Random
2. Masks strings by Character Substitution - Deterministic
3. Masks strings by Character Shuffling - Random
4. Masks strings by Character Shuffling - Deterministic
"""
import logging
... |
435716eea1d60962ed2815d23df7ed83e47ccabe | oskiyu/arcade-labs | /lab02-draw/example-draw.py | 3,273 | 4.3125 | 4 | """
This is a sample program to show how to draw using the Python programming
language and the Arcade library.
"""
# Import the "arcade" library
import arcade
posX = 0.0
# Open up a window.
# From the "arcade" library, use a function called "open_window"
# Set the window title to "Drawing Example"
# Set the and dime... |
844cac8b6c6e746139ffe49a1b4fef4fb3714ea3 | Hu-Ivy/Baishi-Homework | /Day_3/3.py | 359 | 4 | 4 | x = input("input x,y:")
y = input("input x,y:")
if (x == 0 and y == 0):
print("原点")
elif (x == 0):
print("x轴")
elif (y == 0):
print("y轴")
elif (x > 0 and y > 0):
print("第一象限")
elif (x > 0 and y < 0):
print("第二象限")
elif (x < 0 and y > 0):
print("第三象限")
elif (x < 0 and y < 0):
print("第四象限")
|
113800b5d57b540bf9a80111acc0f84a8c94dbc5 | zubie7a/Algorithms | /HackerRank/Python_Learn/01_Introduction/08_Print_Function.py | 285 | 3.796875 | 4 | # https://www.hackerrank.com/challenges/python-print
from __future__ import print_function
if __name__ == '__main__':
# For a given n, print all the numbers 1234567...n without string methods.
n = int(raw_input())
arr = [i for i in range(1, n + 1)]
print(*arr, sep="")
|
a7e825341221ddcf4361229589e3a2c9345321b0 | el-hult/adventofcode2019 | /day01/day1_lib.py | 450 | 4.125 | 4 | from math import floor
def calculate_fuel_consumption(mass: int) -> int:
fuel_needed = floor(mass / 3) - 2
return fuel_needed
def calculate_fuel_consumption_plus_fuel_for_fuel(mass: int) -> int:
fuel_needed = 0
newly_added_mass = calculate_fuel_consumption(mass)
while newly_added_mass > 0:
... |
50a3e3a8f94bcf0e12ef83a589281f6a36c72d77 | kamilloads/prog1ads | /lista3-3.py | 270 | 3.90625 | 4 | #Faça um Programa que verifique se uma letra digitada é "F" ou "M".
#Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido.
gen = str (input("Digite (F) ou (M): "))
if gen == "f":
print("Sexo Feminino")
elif gen == "m":
print("Sexo Masculino") |
e0f5065f58febc438cd49b6c1e0893c7c80bf454 | ZhiquanW/Learning-Python-HackerRank | /Sets/Introduction-To-Sets.py | 245 | 3.734375 | 4 |
def average(array):
# your code goes here
temp_set = set(array)
return sum(temp_set)/len(temp_set)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
0e301035bf05480d99760358f489239b227f6f33 | sbairishal/CodePath-Alumni-Professional-Interview-Prep-Course | /interviewbit-heaps-and-maps-magician-and-chocolates.py | 759 | 3.671875 | 4 | import heapq
class Solution:
# @param A : integer
# @param B : list of integers
# @return an integer
def nchoc(self, A, B):
"""
Python's heapq data structure is a minheap, so I had to put the values in as value * -1,
and then just convert back and forth when popping/pushing from... |
eb470c28f35d6964d3ea2a18b0f445292d93767a | AnoopPS02/Launchpad | /P1.py | 245 | 3.765625 | 4 | from datetime import *
present = str(date.today())
now = present.split()[0].split("-")[0]
Name=input("Enter your name : ")
Age=int(input("Enter your Age : "))
print("Hey ! "+Name.split(" ")[0]+" you'll turn 100 years in "+str(int(now)+100-Age))
|
4849390987f0711ebebc0f5519ae4e563d4e1ba3 | hillala/hack-rank-solutions | /data_structure/level_order_traversal.py | 708 | 3.921875 | 4 |
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
def height(root):
if not root:
return -1
else:
lDepth = height(root.left)
rDepth = height(root.right)
if (lDepth > rDepth):
... |
5f9503e1a39632c914cf0317d6f45c298e3fbcd1 | gabriel-bri/cursopython | /CursoemVideo/ex057.py | 204 | 4.03125 | 4 | sexo = str(input('Digite seu sexo [M/F]: ')).strip().upper()[0]
while sexo not in 'MmFf':
sexo = str(input('Digite seu sexo [M/F]: ')).strip().upper()
print('O sexo informado é: {}' .format(sexo))
|
a8262433e7340b54ef05db6162a1da0c359edadb | liuzi/cs5242_deep_learning | /e0210497_assignment1/codes/nn/operations.py | 18,507 | 3.6875 | 4 | import numpy as np
# Attension:
# - Never change the value of input, which will change the result of backward
class operation(object):
"""
Operation abstraction
"""
def forward(self, input):
"""Forward operation, reture output"""
raise NotImplementedError
def backward(self, out_... |
d8c11a4caa50c345b8852f63c11e3d5136088191 | emttiew/NAI-PJATK | /Battleships/NAI-Battleship.py | 9,291 | 4.125 | 4 | ## Author: Mateusz Woźniak s18182
## Author: JAkub Włoch s16912
## code reference: https://discuss.codecademy.com/t/excellent-battleship-game-written-in-python/430605
## game description: https://en.wikipedia.org/wiki/Battleship_(game)
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#TOD... |
cc8dd1c3bbf1001275751facca342a66561a8e33 | sahilshah1610/HackerRank | /ListComprehensions.py | 429 | 3.609375 | 4 | def listComprehensions(x, y, z, n):
combinations = [[a,b,c] for a in range(0, x+1) for b in range(0, y+1) for c in range(0, z+1)]
resultArray = list()
for arr in combinations:
if sum(arr) != n:
resultArray.append(arr)
print(resultArray)
pass
if __name__ == '__main__':
x = i... |
95538eb93928403ba42127bcbaae0e8a2e6eb2b8 | karendiz/ex-python | /desafio008.py | 660 | 4.09375 | 4 | # Um programa que realize a união do conteúdo de três listas contendo valores inteiros,
# garantindo ao mesmo tempo que o resultado não contenha valores duplicados.
# Utilizando os tipos de dados list e set resolva o problema.
# Você pode utilizar valores arbitrários dentro das listas.
lista1 = ['Maçã', 'Laranja'... |
de0808e51214bbb009111f12697f806037f1db56 | LaBravel/Tedu-code | /python_base/weekly test02/5.py | 329 | 3.609375 | 4 | def calculate(i,j = 0) :
k = i + j
i = int(k / 2)
j = int(k % 2)
return [i,j]
L = [int(input("有多少钱?")),0]
num = 0
while 1 :
num += L[0]
L = calculate(*L)
if sum(L) == 1 and L[0] == 1 :
num += 1
break
elif sum(L) == 1 and L[1] == 1 :
break
print("能买",num,'瓶') |
8b5657a977c8f5fdd574e9dda138bc114ccc7ea1 | gileno/workshop-fase | /basico.py | 1,208 | 4.25 | 4 | # Exemplo de print
# Hello World
# Exemplo de input
# Nome e Quantos anos?
# nome = input("Qual é o seu Nome: ")
# saida = "Seu nome é " + nome
# print(saida)
#
# ano = input("Quando você nasceu? ")
# ano = int(ano)
# idade = 2014 - ano
# print("Sua idade é", idade)
# Exemplo de IF/ELSE
# Qual o maior número?
# numer... |
4f5d4173a2d1c6e1bf9b90b5d381afb95e3e6deb | sushidools/python | /test for practice makes perfect | 688 | 4.1875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 1 19:09:26 2018
@author: aleksandradooley
"""
# How to print a list with every character reversed
def reverse(text):
word = ""
l = len(text) - 1
while l >= 0:
word = word + text[l]
l -= 1
return word
print reverse(... |
4072f06f735842a2661c55b7e475bae98a0177f2 | CaptainnK07/Geek_week__local | /nhk.py | 131 | 3.640625 | 4 | x = 10
y = 50
x = x * y # x = 500
y = x / y # y = 10
x = x / y # x = 50
print("After Swapping: x =", x, " y =", y);
|
524e5e77439696aaa1f357b82b3a1539bc48b434 | stefyk/Respiration | /MCP3208_improved.py | 1,105 | 3.71875 | 4 | #This code has been developed, using
#https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-3-spi-and-analog-input
#This code has been developed, using
#https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi... |
83b59275bd67b56ef19eeab55626f72b802f3a50 | daniel-kauffman/calpoly-vue | /dist/202/pset5.py | 5,234 | 4.28125 | 4 | # Name:
# Course: CPE 202
# Instructor: Daniel Kauffman
# Assignment: Problem Set V
# Term: Spring 2021
from typing import List, Optional, Tuple
class ListNode:
def __init__(self, val: int, ref: Optional["ListNode"]) -> None:
self.val = val
self.ref = ref
def __eq... |
8364142e3e563e01056e665a312aa710c32dbd8f | anildhaker/DailyCodingChallenge | /GfG/Mathematical Problems/powOfPrime.py | 422 | 4.09375 | 4 | # Finding power of prime number p in n!
# eg. n = 4 p =2 --> 4! = 24 = 2*2*2*3 --> should return 4 else return Zero.
# Just count power of p from 1 to n. and add them.
def powerPinNfactorial(n, p):
ans = 0
temp = p
while (temp <= n):
print("n-->",n)
ans += n / temp
print("ans-->",ans)
temp = te... |
962a0925a7b5b2f7162399173012aceb708b9912 | lelilia/invent_your_own_computer_games_with_python | /dragon.py | 1,290 | 3.828125 | 4 | # Das ist ein Choose your own Adventure aus https://inventwithpython.com/invent4thed/ mit genau einer Userinnen Eingabe
import random
import time
def displayIntro():
print('''Du befindest dich in einem Land voller Drachen.
Vor dir siehst du zwei Höhlen.
In einer Höhle befindet sich ein netter Drache,
der seinen... |
675b9e80b63e6f563e615577463a721efa168158 | lyusongll/LeetCode | /111. Minimum Depth of Binary Tree.py | 1,175 | 3.640625 | 4 | class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self,root):
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.lefr),self.minDepth(root.right)) + 1
else:
return max(self.minDepth(root.left),sel... |
d9f4967160208571bebe09c557866e0749a5d0dd | sumitd-archives/coding_problems | /problems/heaps/python/Main.py | 1,240 | 3.5 | 4 | import numpy as np
import Node
import MinHeap
def main():
array = np.array([[1, 3, 5, 7], [2, 4, 6, 12], [0, 9, 10, 11]]);
k, n = np.shape(array);
#node_dt = np.dtype([('value' , np.int,1),('arr_num', np.int,1)]);
#nodes = np.empty((k, n), dtype=node_dt);
nodes = [];
node_num = 0;
for i i... |
e339b3a3749a3d2d05a222bfd0036d399057806f | Titowisk/estudo_python | /book_al_sweigart/cap06/cabecalho.py | 570 | 3.90625 | 4 | #! python
# cabecalho.py - Um programa que facilita o preenchimento de cabecalho
INFO = {
'nome': 'Vitor',
'sobrenome': 'Rabelo Filardi Ribeiro',
'CEP': '40270010',
}
import sys, pyperclip
if len(sys.argv) < 2:
print('Como usar:')
print('Ele abre o python e digita: cabecalho.py [titulo]')
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.