blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b01e5dee91494fdc9bfe68da40b6203e2a0a8cdf | cormachogan/python-snippets | /circle-pretty.py | 1,227 | 4.53125 | 5 | #!/usr/bin/python3
# Demo the use of `repr` and `str`
# If `__str__` is not present, python falls back to using `__repr__`
# This script can be run with and without `__str__` defined to compare the differences
# print uses `__str__` but python will fall back to using `__repr__` if it is not defined (useful for trouble... |
392889571b3603ead5d3f0f6f0af85ee948ac404 | ctc316/algorithm-python | /Lintcode/G_Practice/Tag_Hash/1103. Split Array into Subsequences Containing Continuous Elements.py | 892 | 3.5 | 4 | class Solution:
"""
@param nums: a list of integers
@return: return a boolean
"""
def isPossible(self, nums):
counts = {}
tails = {}
for num in nums:
counts[num] = counts[num] + 1 if num in counts else 1
for num in nums:
if counts[num] == 0:
... |
41b05ca209127b0285efa0be75bff1e15de80c0d | IagoRodrigues/PythonProjects | /orientacao_objeto/conta_4.py | 2,266 | 4 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite=1000.0):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
def extrato(self):
print("Saldo R${:.2f} do titular {}".format(self.__saldo, self.__titular))
def dep... |
abea49114a2a556353f2ecc4c5b206f03d6ad372 | EsdrasGrau/Courses | /Codewars/8 kyu/Area or Perimeter.py | 97 | 3.5625 | 4 | def area_or_perimeter(l, w):
if l == w:
return l**2
else:
return (l+w)*2
|
603c9fc81359f130fc6d353d8ab16342da3959bd | TTA0/Test | /ModuleRandom.py | 142 | 3.703125 | 4 | from random import *
n = randint(0,9)
x = input ("Choisir un nombre entre 0,9: ")
if n == x:
print("Bravo")
else:
print("Erreur")
|
2529846384f5f900fd3729c1a65b48da0aac9436 | SaimunJd/even_odd_cheacking | /Even_Odd_Cheack.py | 237 | 4.0625 | 4 | cheack=int(input("how many times you want to cheack? : "))
for i in range (cheack):
num=int(input("enter a number: "))
if(num<=1):
print("its not even nor odd")
elif(num%2==0):
print("its even")
else:
print("its odd")
|
d5214b079b76475c7f96865ad5d24a4eeea2b2b1 | twtrubiks/leetcode-python | /test_Number_of_1_Bits_191.py | 1,716 | 4.25 | 4 | import unittest
from Number_of_1_Bits_191 import Solution, SolutionBitOperations
"""
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the fun... |
dbb8345d2e01b65f70561dbce484405f7b3e5937 | haibinj/lecture_notes | /lecture_notes/file_operation.py | 825 | 3.75 | 4 |
# f = open("data.txt")
#print(f)
## run this file does not print.
#print(f.read())
#print(f.read(3))
## the good thing of python is that it can control the reading stream of a file.
#f = open("data.txt",'w')
#print(f)
## over-writing a file. 'w' open with write
with open("data2.txt",'w',encoding = 'utf-8... |
21e11c67c743ce8aadd997ab646577b41886c9f6 | ReganBell/QReview | /commentsearching.py | 4,348 | 3.53125 | 4 | '''
Matthew Beatty, Regan Bell, Akshay Saini
CS51 Final Project
Q Comment Summarization
4/22/15
'''
# Import modules
from nltk import tokenize
from nltk.tokenize import wordpunct_tokenize
import nltk
# Function for splitting string by specific delimiters
def tsplit(string, delimiters):
delimiters = tuple(delimi... |
4d6b82136c872fa5a731ef22d6fbd10768d1320a | StuartSpiegel/BlockChain | /BlockChain/BlockChain.py | 1,309 | 4.125 | 4 | # Stuart Spiegel, Date: 6/17/2019
#This Python class is an implementation of a Block Chain
#We must first define the class Block which is the most basic
#unit of the blockchains implementation.
#library to assign hashes to blocks(transactions)
import hashlib as hasher
class Block:
def __init__(self, index, timesta... |
6d06c9de15468f6c210a9119a3d077892c6ca515 | srillaert/project-euler | /p055.py | 377 | 3.546875 | 4 | result = 0
for number in range(1, 10000):
str_number = str(number)
str_reverse = str_number[::-1]
for iterations in range(1, 51):
number += int(str_reverse)
str_number = str(number)
str_reverse = str_number[::-1]
if str_number == str_reverse:
break # palindromic
... |
6bcf977f840aa45037055808ea923fe46230d7db | samuellsaraiva/2-Semestre | /l07e08calculadora.py | 2,182 | 4.65625 | 5 | ''' 8. Simule uma calculadora com as quatro operações aritméticas. Implemente uma
função para cada operação aritmética. Ela recebe dois valores e não retorna nada.
O usuário fornecerá a operação desejada(operador: +, -, x, / )
e os dois valores dentro do programa que chamará uma das quatro funções.
O resultado do c... |
6a4a94d806b5f2bda096505d28e3fea4fd635a69 | ziGFriedman/My_programs | /Intersection_of_lists.py | 762 | 3.9375 | 4 | '''Пересечение списков'''
# Даны два списка и необходимо найти их совпадающие элементы, то есть область
# пересечения списков - элементы, которые присутствуют в обоих списках.
a = [5, [1, 2], 2, 'r', 4, 'ee', 'ee']
b = [4, 'we', 'ee', 3, [1, 2]]
c = []
for i in a:
if i in c:
continue
for j in b:
... |
f8d098daf899f69b4f9454d1110970c21a314797 | vemanand/pythonprograms | /general/json1.py | 1,040 | 4.125 | 4 | '''
Python has a built-in package called json, which can be used to work with JSON data.
you can parse JSON string by using the json.loads(<string>) method. This returns a Python dictionary
you can convert Python object into a JSON string by using the json.dumps(<object>) method. This returns a Json string
The qualifie... |
0e9f1d9ca7153e86b5bf6635135bb755d8608474 | gokou00/python_programming_challenges | /coderbyte/PrimeChecker.py | 733 | 3.671875 | 4 | import itertools
def PrimeChecker(num):
prime = []
prime.append(2)
prime.append(3)
isPrime = True
# generate list of primes
for i in range(4,1000):
for j in range(2,i):
if i % j == 0:
isPrime = False
break
if isPrime:
... |
70057d60c837bc6df80fdba4b95e01c4d1ac8139 | bimri/learning-python | /chapter_30/attributeaccess.py | 1,463 | 3.9375 | 4 | "Attribute Access: __getattr__ and __setattr__"
"""
classes can also intercept basic attribute access (a.k.a. qualification) when
needed or useful. Specifically, for an object created from a class, the dot operator expression
object.attribute can be implemented by your code too, for reference, assignment,
and deletion ... |
56aabdb3b5031e860f862c510d366e586c354164 | sriharshadv8811/sriharsha-python-programs | /python program if file 1.py | 94 | 3.96875 | 4 | num=7
if num > 0:
print(num,"is a positive number.")
print("this is always printed.")
|
7525b2e4e59d4beae889c47e416d8ec9252c1ac4 | Didden91/PythonCourse1 | /Week 8/8_4.py | 218 | 3.640625 | 4 | fhand = open('romeo.txt')
finallist = list()
for line in fhand:
words = line.split()
for word in words:
if word in finallist: continue
finallist.append(word)
finallist.sort()
print(finallist)
|
e38595c02b857e785e18399f7e7c803e2673c49d | Jayhello/python_utils | /python_utils/numpy_operate/arr_sort.py | 1,561 | 3.9375 | 4 | # _*_ coding:utf-8 _*_
import numpy as np
def arr_arg_sort():
arr = np.random.permutation(3 * 4).reshape(3, 4)
np.random.shuffle(arr)
print arr
arr_sort_idx = np.argsort(arr) # default sort by row
print arr_sort_idx
# print np.array(arr)[arr_sort_idx] # does not apply to mul-dim array
arr... |
8ec09ec82a1bf67569dca53bdcab4d10389692c2 | 0ushany/learning | /python/python-crash-course/code/4_operate_list/pratice/7_3_multiple.py | 161 | 4.1875 | 4 | # 3的倍数
# 创建3的倍数列表,输出
multiples = list(range(3, 31, 3))
for mul in multiples:
print(mul)
# 很简单,每次加3就是3的倍数
|
0ca1bd76c5b4e2dfa7151460d92eeeacb3171cee | guruguha/Python_Exercises | /percentages.py | 1,577 | 4 | 4 | __author__ = 'Guruguha'
# Percentages
num_of_students = int(input())
if num_of_students < 2 or num_of_students > 10:
print("Enter valid number of students")
else:
count = num_of_students
student_data = []
valid_input = True
while count != 0:
values = input()
input_list = values.spl... |
e69b96228c4cb48e424bf63831a18603f2cead65 | BlakeLewis1/python | /QA python/grade calculator.py | 580 | 4.125 | 4 | #learning python
#grade calculator code
physics =int(input("enter your physics mark"))
chemistry =int(input("enter your chemistry mark"))
maths =int(input("enter your maths mark"))
total = (physics + chemistry + maths)
percentage =(total/300 * 100)
print ("you got", percentage)
if percentage < 40:
print("try aga... |
7ae1514279d960fbdfb3eac64cca0fa67ab25170 | sherifsoliman61/HOMEWORKS | /Homework 3.py | 1,166 | 3.859375 | 4 | combination = "SSNWES"
stepCounter = 0
lifeCounter = 3
game = True
class LostLife:
if stepCounter == 10:
lifeCounter - 1
stepCounter = 0
class LifeCheck:
if lifeCounter == 0:
game = False
print("Game Over, try again")
while game:
print("You have entered the Maze, where... |
c5c50cd3edf56792a37518e7f6ef1ec1cfaf37f7 | ntravis/codeeval | /stacking.py | 897 | 4.125 | 4 | """
STACK IMPLEMENTATION
CHALLENGE DESCRIPTION: Write a program which implements a stack interface for integers. The interface should have ‘push’
and ‘pop’ functions. Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer.
INPUT SAMPLE: Your program should accept a file as its firs... |
881f247867f9c3c3f5f7c65cbe0a5fe3fc2d3c3b | poc1673/Adaptive_Flashcards | /Adaptive_Flashcard/text_manipulation_functions.py | 798 | 3.6875 | 4 | # Peter Caya
# Function to take a corpus of words and output a list of sentences.
import pandas as pd
import re
#os.chdir("Dropbox/Projects/Adaptive Flash Cards/")
#a = pd.read_csv("Data/2019-11-24 Testing Data.csv",encoding = "ISO-8859-1",squeeze = True).x
def detect_periods(string):
return(string.find(... |
7fe8e4a75bd449de3e1cd46502eefd2965e778d8 | KGeetings/CMSC-115 | /In Class/TipOnMeal.py | 265 | 3.890625 | 4 | costOfMeal = float(input("How much did your meal cost? (before tax) "))
amountOfTip = float(input("What percentage do you want to tip? "))
the_tip = costOfMeal * amountOfTip / 100
the_tip = int(the_tip * 100) / 100
print("Add $", the_tip, " to your meal.",sep="") |
79815b2497f079613859927778355ad2744c6adb | MengLingXiao1/Python_study | /List_study2.py | 177 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# @Author : Mlx
a=[1,2,3]
b=a
a.append(5)
print a,b
#result [1, 2, 3, 5] [1, 2, 3, 5]
a=[1,2,3]
b=a
a=[4,5,6]
print a,b
#result [4, 5, 6] [1, 2, 3] |
38f8a378e3aa0671ef3418eb652edc5d9aa7ab04 | ditcraft/demo-repo | /demo.py | 486 | 3.671875 | 4 | # Python program to find the SHA-1 message digest of a file
# importing the hashlib module
import hashlib
def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
# make a hash object
h = hashlib.sha1()
# open file for reading in binary mode
with open(filenam... |
998827538d14387636739a997e4428a460a1497f | cocoa-dev-1/-- | /수업/list_1.py | 398 | 3.59375 | 4 | #def oddX3_evenX2(n):
# return n*2 if n%2==0 else n*3
#oddX3_evenX2 = lambda n: n*2 if n%2==0 else n*3
#print(oddX3_evenX2(5))
a_list = [i for i in range(10)]
print(a_list)
b_list = list(map(lambda n: n*2 if n%2==0 else n*3, a_list))
print(b_list)
c_list = [i for i in range(21)]
turnToMinus_list = list(map(la... |
1784b3a247a09ba99df831dc3144344a0eac2660 | NiranjanSingh/coding-localdrive | /python/tmp.py | 397 | 3.703125 | 4 | "fuctions"
def a():
x=0
y=3
print('hi shanoo'+ str(x) + str(y))
def b(x):
print('ihello')
x += 1
print(x)
# c('hello')
def c(name):
x=98
y=97
z = 32
print(x + y + z)
print(name)
print(a)
print(b)
print(c)
# print(a printm + "see yourself which is greater address ")
print('a>b ' + str(a>b))
print('b... |
5b23b367fb31330d763a9d1f6d2fe576a9c7d38c | Hyferion/Leetcode | /recursion/frog_jump.py | 273 | 3.828125 | 4 | cache = {0: 1, 1: 1}
def frogjump(feet):
if feet < 0:
return 0
if feet not in cache:
cache[feet] = frogjump(feet - 1) + frogjump(feet - 3) + frogjump(feet - 5)
return cache[feet]
else:
return cache[feet]
print(frogjump(111))
|
3095ae90505b89d27f2c64957c9f5eb91b456fd2 | kr4spy/PatchTuesday | /patchtuesday.py | 935 | 3.671875 | 4 | import datetime
import calendar
from datetime import timedelta
#set first weekday
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
####################
# Set this stuff #
####################
#set the year
year = 2020
#offset in days from patch Tuesday. 3 = Friday, 4 = Saturday, 5 = Sunday
offsetD... |
008c74e5288baf37c73a18a3c9a864da3c19a87a | Sam-Power/033_streamlit_model_deployment | /app.py | 5,943 | 3.546875 | 4 | #streamlit run app.py
import streamlit as st
import pandas as pd
import numpy as np
import altair as alt
# text/title
st.title("Streamlit Tutorial")
st.text("welcome !")
# header/subheader
st.header('This is a header')
st.subheader('This is a subheader')
#Markdownd
st.markdown('### This is a markdown')
st.markdown(... |
017917ce8a021ba517b04f76c6e84c2647a89905 | LittleFee/python-learning-note | /day01/homework-str.py | 1,677 | 4.40625 | 4 | #个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息
# name_1=input("Input your name please \n")
name_1="kiwi"
print("Hello "+name_1.title()+",How's your day")
#调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。
# name_2=input("Input your name please \n")
name_2="feng Yun xiA"
print(name_2.lower())
print(name_2.upper())
print(name_2.title(... |
b1e58b11ad9a741438c0e4a1f1c5551cd1e93564 | crobil/project | /Reverse_or_rotate.py | 1,397 | 3.90625 | 4 | """
The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz).
If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it ... |
b3ced8a1be7130c4d77deb2e7424858406c03c34 | dragonesse/aoc | /2017/day19.py | 2,465 | 3.90625 | 4 | import sys;
import re;
print("Day 16 puzzle: A Series of Tubes");
#read input
puzzle_file = "";
if(len(sys.argv) == 1):
print ("Please provide input file as argument!");
sys.exit();
else:
puzzle_file = sys.argv[1];
layout = [];
#open file
with open(puzzle_file, 'r') as puzzle_in:
for cur_line in puz... |
7dc645b64f870784303bcbb4a0380800ab055164 | damccorm/course-work | /big-data/dannymccormick3-homework-2/2_group.py | 1,410 | 3.515625 | 4 | from mrjob.job import MRJob
import json
'''
Count the screen name with the most tweets and its counts.
See http://mike.teczno.com/notes/streaming-data-from-twitter.html for parsing info.
Get the screen name by accessing tweet['user']['screen_name']
'''
class GroupMaxTweets(MRJob):
# The _ means the field does ... |
99631a755ff0f83c9dc6a34204a2ee5aec68d01c | ajanes780/pythonPractice | /fibonacci.py | 307 | 4.0625 | 4 | def fibonacci_number(num):
if num:
a = 0
b = 1
for i in range(num):
yield a
temp = a
a = b
b = temp + b
else:
return "Please Choose a number greater then 0"
my_list = [i for i in fibonacci_number(-1)]
print(my_list)
|
1357378aa2f9c1ba6587d46c27fed666eb684ab7 | unfit-raven/yolo-octo | /CST100 Object Oriented Software Development/Random Programs/distance_traveled.py | 836 | 4.375 | 4 | # Distance traveled calculator.
# Distance = Speed * Time
# Input validation - positive number for speed, and number greater than 1 for time.
speed = 0 # Priming read
while speed <= 0:
speed = eval(input("Please enter the speed of the vehicle in MPH: "))
if speed > 0: # Speed validation
print("Error.... |
c923dbc9fa163cbb2f653134be652bcb1637a481 | AbdohDev/Pyson | /auth/signup.py | 399 | 3.546875 | 4 | #creating a new user
from user import UserManager
from util.validations import username_signup
def Signup():
# is_valid = False
# username = ""
# password = ""
# message = ""
# user = None
print("I am in signup.py")
username = input("Please enter a username: ")
password = input("Please... |
fa2dab39ab441908fa3cbb13412d76e32a66c350 | jasdestiny0/Competitive-Coding | /Code_Asylums/dsa_bootcamp/array_questions/COUNT_PAIRS_IN_A_SORTED_ARRAY_WHOSE_SUMIS_LESS_THAN_X.py | 259 | 3.6875 | 4 | import math
def sum_less_than_x(arr, x):
n=1
for i in range(0, len(arr)-1):
if arr[i]+arr[i+1]> x:
break
n+=1
return int(math.factorial(n)/((math.factorial(n-2))*2)) if n>1 else 0
print(sum_less_than_x([1,2,3,4,5,6],7)) |
0472249edf7eb708f15463f94b50698e61059588 | djs1193/-w3r-esource | /exe10.py | 171 | 3.921875 | 4 | #finding sum of the type n + nn + nnn
def my_func(n):
ans = (n + (n +10*n) + (n+10*n +100*n))
print (ans)
val =int(input("enter the value of n: "))
my_func(val)
|
9a893ef66a4cdbfff3fefa8a9ed51e918bb02c3c | zhangying123456/python_basis | /Get请求.py | 209 | 3.796875 | 4 |
import random
def fn(x):
return x**2
result = []
for i in range(3):
t = random.randint(1, 10)
print (t)
r = fn(t)
result.append(r)
print (result)
value = eval(input())
print(value)
|
8c716f77b65b0d026d2d1599f4337613de4d42c4 | nai7/advanced-pat-python | /1023.py | 267 | 3.921875 | 4 | num = raw_input()
nums_before = {}
for n in num:
nums_before.setdefault(n, []).append(0)
num = str(2 * int(num))
nums_after = {}
for n in num:
nums_after.setdefault(n, []).append(0)
if nums_after == nums_before:
print 'Yes'
else:
print 'No'
print num |
d9a9b61a5c898f8a2b8b9c458eda66752ba69375 | littlebuddha16/pythonIsEasy | /Homework Assignment #7/dictionariesAndSets.py | 2,614 | 3.875 | 4 | """
Homework Assignment #7
Dictionaries and Sets
Favourite Song
Author: Kiran Kumar P V
"""
"""
Function to clear the terminal
1. OS module has functions which can be used to interact with underlying Operating System
2. Use system function to clear the terminal
3. Use os.name and "if block" to clear eithe... |
851680666916ebb8dc81d9c0d8f4a45aeb10e6e6 | jacobcrigby/Advent-of-Code-Python | /2019/day1.py | 2,294 | 3.734375 | 4 | """
--- Day 1: The Tyranny of the Rocket Equation ---
"""
import math
import unittest
class SpacecraftModule:
"""Generic module with mass
(Part 1)"""
def __init__(self, mass: int):
self.mass = mass
def required_fuel(self, mass: int = False) -> int:
if not mass:
mass... |
4249826c93f6d12b0c6a669ffecc6f7aef1b7568 | BorisovDima/_ex | /algoritms/Merge_sort.py | 1,480 | 3.546875 | 4 | from test_sort import test_sort
import random
# def merge_sort1(iterable):
# if len(iterable) <= 1:
# return iterable
# slice_ = len(iterable) // 2
# left = iterable[:slice_]
# right = iterable[slice_:]
# return merge(merge_sort(left), merge_sort(right))
#
# def merge(i1, i2):
# result ... |
529214716f22291fbf2ce63b56f969ab846e4693 | Baistan/FirstProject | /while_tasks/Задача2.py | 208 | 3.75 | 4 | num = int(input())
i = 2
while num % i != 0:
i += 1
print(i)
print("Конец Цикла")
# num = int(input())
# i = 0
# while i < num:
# i += 1
# print(i)
# print("Конец цикла") |
75cdef0cf035e8cae59855bc8119e664d9313b74 | WokasWokas/UserRegistation | /test.py | 4,869 | 3.640625 | 4 | import os
os.system("cls")
class Data:
users = []
class User(object):
def __init__(self, user: dict):
self.name = user.get("name")
self.exp = user.get("exp")
self.lvl = user.get("lvl")
self.maxExp = user.get("maxExp")
self.password = user.get("password")
... |
af8a6d8d777cfe57f4c603eec56de1b7663f4959 | freeland120/Algorithm_Practice | /CodingTest_Python/Programmers_MaxNumber.py | 243 | 3.640625 | 4 | ## 정렬 "가장 큰 수"
def solution(numbers):
numbers = list(map(str,numbers))
numbers.sort(key = lambda x : x*3, reverse=True)
return str(int(''.join(numbers)))
list1 = [6,10,2]
print(solution(list1))
|
ea0a780daa3aeeb758a20851b6071fffa336253e | itsarcanedave/Python-UDP-Chat | /Client.py | 1,445 | 3.8125 | 4 | import socket
import ipaddress
name = input ("Please enter your name: ")
print ("Hello", name, "!")
local = socket.gethostbyname(socket.gethostname())
print ("Your client IP address is", local)
ip = input ("Please enter server IP address: ")
ipaddress.ip_address(ip)
port = int(input ("Please enter port: "))
... |
636daccf700b752020c49b5c89ca5d4b5f8f020c | janam111/datastructures | /Matrix/Rotate Matrix Anti-clockwise.py | 396 | 3.546875 | 4 | from Common import inputMatrix
def rotateMatrix(arr):
m = len(arr)
n = len(arr[0])
res = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
for j in range(m):
res[n-i-1][j] = arr[j][i]
return res
arr = inputMatrix()
res = rotateMatrix(arr)
for i in range(len(res)):
... |
a139ba27746f9ba0771345ca2fae800ead384390 | yogesh1234567890/insight_python_assignment | /completed/Data40.py | 285 | 4.40625 | 4 | #40. Write a Python program to add an item in a tuple.
tups=(1,2,3,4,5,6,7,8)
lst=list(tups)
num=int(input("Enter the number of values you want to add in the tuple: "))
for i in range(num):
value=int(input('Enter the value: '))
lst.append(value)
out=tuple(lst)
print(out) |
d9b543efa56518a98fc46e9e1562c6e6a9250856 | ericdweise/quantum | /qiskit/myqiskit/circuits.py | 503 | 3.578125 | 4 | from qiskit import QuantumCircuit
def encode_int(number, bit_depth=8):
'''Encode an integer into a quantum circuit.'''
assert(isinstance(number, int))
assert(isinstance(bit_depth, int))
assert(bit_depth > 0)
assert(number >= 0)
assert(number <= 2**bit_depth - 1)
circuit = QuantumCircuit(b... |
83fc67e0b07a518da20886c2fb6bb1b8778529e2 | DamienOConnell/MIT-600.1x | /Week_1/str_involve.py | 373 | 3.984375 | 4 | #!/usr/bin/env python3
# 1 "string involved:"
varA = 4
varB = "adieu"
# 2 "string involved"
varA = hola, varB = hola
if (type(varA) == str) or (type(varB) == str):
print("string involved")
elif (type(varA) == int) and (type(varB) == int):
if varA > varB:
print("bigger")
elif varA == varB:
... |
353ef4c65295bda8a9ce55640b251f2795e7e43c | cfspoway/python101 | /Homework12/Sarah_Homework_12.py | 400 | 3.8125 | 4 | sentence = input('Please input a sentence')
length = len(sentence)
#print(length)
fc = 0 #first character
pos = 0 #position
print('The word list is:')
while pos < length:
if sentence[pos] == ' ':
if pos != fc:
print(sentence[fc:pos])
pos = pos + 1
fc = pos
el... |
cecc607c1374477df7c1f302ffadd5072decaf14 | kevinhan29/python_fundamentals | /10_testing/10_01_unittest.py | 585 | 4.3125 | 4 | '''
Demonstrate your knowledge of unittest by first creating a function with input parameters and a return value.
Once you have a function, write at least two tests for the function that use various assertions. The
test should pass.
Also include a test that does not pass.
'''
def Triple(val):
try:
temp ... |
e878b96101b3e4108246aa1d7a89c3cbe484f493 | isnakie/CMPS115 | /scatter.py | 5,573 | 3.671875 | 4 | """
Created on April 13, 2016
Reads a csv file containing stock market data and
shows and saves a plot of the trend line,
given optional starting and ending date information.
Call makeChart() with return value of readFile()
and a list of prices, e.g., ['Open','Close'].
@author: Johnnie Chang
"""
import argparse
import... |
1ae5e2dfa9b8416c0dab0a7eceacb82840210886 | grozhnev/yaal_examples | /Python+/Python3/src/module/builtins/exception/try_except_finally.py | 181 | 3.578125 | 4 | x = 0
try:
x = 1 / 0
except ZeroDivisionError as error:
print(error)
x = 2
except ValueError as error:
print(error)
x = -1
finally:
x = x * 3
assert x == 6
|
e6b6c32158aec03d8df1f4d4c33907b60151cf02 | famaf/Modelos_Simulacion_2016 | /Practico_04/ejercicio03.py | 2,044 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import random
import math
def esperanza(n):
"""
Calcula la esperanza con la Ley de los Grandes Numeros.
"""
N = 0 # Total de lanzamientos en los n experimentos
for _ in xrange(n):
RESULTADOS = range(2, 13) # Lista de resultados [2...12]
lanzamientos = 0 # ... |
34307b20bc490adc5353c9dec5b6f611754e20e3 | AhmedRaafat14/Solutions-Of-Cracking-the-Coding-Interview-Gayle-5th-Edition | /Chapter 1/1-2.py | 383 | 3.96875 | 4 | """
Implement a function void reverse(char* str) in C or C++ which reverses a null-
terminated string
"""
# Using python benefits =xD
def reverse_s(s):
return s[::-1]
# Using Naive solution
def reverse_s_naive(s):
new_s = ""
for ch in s:
new_s = ch + new_s
return new_s
if __name__ == "__ma... |
72ae950582dac0f0257ab91a8b0462b66c844e6a | asiasumo/pp3 | /python/zadanie23.py | 246 | 3.984375 | 4 | for x in range(1,51):
if x % 3 == 0 and x % 5 == 0:
print("BINGO")
elif x % 5 == 0 or x % 3 == 0:
if x % 5 == 0:
print("BAM")
elif x % 3 == 0 :
print("BIM")
else:
print(x)
|
7b82699ed776f635d4458105c0a222271dd0eeae | fabiano-palharini/python_codes | /2021_couting_valleys.py | 950 | 4.15625 | 4 | test_case_1 = 'UDUDDU'
expected_result_1 = 1
test_case_2 = 'UDDDUU'
expected_result_2 = 1
test_case_3 = 'UDUDUDDU'
expected_result_3 = 1
test_case_4 = 'UDUDDUDU'
expected_result_4 = 2
test_case_5 = 'DUDUDDUU'
expected_result_5 = 3
def count_valleys(sequence):
sea_level = 0
previous_sea_level = 0
number_of_... |
7cb5661cecccbfddc4491173e4a469774757ab4e | jackeown/PythonIsNotSlow | /naiveBenchmark.py | 655 | 3.5 | 4 | import sys
import random
def squareMatrixBenchmark(n):
m1 = [None] * (n**2)
m2 = [None] * (n**2)
m3 = [None] * (n**2)
for i in range(n):
for j in range(n):
m1[i*n + j] = random.random()
m2[i*n + j] = random.random()
for i in range(n):
for j in range(n):... |
e82be1c26a35e93b00c19e29175439e4589671ca | Wbeaching/Cryptanalysis-and-security-assessment-of-the-modern-symmetric-key-algorithms-using-neural-networks | /DataGen/Debug/Bits.py | 786 | 3.75 | 4 | def to_bits(s):
"""
Supports only string on input:
'Hi :D'
"""
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return result
def from_bits(bits):
"""
Supports only bits on input:
[1, 0, 1, 1, 0, 0, 1, 0]
"""
chars = []
for b ... |
8e019b2578512bb97305c2f3a8171eb645730701 | dkaisers/Project-Euler | /015/15.py | 362 | 3.96875 | 4 | import math
print("x by y")
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
def bico(x, y):
if y == x:
return 1
elif y == 1:
return x
elif y > x:
return 0
else:
a = math.factorial(x)
b = math.factorial(y)
c = math.factorial(x - y)
return (a // (b * c))
print("Number ... |
4ed12b5e973290a4694eb684a323007ff898dbd0 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/66_12.py | 2,497 | 3.671875 | 4 | Python – Mutiple Keys Grouped Summation
Sometimes, while working with Python records, we can have a problem in which,
we need to perform elements grouping based on multiple key equality, and also
summation of the grouped result of particular key. This kind of problem can
occur in application in data domains. ... |
20a0da08d9cfd3c8175b704b35aeae2314494bce | mjpmorse/CMU_ML | /HW/HW4/LR_PredictLabels.py | 757 | 3.59375 | 4 | # The matlab code translated is originally authored by Tom Mitchell
# Translated to python 3 by Michael J. P. Morse Sept. 2019
# Predict the labels for a test set using logistic regression
def predict_labels(x_test,y_test,w_hat):
import numpy as np
#get dimensions
num_row,num_col = np.shape(x_test)
... |
50cce03d831a18a36ebd15a20482412b9674fb54 | chaofan-zheng/python_learning_code | /leetcode/huawei/跳台阶.py | 668 | 3.640625 | 4 | """
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
只考虑最后一次的情况
"""
class Solution:
def jumpFloor(self, number):
# write code here
if number == 2:
return 2
if number == 1:
return 1
return self.jumpFloor(number - 1) + self.jumpFloor(number - 2)
c... |
bef8a58794b247476f87218047a776c187b1fc53 | BinceAlocious/python | /oops/inheritance/firstpgm.py | 194 | 3.59375 | 4 | class One:
def m1(self):
print("Inside Parent Method M1")
class Two(One): #Inheritence
def m2(self):
print("Inside Child Method M2 ")
obj=Two()
obj.m1()
obj.m2()
|
38651a76d936008a7c44cd46e42b0c837d86ca64 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/rbnben002/question2.py | 668 | 3.625 | 4 | import math
userA = input(("Enter vector A:\n"))
listA = userA.split(" ")
userB = input(("Enter vector B:\n"))
listB = userB.split(" ")
Addition = [eval(listA[0]) + eval(listB[0]),eval(listA[1]) + eval(listB[1]),eval(listA[2]) + eval(listB[2])]
Sum = ((eval(listA[0])*eval(listB[0]))+(eval(listA[1])*eval(listB[1])... |
e06a159b33d1572ba4ef78ede2cbb0c8bbe37830 | mihirkelkar/EPI | /Tree/Next_Node_Preorder/preOrderNext.py | 1,024 | 4.0625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.parent = None
def preOrderNext(node):
if node.left != None:
return node.left
elif node.right != None:
return node.right
if node.parent == None:
return None
else:
while nod... |
94e9792a5ea96e1e893943f32d5a67dc3a4da53d | cityguy3156/Text-Fantasy-RPG | /TEXT-BASED RPG.py | 20,130 | 3.53125 | 4 | import random
# DAMAGE GIVEN TO ANY ENEMY WITH WEAPON
def weaponDamage(W):
crit = random.randint(1, 5) #CHANCE OF A CRITICAL STRIKE
if (W == "Sword"):
Damage = random.randint(80, 95)
elif (W == "Bow"):
Damage = random.randint(65, 80)
elif (W == "Axe"):
Damage = random.randint(9... |
00915a5edbe4582846b0ec23c74ff4d348b56360 | tnakaicode/jburkardt-python | /counterfeit_detection/counterfeit_detection.py | 14,317 | 3.6875 | 4 | #! /usr/bin/env python3
#
def counterfeit_detection_brute(n, coin, correct):
# *****************************************************************************80
#
# counterfeit_detection_brute detects counterfeit coins.
#
# Discussion:
#
# We are given the weights of N coins, and the co... |
70f34adabee503cba4e41471b4863c1d91f3c496 | MZoltan79/Python_Idomar | /p0031_mutable_immutable.py | 737 | 4.09375 | 4 | #!/usr/bin/env python3
# mutable variable
a1 = [1, 2]
b1 = a1
a1[0] = 'abc'
print(a1, b1)
# a list mutable, azaz ha ugyanarra a referenciára 2
# hivatkozás mutat, és az egyiket változtatom, mind
# a 2 megváltozik.
# ezért 'másolni' kell!
a2 = [1, 2]
b2 = a2[:] # vagy list(a2)
a2[0] = 'abc'
print(a2, b2)
# immut... |
2654a0b8ef12501cc4437b37f48c835487962dcd | Python-lab-cycle/Najmalfawaz | /concatenate elemts in list.py | 177 | 3.96875 | 4 | lis=input("enter a list(apace seperated):")
s1=lis.split()
print(s1)
result=''
for element in s1:
result += str(element)
print("concatenate in the list:",result)
|
9b9a78a66044f37b0b9a812f6dadfb2b70ce01e5 | Izardo/my-work | /Topic_2_statements/numGreaterThan.py | 302 | 4.09375 | 4 | # This program calculates whether one number is greater than another
# Author: Isabella Doyle
num1 = input("Enter the first number:") # requests input of integer
num2 = input("Enter the second number:") # requests input of integer
# prints output of whether one number greater than second
print(num1 > num2) |
c5ec87058ba18923323669c3f71625bb5e080c79 | ezequielhenrique/exercicios-python | /modulos/ex115/lib/interface/__init__.py | 666 | 3.609375 | 4 | def linha(tam=40):
print('~' * tam)
def cabecalho(txt):
linha()
print(f'{txt}'.center(40))
linha()
def leiaInt(txt):
while True:
try:
n = int(input(txt))
except (ValueError, TypeError):
print('\033[031m[ERRO] por favor, digite um número inteiro válido\033[... |
334df13577dbcab2bb01631da6ec7f2beec065c3 | harshareddy832/amfoss-tasks | /Task-2 Programming/amfoss9.py | 130 | 3.859375 | 4 | x=int(input())
s=str(x)
team1="0000000"
team2="1111111"
if team1 in s or team2 in s:
print("YES")
else:
print("NO") |
b4609735102e24d87670a461f23647a0b2face8d | kaunta/IONs | /src/Level4/w.py | 175 | 3.5625 | 4 | ## w.py
# Welcome to Level 4. We begin by reviewing our notation
# for ω, the smallest infinite ordinal.
X=""
while True:
output(X)
X = "output('" + escape(X) + "')" |
c409e3822df40a681aec5bc8ee1d069d05110cbf | NorthcoteHS/10MCOD-Jason-VU | /modules/u3_organisationAndReources/naming/New folder/temp/completeMe.py | 573 | 4.0625 | 4 | """
Prog: rectCalc.py
Name: Student Name
Date: 12/03/18
Desc: Calculates the area and perimeter of a rectangle.
"""
# Display welcome message.
print('Welcome to the Rectangle Calculator!')
# Use input to get the rectangle's length and width (2 lines).
# - Remember to provide a prompt message for each input.
... |
be6d99da4403b6b9a5993988c7a6fdab13ae7cbe | Mustafamado/Quran_Module | /Quran_Module.py | 4,195 | 3.515625 | 4 | import os
import csv
class Project_Quran:
def __init__(self):
Quran_English = []
with open('./Quran_English.csv', 'rt') as f:
for rows in f:
Quran_English.append(rows)
self.Quran_English = Quran_English
Quran_Arabic = []
with open('./... |
68593ade992c345cc82c4659f7113ce16310b9c0 | riishij/Land-of-the-Pirates | /Choose Your Story.py | 78,191 | 3.8125 | 4 | #-------------------------------------------------------------------------------
# Name: Riishi Jeevakumar
# Program Name: Lost in the land of Pirates: A choose your story adventure game
#-------------------------------------------------------------------------------
#start of game
#outputs introduction to game
p... |
ee435a89a5d765f50f4b2b9e40bdb2d4fc64bff8 | vijayvardhan94/pychilis | /pyprac/1.py | 474 | 4.3125 | 4 | #Create a program that asks the user to enter their name and their age.
#Print out a message addressed to them that tells them the year that they will turn 100 years old.
UserName = str(input("Enter your Name:"))
UserAge = int(input("Enter your age:"))
AgeToHundred = 100 - UserAge
CurrentYear = 2018
YearOfHundred = C... |
3c49cd8556b168585313028e00b338b2d32a98ad | rbassett3/ProverbGenerator | /Generator1.py | 1,292 | 4.09375 | 4 | import random
class Proverb:
"""A proverb generator, which takes a text corpus W at initialization.
W is an array of words with '!' as a starting token and '.' as an end token.
Generate a proverb with Proverb.Generate().
This method is a Markov chain model. The state is the current word.
To proceed to the next... |
85511ab633cd67594edf5836211906ef3ca363fd | madeibao/PythonAlgorithm | /PartB/Py华为的重复的字符串来进行排序.py | 454 | 3.59375 | 4 |
# 重复字符排序
# 题目描述:找出输入字符串中的重复字符,再根据ASCII码把重复的字符从小到大排序。
# 例如:输入ABCABCdd,输出ABCd。
# 找出字符串中的重复的字符,来进行排序
from collections import Counter
str2 = input()
dict2 = dict(Counter(str2))
res = []
for i in list(str2):
if dict2.get(i)>1:
res.append(i)
else:
continue
res.sort()
print("".join(res))
|
4c69c1b9be3ae7d23d4601a5e7501c6905fca722 | NataliaDiaz/BrainGym | /detect-feature-kernel.py | 2,387 | 4.03125 | 4 |
"""
# Feature detection in a image with:
- a convolution kernel,
- a threshold and
- image
as input. The convolution kernel is a square K x K real matrix denoted by k(i,j),
the threshold is a real number, and the image is given as an RxC real matrix with
elements between 0 and 1, with the pixel in row r and column c g... |
28345162d98c78903cf20acb459ccc1a87d210ed | pisfer/cin-in-python | /__init__.py | 1,060 | 3.59375 | 4 | import re
class ArgumentError(Exception):
def __init__(self, message):
super().__init__(message)
class cin:
"""cin func in python"""
def __init__(self, *args, text):
self.args = args
self.n = text
self.pora = "(?P<" + self.args[0] + ">[\w\d\S]*)"
self.ind... |
e649a77bc83700744f29a5d53bbd1d31c8036940 | tx991020/MyLeetcode | /数组/两数之和.py | 668 | 3.796875 | 4 |
'''
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
'''
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
... |
93321b44a8996bd2e2432532e905753ec918db06 | AlokRanjanBhoi/HackerRank_Python_Solutions | /1. Introduction/Loops.py | 239 | 3.546875 | 4 | '''
Title : Loops
Subdomain : Introduction
Domain : Python3
Author : Alok Ranjan Bhoi
Created : 14 January 2019
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(input())
for i in range(0,a):
print(i*i)
|
9755b0787b01481be6b76bb1c8d0eb8e14cc1dd7 | hengzeforever/165A-M1 | /template/page.py | 2,438 | 3.671875 | 4 | from template.config import *
'''The Page class provides low-level physical storage capabilities. In the provided
skeleton, each page has a fixed size of 4096KB. This should provide optimal
performance when persisting to disk as most hard drives have blocks of the same size.
You can experiment with different size... |
d092c8e959e361606e94b6048da90981316d2ca5 | LearningSteps/Learn-Python-The-Hard-Way-Test-Driven-Learning | /LearnPythonTheHardWay/ex31.py | 765 | 4 | 4 | #Making Decisions
print("Door 1 or 2?")
door = input("> ")
if door == "1":
print("There's a bear and a cake.")
print("What do you do?")
print("1. the cake")
print("2. The bear")
bear = input("> ")
if bear == "1":
print("You died. GG")
elif bear == "2":
print("The bear eat... |
54d6f4765a2e50bcebaf22245653527c4b5452e2 | Max143/Python_programs | /reversing the number.py | 438 | 4.15625 | 4 | # write python to reverse a given number
# using loop
# using recursion
# using function
# 1. By using loop method
number = int(input("Enter number: "))
Reverse = 0
while (number > 0):
Remainder = number % 10
Reverse = (Reverse*10) + Remainder
number = number // 10
print("In reverse of ... |
2887d929b4540fd38a89398292571c1d91d5af42 | macio-matheus/algorithms-and-data-structure-practices | /leetcode_merged_k_sorted_lists.py | 1,612 | 4.28125 | 4 | """
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:[1->4->5, 1->3->4, 2->6]
Output: 1->1->2->3->4->4->5->6
Approach 1: Brute Force
Intuition & Algorithm
Traverse all the linked lists and collect the values of the nodes into an array.
Sort and itera... |
bbf411463736a030a68272e3687a63fbbf3ac7b9 | Alarical/Interview | /LintCode/lint_solution/664CountingBits.py | 390 | 3.546875 | 4 | class Solution:
"""
@param num: a non negative integer number
@return: an array represent the number of 1's in their binary
"""
def countBits(self, num):
# write your code here
if num == 0 :
return [0]
dp = [0 for i in range(num+1)]
for i in range(1,num+1)... |
4bddf8bed9c0dd249fbb03be82a5a8349a3e3dd7 | OlgaShevtsova1/Python | /HW_2_5.py | 297 | 4.03125 | 4 | # Задача 5
Reiting= [7,5,3,3,2] #начало
print()
print("Рейтинг:",Reiting)
r=-1
while r!=0:
r=int(input("Введите целое число от 0 до 10"))
Reiting.append(r)
Reiting.sort ()
Reiting.reverse()
print("Рейтинг: ",Reiting)
print()
|
640dcff5d587eb8b14ef5bb3b12774b8d2bc5366 | iftitutul/Using-Python-to-Interact-with-the-Operating-System | /Week-3/3.3.10-regex-sub.py | 222 | 3.609375 | 4 | #!/usr/bin/env python3.6
import re
result = re.sub(r"[\w.%+-]+@[\w.-]+", "[REDACTED]", "Received an email for go_nuts95@my.example.com")
print(result)
result = re.sub(r"^([\w .-]*), ([\w .-]*)$", r"\2 \1", "lovelace, Ada")
print(result) |
6cdc57e90461a3140aa31d9beb4b5d7669c59f18 | ideven85/Machine_Learning_Algorithms | /Algorithms/HundredDaysOfCode/GraphProblems.py | 6,321 | 3.8125 | 4 | from collections import deque
from functools import lru_cache
from typing import List
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self
def depthFirstSearch(self, array):
... |
5f3a299afd1f42c9c50551178812a5ca3cc49152 | MohamedAwad9k8/Travian-Manager | /Functions.py | 1,045 | 3.859375 | 4 | def read_from_file(file_name, task_list):
try:
input_file = open("text_files\\" + file_name + ".txt", "r")
except:
print(file_name + ".txt couldn't be found, please make sure it exists in text_files directorty")
else:
for line in input_file:
task_list.append(line.s... |
c4a40d13b36babfd2f986215d5f2791c5b8ecdf5 | alexbaltman/ctci | /ch8-RecursionDynamicProgramming/questions/paintfill.py | 489 | 3.84375 | 4 | '''
Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.
Hints: 364, 382
'''
def paintfill(s):
pass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.