blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a245c1688386bd966ee720f661926b2d1c0a1cca | abmurli/my_codes | /python_code/Self-test/ladder.py | 392 | 3.84375 | 4 | def ladder(n):
for x in range(1, n+1):
print('{}'.format(' ' * (n-x)) + '{}'.format('#' * (x)))
def ladder_1(n):
for i in range(1, n+1):
for j in range(i, n+1):
if i >=j:
print("#"*j, end= "\n")
def ladder_2(n):
for i in range(1, n+1):
print("#"*i, end... |
dbe9157c5ad08f06bb5eba7a2215892f3eef1abe | leetcode-notes/CSE20-Projects | /Assignment_1/Converter.py | 265 | 3.703125 | 4 | num = float(input())
if (num<1024):
print(num, " B")
elif (num>=1024 and num<(1024*1024)):
print(int(num/1024), " KB")
elif (num>=1024*1024 and num<(1024*1024*1024)):
print(int(num/(1024*1024)), " MB")
else:
print(int(num/(1024*1024*1024)), " GB")
|
49f433c6afc3afa42e7ce6bec9418def0613616e | minghuadev/minecraft-tests | /other-pygui/prog-py/generator-test3.py | 3,209 | 4.46875 | 4 | #!/usr/bin/env python
###################################################################
'''
this is almost a verbatim copy of itertools.product with only added
one more level of indirection when len(args)==1. this adds the ability
to pass args in a single tuble argument variable.
'''
def product(*args, **kwds):
... |
9037338250f4b9674a35275cbff33ac5f0b348d7 | tvonsosen/CAP-code | /lowToHigh.py | 268 | 4.09375 | 4 | # function that sums all the numbers from the lower bound number given to the higher bound number given (inclusively)
def lowHigh(lowB, highB):
answer1 = 0
for i in range(lowB,highB +1):
answer1 = answer1 + i
return answer1
print(lowHigh(-2,5))
|
a940c43f131cbf3625fa014687eaa1d5c4678811 | ivSaav/Programming-Fundamentals | /R09/budgeting.py | 668 | 3.609375 | 4 | '''
BUDGETING
'''
def sort_rule(x):
return x[1]
def budgeting(budget, products, wishlist):
# sorted product dictionary (descending order)
sort_prod = sorted(products.items(), key = sort_rule, reverse = True)
sort_p = dict(sort_prod)
price_list = list(sort_p.keys())
... |
fc86bc45f4aeb4ccfe156080a6c0970ebe7749cf | tadvepio/Object-Oriented-Programming | /Exercise5/Codefiles/student_mammal.py | 1,266 | 3.59375 | 4 | """
Created 8.2.2021
@File: student_mammal.py
@Description: Create a dictionary with studen object as key
and a pet mammal as value
@author: Tapio Koskinen
"""
# Import necessary modules
from mammal import Mammal
from student_class import Student
def main():
# Create a dictionary to hold mammal an... |
0a7afcfef3f80b8f51bb59daffef49e74cbbd3a7 | Akitektuo/University | /1st year/PF/Lab/Assignment2/complex.py | 1,785 | 4.3125 | 4 | import math
class Complex:
# Init block
def __init__(self, real = 0, imaginary = 0):
self.real = real
self.imaginary = imaginary
# Override str()
def __str__(self):
if self.imaginary == 0:
return self.format_float(self.real)
if self.real == 0:
... |
a6204b27e9e26637fd41b1433add8bcc2fa92312 | measlesbagel/isa-281 | /HW1/Cagle-Myles-HW1-Q2.py | 409 | 3.984375 | 4 | #Cagle-Myles-HW
food = float(input("Enter the cost of food "))
tip = float(input("Enter the amount tipped: "))
ratio = (tip/food)*100
if(ratio < 10):
print("You only tipped",round(ratio,2),"% please tip better next time.")
elif(ratio >= 10 and ratio <= 20):
print("You tipped",round(ratio,),"% thats perfect keep... |
9704d9e459111b7c66b56f9b66c9148e301e9370 | rporumalla/Interview_Programming_Practice | /binarySearch.py | 524 | 3.828125 | 4 | # O(log n)
def binarySearch(myList,x):
myList=sorted(myList)
low=0
high=len(myList)-1
while True:
if low>high:
return -1
mid=low+(high-low)/2
if x<myList[mid]:
high=mid-1
elif x>myList[mid]:
low=mid+1
else:
return mid
lst=[10,14,19,26,27,31,33,35,42,44]
idx=binarySea... |
110d1ac444411439845365cbddadb54c558606c5 | Tumle/Project1 | /search_file.py | 1,720 | 3.9375 | 4 | #http://www.opentechguides.com/how-to/article/python/59/files-containing-text.html
#Import os module
import os
import re
# Ask the user to enter string to search
search_path = raw_input("Enter directory path to search : ")
file_type = raw_input("File Type : ")
search_str = raw_input("Enter the search string : ")
# I... |
c53b2b897b1ba71f36247858d310f84447dc42c4 | nurlan5t/python-homeworks | /hw15_fibonacci recursion.py | 577 | 4.34375 | 4 | '''Написать Fibonacci sequence с помощью рекурсивного метода.
Пользователь вводит число(например 8) и программа
должна вывести числа Фибоначчи до 8.'''
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = int(input('Enter integer number: '))
if nterms <=... |
06a0d6b3714108cb35bb6ad3e7758e8353395b4e | alfonsoar/SpaceApps | /services/population_density.py | 1,320 | 3.65625 | 4 | import pandas as pd
import json
import constants
def readDataForPopulationDensity(populationFileName):
"""
Should only need to be run once to generate
json file with calculated population densities
"""
headers = ["city", "area", "populationCount"]
popFile = pd.read_csv(populationFileName, name... |
955dc45d6f6ce25fc05e78bfbea06125fb2fd783 | oguztimurtasdelen/PerformanceAnalysisTechnology | /driver.py | 9,401 | 3.84375 | 4 | """
Izmir University of Economics Faculty of Engineering
Project Name: Performance Analysis Technology
Lecture: FENG 498 - Graduation Project II
Supervisor: İlker KORKMAZ
Project Group: Ömer EROĞLU - Fatih KOCA - Oğuz Timur TAŞDELEN
"""
import csv # importing the csv module
import re # importing regex
import random ... |
a8f563cc2ee4ef7064a6d329d676963610243478 | Shivanshgarg-india/pythonprogramming-day4 | /class and object/questio 4.py | 468 | 4.125 | 4 | # Write a Python class named Student with two attributes student_id, student_name. Add a new attribute student_class. Create a function to display the entire attribute and their values in Student class
class Student:
student_id = 'V10'
student_name = 'Jacqueline Barnett'
def display():
print(f'... |
8552ba656127ae33182510c3d8a4a2870ecbe0ed | BrianS3-Git/day-2-3-excercise-time-left | /main.py | 383 | 3.796875 | 4 | # 🚨 Don't change the code below 👇
age = input("What is your current age? ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
age_as_int = int(age)
daysLeft = (90 - age_as_int) * 365
weeksLeft = (90 - age_as_int) * 52
monthsLeft = (90 - age_as_int) * 12
print(f"You have {daysLeft} days, {wee... |
682c691f9c955f6500e4a6a85978cb341ae16118 | mklsw/python-learning | /basic/output/print.py | 704 | 4.1875 | 4 | x = 7 **6
print (x)
a = 10 # int
b = 3.14 # float
c = 3 # int
d = a **2 # square of a
print (type(d)) #return the type of d
print (type(d//10)) # return the type of d/10
print (type(a/b)) # return the type of a/b
print (type(a/c)) # return the type of a/c
print (type(b*d)) # return the type of b*d
x = 7 **6
... |
3feaf460ab4669f87971fba67339e027f1ff10cc | KennyMcD/Blackjack | /blackjack.py | 13,013 | 4.09375 | 4 | """
@author: Kenneth McDonnell
"""
import random
# Dictionary for card values
cardVal = {
'A': 11,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'J': 10,
'Q': 10,
'K': 10
}
MAX_CARDS =... |
48ea4b5c6ba89b4e488b774579ab9d4fd201f8f3 | rvmoura96/distance-optimizer | /truck.py | 766 | 3.640625 | 4 | """Using Python 3.6."""
from cargo import Cargo
from haversine import haversine
class Truck:
def __init__(
self, truck: str, city: str, state: str, lat: float, lng: float
) -> None:
self.truck = truck
self.city = city
self.state = state
self.lat = lat
self.long... |
45d408c1bf1c8a71dce2e531d58ee795d6ab21b2 | neilpelow/Security | /vigenere.py | 907 | 3.890625 | 4 | from itertools import cycle
ALPHA = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.1234567890'
myKey = "FACEBOOKPASSWORD"
myText = "Yhwvtroi, 28 Yuqa 2016"
def encrypt(key, plaintext):
"""Encrypt the string and return the ciphertext"""
pairs = zip(plaintext, cycle(key))
result = ''
for pai... |
e31f0f77128d8c672486570f1f445eba9f8fc7c6 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4005/codes/1590_1446.py | 259 | 3.78125 | 4 | # Teste seu codigo aos poucos.
var = input("litros:")
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
d= float(var)/3
restante = round(d,3)
print(restante)
|
4b5b879655f95e253d7e3a12f20cf86b35929407 | jbelke/catalyst | /catalyst/examples/simple_universe.py | 6,176 | 3.53125 | 4 | """
Requires Catalyst version 0.3.0 or above
Tested on Catalyst version 0.3.3
These example aims to provide and easy way for users to learn how to collect data from the different exchanges.
You simply need to specify the exchange and the market that you want to focus on.
You will all see how to create a universe and f... |
ef723bbff557577e369c0342db99af5912fcbf28 | thatguy0999/PythonCodes | /Python2/Ex50.py | 582 | 4.0625 | 4 | from math import sqrt
a = float(input('what will be the value of a '))
b = float(input('what will be the value of b '))
c = float(input('what will be the value of c '))
no_roots = (b**2)-(4*a*c)
if no_roots < 0:
print('there are no intersections with the x axis')
elif no_roots == 0:
print('there is a repeate... |
68308b935782c09d34cf1e2457da6d42a815d549 | MozartArthur/Programming-3-4-5-6 | /Тема 8. Встроенные коллекции/ВСР.py | 1,614 | 4.21875 | 4 | # Создание программы, позволяющей выполнять основные операции (объединение, пересечение, вычитание) над множествами (количество множеств и их элементы вводятся вручную)
def set_array(count: int):
i = 1
arrays = []
while i <= count:
a = input("Введите множество " + str(i) + ": ")
a = ... |
0e2c2d0ed852a4a94d4fab12a020515b6a6c486e | erinspace/NightSkyNetwork | /NsN_project.py | 826 | 4 | 4 | requesters = {'Erin': 3, 'Mary': 5, 'Sue':1, 'Frank': 2}
MAXIMUM_REQUESTS = 5
def show_requesters():
for name, request in requesters.items():
print '{0:5} has requested {1:5d}'.format(name, request)
def new_entry():
new_name = raw_input('Please enter your name: ')
new_request = int(raw_input('Enter a number of ... |
c93b87e7a6b5d95292d4ebc28b23fe7904a55a68 | vo-andrew/interview-prep | /epi/5.5.py | 1,111 | 4.03125 | 4 | """
Delete Duplicates From A Sorted Array
Input:
A sorted array with duplicate values.
Output:
An array with the duplicate values removed.
"""
def solution(A):
"""
We want to overwrite duplicate values with new values that we see in one pass.
"""
available = 1
for i in range(1, len(A)... |
8fc898c47a3fb1e427a8278c550f8e7859593707 | sohannaik7/python-fun-logic-programs- | /fun_with_dates.py | 975 | 4.15625 | 4 | from datetime import datetime
def checkdate(date):
monthNames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
month, day, year = date.split('/')
if int(year) % 4 == 0 or int(year) % 400 == 0:
print("This ",year, "is a leap year")
else:
print... |
993b3423859cc6016ef1af0463891f4fdf1a89f7 | tkazusa/TDD-python-practice | /chapter05/money/franc.py | 274 | 3.703125 | 4 | class Franc(object):
""" franc class"""
def __init__(self, amount: int):
self._amount = amount
def times(self, multiplier: int):
return Franc(self._amount * multiplier)
def __eq__(self, other):
return self._amount == other._amount
|
4983c1571119d44f8bade6b9d7fd877ae4a96d97 | Nurdilin/cryptography | /nullCipher/nullCipher_decode.py | 624 | 3.90625 | 4 | #!/usr/bin/python
# Decode Null Cipher
def decode(encryptedText, charPosition):
decodedText = ""
for word in encryptedText.split():
if (word[charPosition] >= 'A' and word[charPosition] <= 'Z') or (word[charPosition] >= 'a' and word[charPosition] <= 'z'):
decodedText += word[charPosition]
return decodedTex... |
ca9b04c06bdf1d8ef0b18ec70b976de06da78327 | htostes/hello-world | /CursoEmVideoPython/Desafio092.py | 501 | 3.765625 | 4 | from datetime import date
pessoa = {'nome': str(input('Nome: ').strip()),
'idade': date.today().year-int(input('Ano de nascimento: ')),
'CTPS': int(input('CTPS (Só números): '))}
if pessoa['CTPS'] != 0:
pessoa['contratacao'] = int(input('Ano de contratação: '))
pessoa['salario'] = int(input(... |
2ebbb8450eea8134d6fa09738d44c1acfb092ad8 | FelipeGabrielAmado/Uri-Problems | /Iniciantes/1065.py | 116 | 3.6875 | 4 | par = int(0)
for x in range(1, 6):
A = int(input())
if (A%2 == 0):
par += 1
print("%d valores pares" %par)
|
435c49090f8b6f6902623521c4905f93c085f127 | sebastian011511/Blackjack | /BlackJack.py | 7,737 | 4.0625 | 4 | """
Sebastian Vasco
This program allows the user to play the game of blackjack to a very limited extent
Fall 2017
"""
# Todo: Change minimum from 100 to 1000
from tkinter import *
import tkinter.messagebox as box
import random
total_made_lost=0
def PlayGame():
# () rather than [] makes array immutable
fac... |
78050a6ab7fb76e3d6da51cd0a524a5cb072792a | thatsmysky/Python-Program-Five | /PROGRAM 5 CODE.py | 3,393 | 4.0625 | 4 | import csv
def try_open(file):
try:
opening_file = open(file, 'r')
return True
except IOError:
print("I'm sorry, that file cannot be opened, please try again.")
except:
print("Please try again")
def try_output(file):
try:
opening_file = open(file, 'a')
r... |
42651a49b6736aa10e816758c106c77594e064a9 | ishantk/PythonDec5 | /venv/Session2.py | 1,017 | 4.1875 | 4 | """num1 = int(input("Enter Number1"))
num2 = int(input("Enter Number2"))
# Arithmetic : +, -, *, /, %
num3 = num1 % num2
print(num3)
"""
age = 2
gender = "M"
# Conditional : >, <, >=, <= == !=
print(age>18)
# Logical : and or not
print(age>18 and gender=="M")
num1 = 8 # 1 0 0 0
num2 = 10 ... |
ba6b98385356750c318a5b6378234980c374ec21 | lucafrance/practice-python-solutions | /es02/es2.py | 300 | 4.125 | 4 | num = int(input("What's the number to check? "))
check = int(input("What's the number to divide by? "))
if num % 4 == 0:
print("It's a multiple of 4! :)")
elif num % check == 0:
print(str(num) + " is divisible by " + str(check))
else:
print(str(num) + " ain't divisible by " + str(check)) |
a31e24f73bce97d906d859027c7957810c774b05 | mariaprandt/Bioinformatica | /ProjetoAtividade2/teste.py | 240 | 3.765625 | 4 | linha = list()
for c in range(1,6):
for i in range (1,c+1):
linha.append(c*i)
print(f'{linha}')
linha.clear()
print('\n')
for j in range(1,6):
for b in range (1,j+1):
print(f'{j*b}', end=' ')
print('') |
f82f92d70a5916240fd28eb1d53163815de71e78 | xaohuihui/algorithm_study | /tree/binary_tree_traversal.py | 2,671 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# @Author : xaohuihui
# @Time : 19-12-19 上午9:59
# @File : binary_tree_traversal.py
# Software : algorithm_study
"""
二叉树遍历,pre_order(先序遍历)、in_order(中序遍历)、post_order(后续遍历)、breadth_first_search(广度优先遍历)、depth_first_search(深度优先遍历)
"""
import collections
class TreeNode:
def __init__... |
09f15bc88cbd77bb37cb313623ad4a19b0b067b5 | wmillar/ProjectEuler | /057.py | 996 | 4.09375 | 4 | '''
It is possible to show that the square root of two can be expressed as an
infinite continued fraction.
2^.5 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1... |
3a1e97fac6f009f79c0963dcfe7bf61b8dbc87d6 | pavanq/Practice | /python_assessment/q8.py | 320 | 3.953125 | 4 | class Point:
def __init__(self, x, y ):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Point(x,y)
p1=Point(2,3)
p2=Point(1,4)
print (p1+p2)
|
360699b859201a3a67c5087e2a80affda6933870 | prajakta401/UdemyTraining | /venv/Lect51 Box and Violin Plot.py | 1,439 | 3.890625 | 4 | #Lecture 53 Heat map and Clustered Matrixes
import numpy as np
import pandas as pd
from numpy.random import randn
# from pandas import Series,DataFrame
import matplotlib as mpl
import matplotlib.pyplot as plt#plotting
import seaborn as sns#
from scipy import stats# for stats
flight_dframe = sns.load_dataset('flights')... |
2f8ab557be71db1cc40cd15b175155116ee3ce86 | NUsav77/Python-Exercises | /Crash Course/Chapter 6 - Dictionaries/6.7_people.py | 1,056 | 4.625 | 5 | """Start with the program you wrote for Exercise 6-1. Make two new dictionaries representing different people,
and store all three dictionaries in a list called people. Loop through your list of people. As you loop through the
list, print everything you know about each person. """
pa_xiong = {
'first_name': 'pa',
... |
8a9ccd254ebf8c79aa19b651711d41fa882dd474 | Iso-luo/python-assignment | /practice/Ch8_Strings/1.py | 551 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time: 2020-05-06 8:41 a.m.
import math
#
# def theta(m1, m2, r):
# a = -3 * math.pi * (r ** 3)
# b = math.sqrt((m1 * m2) / (2 * (r ** 2)))
# c = math.log10((3 * m1) / (4 * m2))
# d = math.exp(math.tan(r))
# print(a * b * c * d)
def theta(m1, m2... |
575da21a38ff2e09c6ed5cf34348c92a1dfaa5e7 | HBinhCT/Q-project | /hackerrank/Algorithms/Matrix Layer Rotation/solution.py | 1,763 | 3.546875 | 4 | #!/bin/python3
# Complete the matrixRotation function below.
def matrixRotation(matrix, r):
height = len(matrix)
width = len(matrix[0])
for i in range(min(height // 2, width // 2)):
state = []
# top-left to top-right
for j in range(i, width - i):
state.append(matrix[i][... |
005056754b1b097f33d0bad87340b8461f7802bb | yiranzhimo/Python-Practice | /Day-1_3.py | 163 | 3.703125 | 4 | num=int(input("请输入您的数字:"))
dic=dict()
if num<=0:
print("输入不规范!")
for i in range(1,num+1):
if i>0:
dic[i]=i*i
print(dic) |
9b693f85a3183584799f39119225beaddc8fcd10 | robpalacios1/holbertonschool-higher_level_programming | /0x0A-python-inheritance/7-base_geometry.py | 810 | 3.625 | 4 | #!/usr/bin/python3
'''Same class or inherit from module'''
class BaseGeometry():
'''empty class BaseGeometry'''
pass
def area(self):
'''that raises an Exception with the message area()
is not implemented
'''
raise Exception("area() is not implemented")
def integer_... |
9995fb26b93dd92f9c18f4d5d1edef4eaac39d3a | EachenKuang/LeetCode | /code/98#Validate Binary Search Tree.py | 3,204 | 4.09375 | 4 | # https://leetcode.com/problems/validate-binary-search-tree/
"""
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys gr... |
62212db6d6a9139e24f8cb567c9ae58d5b44951f | Stefanh18/python_projects | /mimir/assingnment_4/q8.py | 170 | 3.828125 | 4 | stars = int(input("Max number of stars: ")) # Do not change this line
for x in range(1, stars + 1):
print("*" * x)
for x in range(stars-1, 0, -1):
print("*" * x) |
bda2dba98d0c4ff7bddd8239bbe4c0736cbc25e3 | amzn/differential-privacy-bayesian-optimization | /experiments/output_perturbation/scikit-learn/examples/linear_model/plot_polynomial_interpolation.py | 2,070 | 4.15625 | 4 | #!/usr/bin/env python
"""
========================
Polynomial interpolation
========================
This example demonstrates how to approximate a function with a polynomial of
degree n_degree by using ridge regression. Concretely, from n_samples 1d
points, it suffices to build the Vandermonde matrix, which is n_samp... |
cbcefe68790b74d3f62266cf29c9a5945b428c9c | smohapatra1/scripting | /python/practice/start_again/2021/02222021/factors_of_a_num.py | 344 | 4.0625 | 4 | # Find the factors of a number
def main():
n = int(input("Enter a number "))
i = 1
a = []
while i <=n:
if n % i == 0 :
#print ("The Factors are %d for num %d" % (i, n))
a.append(i)
i +=1
print ("The factors are %s for num %d " %(a, n))
if __name__ =... |
e51605eefe682f35632253ee38a7d53c17b7772e | medesiv/ds_algo | /sorting_and_searching/qsort.py | 841 | 3.890625 | 4 | """
implement qsort
[10,7,5,3,8,9]
10 7 5 3 8 9
"""
import random
def qsort(arr):
return helper(arr,0,len(arr)-1)
def helper(arr,s,e):
#if len is <2 or if s>=e to check arr size is 0 or 1
if s>=e:
return
#select a random number as pivot
p_indx = random.randint(s,e)
#swap pivot wi... |
59b99ffe2e96be588a73ccd7866ac53c019da414 | srinujammu/Python | /Types and Values/2 Numbers.py | 173 | 3.734375 | 4 | from decimal import *
x= .1+ .1 + .1 - .3
print('x is {}'.format(x)) # it is wrong
a = Decimal('.10')
b = Decimal('.30')
y = a+a+a-b
print('y is {}'.format(y))
|
603fa0ebe855042a232de283ab803b4c717f2391 | emhhd7/python-rpg | /rpg-01.py | 2,500 | 3.765625 | 4 | class Character():
def __init__(self, name, health, power):
self.name = name
self.health = health
self.power = power
def alive(self):
if self.health > 0:
return True
def print_status(self):
return "%s has %d health and %d power." % (self.name, self.healt... |
c8ab8046b8179e3f71ccf668bbcbfd883119bf9a | southpawgeek/perlweeklychallenge-club | /challenge-118/cristian-heredia/python/ch-1.py | 624 | 4.09375 | 4 | '''
TASK #1 › Binary Palindrome
Submitted by: Mohammad S Anwar
You are given a positive integer $N.
Write a script to find out if the binary representation of the given integer is Palindrome. Print 1 if it is otherwise 0.
Example
Input: $N = 5
Output: 1 as binary repr... |
7c21d83a825f8c5670669101a64587f71de8d5a1 | itminsu/Python | /Assignment#2/asd.py | 3,230 | 3.8125 | 4 | __author__ = 'Minsu Lee'
#Declare random
import random
dice1=random.randint(1,6)
dice2=random.randint(1,6)
dice3=random.randint(1,6)
dice4=random.randint(1,6)
dice5=random.randint(1,6)
#Declare Variable to determine the number
amountOfOne = 0
amountOfTwo = 0
amountOfThree = 0
amountOfFour = 0
amountOfFive = 0
amountO... |
4e23316f462bf8b25e0071c19a0fb2fa57f060ab | alexp01/trainings | /Python/6_Advance_Python_development/607_Timezones/app.py | 546 | 4.1875 | 4 |
# https://www.udemy.com/course/the-complete-python-course/learn/lecture/9477766#questions
# https://www.udemy.com/course/the-complete-python-course/learn/lecture/9477768#questions
from datetime import datetime,timezone, timedelta
now = datetime.now(timezone.utc)
print(now)
tomorrow = now + timedelta(days=2)
print(to... |
5f9630b23f4c248e57b2bbf8c27ac451c519da44 | loc-dev/CursoEmVideo-Python | /Fase07/Desafios/Desafio_11.py | 310 | 3.9375 | 4 | # Fase 07 - Operadores Aritméticos
# Desafio 11
# Crie um programa que leia quanto dinheiro
# uma pessoa tem na carteira e mostre quantos
# dólares ela pode comprar.
dolar = 5.65
saldo = float(input('Quantos reais você tem na carteira? '))
print('Posso comprar US${:.2f}'.format(saldo * dolar))
|
32d3e02d6c05d23d7dd766e885ec6effee357385 | SR0-ALPHA1/hackerrank-tasks | /list_reverse.py | 260 | 3.890625 | 4 | """
Task: Implement List.reverse()
"""
def reverse(lst):
for i in xrange(int(len(lst)/2)):
tmp = lst[i]
lst[i] = lst[len(lst)-1-i]
lst[len(lst)-1-i] = tmp
return lst
l = ['q','w','e','a','s','d','f']
print l
print reverse(l)
|
fd18ca72054c6440837b9bf218ee40fdec403af9 | MarcosLazarin/Curso-de-Python | /ex070.py | 1,007 | 3.875 | 4 | # Fazer um programa que leia o nome e o preço de vários produtos.
# O programa deverá perguntar se quer continuar.
# No final, mostre:
# Qual é o total gasto na compra.
# Quantos produtos custam mais de R$100,00 reais.
# Qual é o nome do produto mais barato.
totalgasto = maiorque100 = ma = me = c = 0
while True:
n... |
661e3167420f104c7b52190d025139f265300630 | anshusolar/antenna_modelling_data_processing | /package_common_modules/find_line_in_text_file.py | 499 | 4.15625 | 4 | '''
'''
# *** Find_line finds a line in .txt file which contains 'needed_text' ***
# needed_text - text to find
# start_char - number of character where the needed_text starts in line
# line - returns a text line from the file with needed_text
def find_line_in_text_file (file_handle, needed_text, start_cha... |
3f16dd3adfd7ca566615be964afd52f41701c29f | ironmanvim/coding_interview_questions | /19_sep_2020/1-2.py | 1,235 | 3.8125 | 4 | # Definition for singly-linked list.
class ListNode (object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2, c=0):
# Fill this in.
result = ListNode(c)
if l1 and l2:
result.val += l1.val + l2.val
... |
c1442d0eeb7e59d405ec7d154b3fe3cc72b55e55 | deroahe/Project-Euler | /Problem 7/euler.py | 461 | 3.953125 | 4 | # What is the 10 001st prime number?
import math
def prime(n):
if (n < 2):
return 0
if (n != 2 and n % 2 == 0):
return 0
x = math.floor(math.sqrt(n))
for d in range (3, x + 1, 2):
if (n % d == 0):
return 0
return 1
if __name__ ... |
8570cac15e7c9aee219188af258f1f23eec12090 | yanfriend/python-practice | /licode/st45.py | 463 | 3.609375 | 4 | class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret=0
max_reach=0
i=0
while max_reach<len(nums)-1:
next_reach=max_reach
while i<=max_reach:
next_reach=max(next_reach,i+num... |
dcc1b912188ccdf1f13f042d4c713cf6994a21a7 | sixiangxz/Python | /python算法/算法/排序/选择排序.py | 624 | 3.578125 | 4 | # 选择排序 O(n*n)
def select_sort(lis):
for i in range(len(lis)-1):
# 假如lis_min为list无序区最小数的下标,默认为第一个数
lis_min = i
# i之前为有序区,i之后为无序区,通过循环找到无序列表最小值然后获取下标
for j in range(i, len(lis)):
if lis[j] < lis[lis_min]:
lis_min = j
# 找到比lis_min还小的值,并交换这个值
... |
05bfe4ebc216f2cbd8947a08da89ab18904ec6b6 | scasica0/FTPDemo-client-server- | /cli.py | 9,458 | 3.75 | 4 | # *****************************************************
# Description: Client for FTP server
# *****************************************************
import socket
import sys
import commands
import os
def get_function(clientSocket,host,port,fileName):
# Send get command
sendMsg (clientSocket, "get")
# ... |
3cb1840b453d6aab58323676075f10fd442ed60b | batuhand/LYK17 | /class_ageOf.py | 1,100 | 3.515625 | 4 | class insanlar():
def __init__(self,mevki = "isci",saldirigucu=50,savunmagucu=10,kalancan=120):
self.mevki = mevki
self.saldirigucu = saldirigucu
self.savunmagucu = savunmagucu
self.kalancan = kalancan
def durum(self):
print("Bu insan bir ",self.mevki,". Saldırı gücü : "... |
4127ba34e97dca9d7638d10cdb7f54f58deb16cd | sobriquette/interview-practice-problems | /Project Euler/nthFibonacci.py | 1,011 | 4.125 | 4 | # Print the nth number in the Fibonacci Sequence
# Approach 1: iterative, space optimized
def fibIterative(n):
n1, n2 = 0, 1
if n < 0:
return "Input is incorrect"
elif n == 1:
return n1
elif n == 2:
return n2
else:
for i in range(2,n):
n1, n2 = n2, n1 + n2
return n2
# Runtime: O(n)
# Space: O(1)
#... |
aa0016970bf263752a47c6c88b6dab48cff77e65 | Cherry232/Python | /Print.py | 732 | 4.03125 | 4 | print ("Hoi ik ben Kirsten en hier komt weer een nieuwe tekening met mijn geliefde turtle ik hoop dat jullie hem leuk vinden!")
import turtle
Jurjen = turtle.Turtle()
Jurjen.speed(50)
Jurjen.shape("turtle")
Jurjen.color("red")
Jurjen.penup()
Jurjen.forward(500)
Jurjen.pendown()
for i in range(5,106,3):
Jurjen.fo... |
ea6fbbe3f700fafaba182bdf3bd731e16c4299ee | Aasthaengg/IBMdataset | /Python_codes/p03433/s298100007.py | 71 | 3.5 | 4 | n=int(input())
a=int(input())
if a>=n%500:print("Yes")
else:print("No") |
29ec583c4fa2eb5054dd3fe430495a0b5cb9c2e9 | chunamanh/PY4E-PythonForEveryOne | /python_codes/fibonacci.py | 294 | 4.1875 | 4 | # count the nth fibonacci number with dynamic programming (Quy hoach dong)
# Fibonacci: 1 1 2 3 5 8 13 ...
def fibonacci(n):
result = [0] * (n + 1)
result[1] = 1
for i in range(2, n + 1):
result[i] = result[i - 1] + result[i - 2]
return result[n]
print(fibonacci(3)) |
eee6dd45fda2f7b47fc2c317c2162fb65c59fa20 | prc3333/Exercicios--de-Phyton- | /Exercicios mundo 1/ex078.py | 559 | 4.0625 | 4 | '''listnum = []
for c in range(0, 5):
listnum.append(int(input(f'Digite um valor para a posição {c}: ')))
print(f'você digitou os valores {listnum}')
print(f'O maior valor digitado foi:{max(listnum)}')
print(f'O menor valor digitado foi:{min(listnum)}')'''
lista = []
for c in range(0, 5):
lista.append(int(inpu... |
4769eabbeff25ae589352ee901815a4d32109b7b | Faethreck/Personal-Projects | /Random small projects/Tarea 8.py | 154 | 3.921875 | 4 | def sumDigits(numbers):
if numbers == 0:
return 0
else:
return numbers % 10 + sumDigits(int(numbers / 10))
print(sumDigits(345))
|
e456742dfe2e4e069f9f6e4bc7dae741e3d540b7 | nicklevin-zz/dailyprogrammer | /2016/10/10/KaprekarsRoutine.py | 972 | 3.640625 | 4 | def kaprekar(num) :
i = 0
while num not in [6174, 0] :
num = desc_digits(num) - asc_digits(num)
i += 1
return i
def breakdown_digits(num) :
digits = list(map(int, list(str(num))))
while len(digits) < 4 :
digits.append(0)
return digits
def largest_digit(num) :
return ... |
1654fe1de8b8ea919aa56352579a47074cc79442 | fifa007/Leetcode | /src/word_break.py | 692 | 4.0625 | 4 | #!/usr/bin/env python2.7
'''
Given a string s and a dictionary of words dict, determine
if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
'''
class Soluti... |
ef3088ca3dc9ac8fb170367952d49f97780eac05 | sairamprogramming/python_book1 | /chapter6/programming_exercises/exercise12.py | 1,561 | 4.5 | 4 | # Average Steps Taken
# Program to find the average steps taken per month.
def main():
# Opening the step file.
infile = open('steps.txt', 'r')
# Initalizing the month variable
month = 0
# Getting the average number of steps for each month.
while month < 12:
month += 1
print('... |
591f2b0da0584ba34d7e9d970320facfa31416ae | Akhilnazim/Problems | /leetcode/largest.py | 567 | 4.25 | 4 | #laargest number without using conditional operator
# Python3 program to Compute the minimum
# or maximum of two integers without
# branching
# Function to find minimum of x and y
def min(x, y):
return y ^ ((x ^ y) & -(x < y))
# Function to find maximum of x and y using xor operation
def max(x,... |
82c6d548a61eda542202376e76696196146a1156 | littleliona/leetcode | /medium/386.lexicographical_numbers.py | 448 | 3.578125 | 4 | class Solution:
def lexicalOrder(self, n):
"""
:type n: int
:rtype: List[int]
"""
result = []
stack = [1]
while stack:
y = stack.pop()
result.append(y)
if y < n and y % 10 < 9:
stack.append(y + 1)
... |
842d345067b288a27c2e8261616a088f0532c28a | NicoleGruber/Codility | /03-OddOccurrencesInArray.py | 1,906 | 4.34375 | 4 | '''Uma matriz não vazia A que consiste em N números inteiros é fornecida. A matriz contém um número ímpar de elementos e cada elemento da matriz pode ser emparelhado com outro elemento que tem o mesmo valor, exceto por um elemento que não é emparelhado.
Por exemplo, na matriz A, de modo que:
A [0] = 9 A [1] = 3 A [... |
4f2366209e0040815698ec2ac6b05c21ff657053 | czamoral2021/CEBD-1100-CODE-WINTER-2021 | /CZ_Exercises_class04/draw_triangle2.py | 441 | 3.796875 | 4 | # Isosceles triangle. Iso symmetrical triangle 3 lines only
# Triangle base size 5 starting with 1.
# initialize variables
v_triangle = 9
v_count = 1
v_string = ""
# v_triangle even => please enter an ODD base triangle and greater than 1
for y in range(1, int(v_triangle) + 1):
if v_count % 2 != 0:
v_str... |
8df442a6a2a65d90b499947957a6e736123bf10d | Filipo-Dev/Python_Lists_Prac | /dictionaries_set_generator_compre.py | 1,181 | 4.15625 | 4 | #Dictionary comprehensions
names = ['Brian', 'Seth', 'Peter', 'Philip', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
#print (zip(names, heros))
#I want a dict{'name': 'hero'} for each name, hero in zip(name, heros)
my_dict = {}
for name, hero in zip(names, heros):
my_dict[name] = he... |
ffb789d038f8973d77ac4f49da36a8e7e111d188 | fred112f/CS | /new2.py | 232 | 4.21875 | 4 | def vowel(word):
if word[0] in("a", "e", "i", "o", "u","æ","ø","å"):
return True
return False
word= input("Type a word: ")
if vowel(word):
print ("Starts with a vowel")
else:
print ("Does not start with a vowel")
|
23d3f3666e373f8a899991213356d9276a9489e2 | ldosen/Shiftease-server | /flaskApp/test.py | 1,322 | 3.5625 | 4 | import unittest
import main_algorithm
class TestMainAlgorithm(unittest.TestCase):
def setUp(self):
self.raw_availabilities = [0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0]
self.slots_to_fill = {
2019: {4: {23: {"9am": None, "10am": None}, 24: {"9am": None, "10am": None}}}}
self.max_slot... |
bd20cdad1017159f5fa5cfc3ec7d8f0639945888 | Rudyk-Iurii/hilel_test | /tests.py | 3,565 | 3.6875 | 4 | from functions import (
task1,
task2,
task3,
)
#task 1
print("\ntask 2:")
"""
1. Напишите код на python, который посчитает и выведет на экран количество единичек и их индексы в массиве:
[-1, 1, -2, -1, -2, 0, 2, -3, 2, -2, 0, -1, 1, -3, 0, 1, 2, -1, -3, -3]
"""
list = [-1, 1, -2, -1, -2, 0,... |
a34092ae5f77b3abdfc74574f4fc8ee8b4188236 | dev-arthur-g20r/how-to-code-together-using-python | /How to Code Together using Python/EVENT DRIVEN PYTHON/perimeteroftriangle.py | 355 | 4.125 | 4 | import os
def perimeterOfTriangle(a,b,c):
p = a + b + c
return p
print("Enter length of two sides and base to check perimeter of the triangle.")
base = float(input("Base: "))
side1 = float(input("Side 1: "))
side2 = float(input("Side 2: "))
perimeter = perimeterOfTriangle(side1,base,side2)
print("Perimeter of triangl... |
fddf2fb2aec4674c7d4f0aa6a6ffd345e6acc009 | pombredanne/dssp1 | /stack.py | 697 | 4.125 | 4 | # -*- coding: utf-8 -*-
import linked_list
class Stack(object):
"""
All operations on a stack are O(1)
"""
def __init__(self):
self.items = linked_list.DoublyLinkedList()
def push(self, value):
self.items.add_last(value)
def peek(self):
if not self.items.count:
... |
bea3e24654283e21e6b5dacca5dd5715547a182f | CandyDong/Algorithms | /String/string_easy.py | 867 | 4 | 4 | #############################################reverse string###################################
def reverseString(s):
result = ""
length = len(s)
i = length-1
while (i >= 0):
result += s[i]
i -= 1
return result
#############################################reverse string###################################
####... |
fa66d73ef53ffe6f221af8f735fe476a54cb0e9e | abostroem/AstronomicalData | /_build/jupyter_execute/04_select.py | 16,124 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Chapter 4
#
# This is the fourth in a series of notebooks related to astronomy data.
#
# As a running example, we are replicating parts of the analysis in a recent paper, "[Off the beaten path: Gaia reveals GD-1 stars outside of the main stream](https://arxiv.org/abs/1805.00... |
c035fcefec027a5b8e1c619b49d09c7c96cbc330 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-169-simple-length-converter.py | 1,245 | 4.34375 | 4 | '''
Your task is to complete the convert() function. It's purpose is to convert centimeters to inches
and vice versa. As simple as that sounds, there are some caveats:
convert():
The function will take value and fmt parameters:
value: must be an int or a float otherwise raise a TypeError
fmt: string containing either ... |
0ddfaaa3e78f7507cfa0cada48642f64e01c8789 | ximuwang/Python_Crash_Course | /Chap9_Classes/Practice/user_module.py | 1,010 | 3.921875 | 4 | # A user module
class Users():
'''A class representing users'''
def __init__(self, first, last, user_profile):
'''Initialize the users'''
self.first_name = first
self.last_name = last
self.user_profile = user_profile
self.login_attempts = 0
def describe_u... |
c84ec1c58774a4bd33d490e727f3d3233fad2d5d | HyeonJun97/Python_study | /Chapter06/Chapter6_pb2.py | 261 | 3.53125 | 4 | #Q6.2
def sumDigits(n):
sum=0
while n!=0:
sum+=n%10
n=n//10
return sum
def main():
a=eval(input("정수를 입력하세요: "))
print(a,"의 각 자릿수의 합은",sumDigits(a),"입니다.")
main() |
ffc206c03e989689c2b14043df6da47b2d7234ca | itizarsa/python-workouts | /reverseNumber.py | 241 | 4.40625 | 4 | #program to enter a number and print its reverse
number=int(input("Enter Number "))
reverse=0
i=0
while i<number:
last_num=number%10
reverse=(reverse*10)+last_num
number=number//10
print("The Reverse of numbers are", reverse) |
254b667fe980285a95e9c22cff6d38a6acede3dd | maxwell-martin/gaddis-python2018-projects | /magic_dates/magic_dates.py | 241 | 4.1875 | 4 | month = int(input("Enter the month (numeric): "))
day = int(input("Enter the day (numeric): "))
year = int(input("Enter a two digit year: "))
if month * day == year:
print("The date is magic.")
else:
print("The date is not magic.")
|
1bdde830ff3445ec16101fd5be187d186aa46a35 | epidersis/olymps | /705A/705A.py | 157 | 3.78125 | 4 | string = ['I hate that' if x % 2 == 0 else 'I love that' for x in range(int(input()))]
string[-1] = string[-1].replace('that', 'it')
print(' '.join(string))
|
caf0de2234614941d2affedac15427224e41ff96 | threemay/python3_study | /class/bicycile.py | 917 | 4 | 4 | class bicycle:
def __init__(self,name):
self.name = name
def run(self, km):
print(self.name,'has ride',km,'KM by legs')
class Ebicycle(bicycle):
volume = 0
def __init__(self,name):
super().__init__(name)
def Charge(self,vol):
Ebicycle.volume += vol
print(name,... |
1474321166a753e472e7e308abb997de2a53c2d3 | NMoro811/Battleship-Online-AI | /textbox_class.py | 5,243 | 3.640625 | 4 | '''
Contains the TextBox class
'''
import os
import pygame as game
game.init()
game.event.set_allowed([game.MOUSEBUTTONDOWN, game.KEYDOWN])
# TextBox design
inactive_color = game.Color("dark gray")
active_color = game.Color("black")
background_color = (0, 85, 128)
default_font = game.font.SysFont('Cambria'... |
da4d91057f6c3fa848fd7f5e3205277ad7a182d2 | vimallohani/LearningPython | /three_dry.py | 646 | 3.71875 | 4 | #Dry principle says do not repeat same lines.
#This is better version of exercise_three_eight_guessing_game
import random
rand=random.randint(1,100)
counter=1
gameover=False #just to make logic for a gammer point of view
while not gameover:
num=int(input("Please guess a number between 1 and 100 :"... |
ee438e3878a7fcf5ec6e2a0a9c0cd7f5166a8315 | saswatmohanty95/trainingassignments | /Python/Assessments/Day1/Dayofmonth.py | 524 | 4 | 4 | '''
a=input("Enter date in number dd:")
if int(a)%7==1:
print("Friday")
elif int(a)%7==2:
print("Saturday")
elif int(a)%7==3:
print("Sunday")
elif int(a)%7==4:
print("Monday")
elif int(a)%7==5:
print("Tuesday")
elif int(a)%7==6:
print("Wednesday")
elif int(a)%7==0:
print("Thursday")
'''
days=['Thursday','Frida... |
403a1bf5c865478b68e73ef361887aba8720474b | edu-athensoft/stem1401python_student | /py200325_python1/py200508/homework/stem1401_python_homework_12_max.py | 456 | 3.984375 | 4 | """
Quiz 6
"""
# 8.
matrix123 = [[1,2],[1,2],[1,2]]
print(matrix123[0])
print(matrix123[1])
print(matrix123[2])
# 9.
# 9.1
print("The dimensions of the box are {}, {}, {}".format("width: 30cm", "height: 20cm", "depth: 10cm"))
# 9.2
print("The dimensions of the box are {2}, {1}, {0}".format("depth: 10cm", "height: 20... |
cd99d21a5e6785a65eb0f2f17749eb28ff5fa385 | yoanschnee/Neural-Network | /yoannet/loss.py | 720 | 3.671875 | 4 | """
A loss function measures how good our predictions are
we can use this to adjust the parameters of our network
"""
from yoannet.tensor import Tensor
import numpy as np
class Loss:
def loss(self, predicted: Tensor, actual: Tensor) -> float:
raise NotImplementedError
def grad(self, predicted: Tensor... |
7a292b5a02f844649369413de53cd9170aac622d | jameswmccarty/AdventOfCode2015 | /day4.py | 1,512 | 4.0625 | 4 | #!/usr/bin/python
import hashlib
"""
--- Day 4: The Ideal Stocking Stuffer ---
Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.
To do this, he needs to find MD5 hashes which, in hexadecimal, start with at le... |
b8e3f5f3d87fd72ca2285c6be3337fccffaf19e4 | rashmiranganath/list-programs-python- | /min_max.py | 227 | 3.5 | 4 | def min(a):
i=0
min=list[i]
while i<len(list):
if list[i]<min:
min=list[i]
i=i+1
print min
j=0
max=list[j]
while j<len(list):
if list[j]>max:
max=list[j]
j=j+1
print max
list=[2,5,8,1,20,0]
min(list)
|
5da0894635c4aa2e418a9c8c3d142425cf7dbedb | handole/pythonthusiast-course | /Fundamental/denih/latihan1.py | 291 | 4.125 | 4 | names = ['Jep', 'Ger', 'Joll', 'Sam']
for name in names:
print('Hello there, ' + name)
print(' '.join(['Hello there,', name]))
print(', '.join(names))
who = 'Garyy'
how_many = 12
print(who, 'bought', how_many, 'apple today!')
print('{} bought apples today!'.format(who, how_many)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.