blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f11081f19d408f5a8dd5716f54476782484ba3b7 | Immutare/euler-project | /eu3.py | 351 | 3.53125 | 4 | """
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
numero = 600851475143
factors = []
prime = 2
while True:
if numero % prime == 0:
factors.append(prime)
numero = numero / prime
else:
prime+=1
if numero == 1:
... |
4c20561b630ea391b2ccebf306552bab5e3fad46 | liuyanglxh/python-comprehensive | /arithmetic/mergeKLists/s2.py | 773 | 3.5 | 4 | from typing import List
import functools
from arithmetic.listnode import ListNode
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
lists = [ele for ele in lists if ele]
# 倒叙排
def cmp(a: ListNode, b: ListNode):
return b.val - a.val
sorted(lists, key=functools.cmp_to_key(cmp))
... |
db2be9683795956e279b869a6b4fd46b2c35f640 | keeykeey/dogclassifier | /makedata.py | 403 | 3.53125 | 4 | #二つの犬の写真をモデルに投入できる型に整形する
import os
import numpy as np
import pandas as pd
class picturesdirectory(self):
'''
<USAGE>
ex) dir_name = picturesfile() #dir_name:directory which has some pictures to put into models in
'''
def __init__(self,dirname);
self.name = dirname
self.pic_ins... |
950550d66f2b5321fabf83eab06165c43e8b2869 | joselluis7/bookstore | /app/helpers/utils.py | 203 | 3.703125 | 4 | #-*-encoding:utf-8-*-
import locale
def list_string(l):
s = ""
item = 0
if len(l) > 1:
for item in range(len(l) - 1):
s = s + l[item] + ", "
s = s + l[item + 1]
else:
s = l.pop()
return s |
54c47a192ce2e43b3da61e8f1f57e6d59a42da4e | Ahmed-Sanad24/FEE | /question2-buylotsofFruit.py | 700 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
# we need that the price of 2 kilos of apple and 3 of pear and 4 of limes is 12.25 pounds
# so we assume the price of these fruits according to this price
fruitprice = {'apples': 1.00 ,'pears': 1.75 , 'limes': 1.25 , 'bananas':2.00 , 'oranges': 0.75 }
# In[22]:
def... |
9e779e2f52e92306fb44c1f50d0ed4286cff65b5 | asyrul21/recode-beginner-python | /materials/week-5/src/endOfClass-1.py | 593 | 4.34375 | 4 | # The first part of this exercise is to define a function which returns a boolean.
# it returns True if the number is odd, otherwise return False
# If you remember, we assume that if a number is divided by 2 has a remainder of non 0, the
# number is an odd number.
# The loop will iterate through a list of numbers, and ... |
2c992e4a60f69a6bee14273f174dc8e76722078a | BlackRob/Euler | /prob24.py | 1,603 | 3.765625 | 4 | def genOrderedPerms(lcr,perms,p_in):
""" generate ordered permutations by splitting
lcr = list of characters remaining
the idea is given a list of characters, the set of all possible
permutations of those characters can be split into len(lcr) subsets,
each starting with a particular character, for... |
00325bb2a5cdaaab88de688ec8312b7b1e0e04d5 | qingyunpkdd/pylib | /design pattern/share.py | 1,099 | 3.578125 | 4 | #-*- encoding:utf-8 -*-
__author__ = ''
class Share_m():
def __init__(self,name=""):
self.value={}
self.name=name
def __getitem__(self, item):
print("method __getitem__{item} return".format(item=item))
return self.value[item]
def __setitem__(self, key, value):
print("... |
08f62ea0742a2e489bfb3007c1ed14c2e4f92b4f | Aasthaengg/IBMdataset | /Python_codes/p02263/s708155947.py | 365 | 3.59375 | 4 | def push(x):
global stack
stack.append(x)
def pop():
global stack
ret = stack.pop()
return ret
ope = {"+": lambda a, b: b + a,
"-": lambda a, b: b - a,
"*": lambda a, b: b * a}
if __name__ == '__main__':
stack = []
for c in input().split():
if c in ope:
push(ope[c](pop(), pop()))
else:
pu... |
623f329a718fcc13167a868f900e9ab079de7d3b | Zjianglin/Python_programming_demo | /chapter6/6-15.py | 2,190 | 3.5625 | 4 | '''
6-15.转换。
(a)给出两个可识别格式的日期,比如MM/DD/YY或者DD/MM/YY格式,计算出两
个日期间的天数。
(b)给出一个人的生日,计算从此人出生到现在的天数,包括所有的闰月。
(c)还是上面的例子,计算出到此人下次过生日还有多少天。
'''
import time
def date2num(ds):
'''
format: DD/MM/YYYY
return the number of days since 1/1/1900
'''
months = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
da... |
fc56a99431e68f2e958600e8c60063f57431d3bc | manugildev/IPDP-Course-DTU | /Assignment4/Assignment4F.py | 765 | 3.75 | 4 | import numpy as np
import math
# Function that returns if an specific experiment is complete or not
def isComplete(temp):
if temp.size == 3:
return True
return False
def removeIncomplete(id):
# This array will hold elements to remove
numsToDelete = np.array([])
for i in id:
temp = id[id > math.floor(i)]
... |
f2b7976c234fe6ef8ffeb7f9a2c47540609b2794 | LuisFer24/programacion-python | /Laboratorio 4/Ejercicio 1,tarea 4.py | 438 | 3.984375 | 4 | #<>
#Luis Fernando Velasco García
#Ejercicio 1
#para ejecutar el programa se debe abrir python en la carpeta donde se encuentra el texto.txt, y ejecutar el programa
a=raw_input("Introduce el nombre de un archivo.txt(debe estar en la carpeta actual): ")
b=input("Introduzca el nùmero de lineas que desea leer: ")
de... |
5a724273c94895abf7807b7c6a8191872f889ddb | shookies/text_finder | /WordFinder.py | 1,126 | 3.5 | 4 |
############# Constants #############
#TODO add substring functionality
############# Word class #############
class word:
def __init__(self, theWord, xs, ys, xe, ye, page):
self.start = (xs, ys)
self.end = (xe, ye)
self._string = theWord
self.pageNum = page
def get_co... |
42d8eb553fc62a2521d3a559c77f6be0066962bc | euijun0109/Multivariable-Linear-Regression | /LinearRegressionMultivariable.py | 2,320 | 3.59375 | 4 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
class LinearRegressionMultivariable:
def __init__(self, alpha, n):
self.thetas = np.zeros((n, 1), dtype= float)
self.m = 0
self.n = n
self.cost = np.zeros((n, 1), dtype= float)
self.a... |
9518984d313d2826ac675eaa6744edb421340912 | dMedinaO/python_course | /examples_05_05/ejemplo_condiciones.py | 967 | 4.03125 | 4 | #determinar si enviamos una alerta de sismo
#la alerta de sismo se enviara si y solo si, el valor de la actividad es mayor a 5
#num_habitantes > 1 -> si envio la alerta
valor_escala = float(input("Favor ingrese el valor en escala "))
num_habitantes = float(input("Favor ingrese el numero de habitantes en MM "))
'''
#... |
06a9c8729d1f8a751db0b7df4213838ebfc705e5 | emmorga2007/morgan_e_pythonHW | /game.py | 883 | 4.15625 | 4 | #import then random package so we can generate a random ai
from random import randint
#"basket" of choices
choices=["rock", "paper", "scissors"]
#let the AI make choices
computer=choices[randint(0,2)]
#set up a game loop here so we don't have to keep restarting
player= False
while player is False:
player=input(" c... |
4f5576324116179724963f6b6b4a945c85368cd3 | MinSuArin/Baekjoon | /1085 직사각형에서 탈출.py | 290 | 3.5 | 4 | if __name__ == "__main__" :
x, y, w, h = map(int, input().split())
if w - x <= x :
dis_x = w - x
else :
dis_x = x
if h - y <= y :
dis_y = h - y
else :
dis_y = y
if dis_x <= dis_y :
print(dis_x)
else:
print(dis_y) |
6df259cad59beafb6dc8e1df557bd4369f9ad49d | Zerryth/algos | /algorithmic-toolbox/4.divide-n-conquer/quicksort.py | 1,093 | 4.03125 | 4 | # Uses python3
import sys
import random
def partition3(a, l, r):
#write your code here
pass
def partition2(a, left, right):
current_val = a[left]
pivot = left
for i in range(left + 1, right + 1):
if a[i] <= current_val:
pivot += 1
a[i], a[pivot] = a[pivot], a[i]
... |
7593483db4836e2ef7b64493a5d7e60ed57055bd | bjainvarsha/coding-practice | /LinkedList.py | 4,530 | 3.84375 | 4 | class Node:
def __init__(self, data = None):
self.data = data
self.next = None
class Single_LL:
def __init__(self):
self.head = None
self.tail = None
def print_LL(self):
if not self.head:
print("Linked List Empty")
return
temp = self.head
LL_string = "\n|"
while temp:
LL_string += str(te... |
aa8a563ff6ebd5195020835a8041fee4f0264f15 | nijingxiong/LeetCode | /6ZigZagConversion.py | 248 | 3.59375 | 4 | # l=[0 for i in range(2)]
# print(l)
# l=['a','b']
# s=[]
# s.append(l)
# l=['c','d']
# s.append(l)
# for i in s:
# for j in i:
# print(j)
# print(s,l)
s=[['a', 0], [0, 'b'], ['c', 0], [0, 'd'], ['e', 0], [0, 'f']]
print(len(s))
print() |
79432715628d3a2feb866ea13907782e79959a8c | hexycat/advent-of-code | /2022/python/07/main.py | 2,497 | 3.703125 | 4 | """Day 7: https://adventofcode.com/2022/day/7"""
def load_input(filepath: str) -> list:
"""Reads input and returns it as list[str]"""
lines = []
with open(filepath, "r", encoding="utf-8") as file:
for line in file.readlines():
lines.append(line.strip())
return lines
def update_fo... |
f39cace481739444e92f8b17642525f9d5cbc407 | VenkataNaveenTekkem/GoGraduates | /loops/Loops.py | 1,841 | 4.15625 | 4 | #for loop example
x="python"
for i in range(len(x)): # range starts from index 0 to the value given to it
print(x[i])
y="loops class"
for i in y:
print(i)
#take a string with alphanumeric characters and print only digits in the string
z="abc123xyz"
for i in z:
if(i.isdecimal()):
print(i)
#this t... |
8082034f3b44c9e9f716c6c0d76c2fd7224c0f9b | csusb-005411285/CodeBreakersCode | /maximum-number-of-visible-points.py | 908 | 3.59375 | 4 | class Solution:
def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:
left = 0
angles = []
count = 0
duplicates = 0
if angle == 360:
return len(points)
for point in points:
x1, y1 = point
x2, y2 =... |
3d359be33202a34e3ef703be17130b19d8f8d3ae | joshdavham/Starting-Out-with-Python-Unofficial-Solutions | /Chapter 4/Q11.py | 332 | 4.03125 | 4 | #Question 11
def main():
seconds = float(input("Enter the number of seconds: "))
minutes = seconds / 60
hours = seconds / 3600
days = seconds / 86400
print("\nIn", seconds, "seconds there are...")
print(minutes, "minutes.")
print(hours, "hours.")
print(days, "days.")
... |
e99dbfbe5ab4b1c78297c4de7d70de75d0cc4570 | RMhanovernorwichschools/Cryptography | /cryptography.py | 2,462 | 3.890625 | 4 | """
cryptography.py
Author: Rachel Matthew
Credit: none
Assignment:
Write and submit a program that encrypts and decrypts user data.
See the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md
"""
associations = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123... |
a643c0dbfd386480209c177db10e428cdc9b68ab | stefan1123/newcoder | /构建乘积数组.py | 1,724 | 3.65625 | 4 | """
题目描述
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
代码情况:accepted
"""
class Solution:
def multiply(self, A):
# write code here
# # 方法一,暴力相乘,O(n^2)
# if len(A) <= 0:
# return -1
# elif len(A) == 1:
# # 数组A... |
d89a593836f159e1d9f2edf7f1e0b55c434a13d0 | yinxx2019/python | /hw06/print_cube.py | 1,213 | 4.125 | 4 | def main():
"""
draws 2D cubes with sizes from user input
"""
n = int(input("Input cube size (multiple of 2): "))
while n % 2 != 0 or n < 2:
n = int(input("Invalid value. Input cube size (multiple of 2): "))
else:
cube(n)
def cube(n):
double_n = n * 2
# draw top side
... |
d07eb0c27412ecc3a1d11dba41581b1d6f0357d7 | saivijay0604/algorithms | /general/arrayDiv3.py | 568 | 4.15625 | 4 | from numpy import *
def isDiv3(x):
for i in range(len(numberArray)):
if numberArray[i] % 3 == 0:
ele = numberArray[i]
listElements.append(ele)
else:
pass
print("From list numbers which are divisble by 3 are:",listElements)
global numberArray
numberArray = arra... |
3cec57cdc15456782476d6cd547fb9a5f5879661 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/mggdac001/question2.py | 1,061 | 3.875 | 4 |
from math import sqrt
def vector():
f='{0:1.2f}'
vector_A=[]
vector_a=input("Enter vector A:\n")
vector_B=[]
vector_b=input('Enter vector B:\n')
for num in (vector_a.split()):
vector_A.append(num)
#print(vector_A[1])
for num in (vector_b.split()):
vector_B.ap... |
c28f2b5b07d8f4284d7d9643a834e9cefda2a320 | mykeal-kenny/Intro-Python | /src/dicts.py | 637 | 4.15625 | 4 | # Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{"lat": "48.8584° N", "lon": "2.2945° E", "name": "Eiffel Tower"},
{"lat": "40.6892° N", "lon": "74.0445° W", "name"... |
8b805de163a63153badac66f931466ddce7bb811 | RahulBhoir/Python-Projects | /data_structure/panlindrone.py | 463 | 3.96875 | 4 | def ReverseNumber(number):
reverse = 0
count = 0
while(number > 0):
digit = int(number % 10)
reverse = (reverse * 10) + digit
number = int(number / 10)
count += 1
return reverse
def IsPanlindrone(number):
reverse = ReverseNumber(number)
if reverse == number:
... |
d38111744ef9ec977aa3dc1f9e0834fa61cf1fa3 | rhjohnstone/random | /series_betting.py | 2,202 | 3.828125 | 4 | """
Team A playing Team B in a series of 2k+1 games.
The first team to win k+1 games wins the series.
We want to place a 100 bet on Team A winning the series, with even odds.
But we can only bet on a game-by-game basis.
What betting strategy can we use to have the same result as the original plan?
"""
import operator
... |
bf7a7280e44c710fe3a64f50ebe3deded0d67028 | joaocarvalhoopen/Pencil_Draw_Help_Program | /pencil_draw_help_program.py | 12,587 | 3.765625 | 4 | ###############################################################################
# Name: Pencil Draw Help Program #
# Author: Joao Nuno Carvalho #
# Email: joaonunocarv@gmail.com #
... |
05c39781642a44d51067178bdf5063582ff9a42e | huilongan/Python | /SinglyLinkedList.py | 4,307 | 3.75 | 4 | '''
To review the singly linked list
'''
#SinglyLinkedList
class Empty(Exception):
pass
class SinglyLinkedBase:
class _Node:
__slots__='_element','_next'
def __init__(self,element,next):
self._element= element
self._next=next
def __init__(self):
... |
04204910cf81ff567e669b20b6124c716a5f135f | SMAshhar/Python | /5_LoginGreeting.py | 985 | 4.1875 | 4 | current_usernames = ["admin", "v2fftb", "Ali", "Rubab", "Nawal"]
# 5-8 greet every login. Some oneway, the others the otherway
for a in current_usernames:
username = input("Enter username: ")
if username == "admin":
print("Hello admin, would you like a report?")
break
elif username ... |
a5a95f41d6ea8593ead4e2d361ec72d086a9c4dc | cod3baze/initial-python-struture | /w3/JSON.py | 1,035 | 3.703125 | 4 | import json
# dados JSON
x = '{"name":"jhon", "age":30}'
# Converter os Dados para dicionario python
y = json.loads(x)
print(y)
# dicionario python
w = {
"name": "John",
"age": 30,
"city": "New York"
}
#converter o dicionário para dados JSON
z = json.dumps(w)
print(z)
#Converte objetos Python em strings JSON... |
09c9533f5c28e11aff42f91813f61e4fae6891f4 | melissafear/CodingNomads_Labs_Onsite | /week_03/02_exception_handling/04_validate.py | 537 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
isinteger = "nope"
while isinteger == "nope":
user_input = ... |
d2a6ba9b155a54251489ef96fb94bd7557a0c5df | khalilabid95/checkpoints | /Q3.py | 201 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 17:24:50 2020
@author: Khalil
"""
import math
mydic={}
n= int(input('donner la taille de list'))
for i in range(1,n+1):
mydic[i]= i*i
print(mydic) |
503c0f507b55b3ab7cd2c61a909cb48490c15c6e | linuxsed/python_script | /sort_list.py | 115 | 3.625 | 4 | a=[1,3,5,7,9]
b=[2,4,6,8,10]
new_list=[]
for i in a+b:
new_list.append(i)
new_list.sort()
print (new_list)
|
8449f12a28a2e514d912ced806727b50ffa9b287 | beingimran/python | /even_odd.py | 186 | 3.6875 | 4 | a = [1,2,3,4,5,6,7,8,9,10]
even=0
odd=0
for i in a:
if i%2 == 0:
even+=1
else:
odd+=1
print("no. of even:",even)
print("no.of odds:",odd)
|
2f2814cf781274742b3ab9e8ffec6f6d9c82ad57 | tmoertel/practice | /EPI/06/soln_06_001_dutch_national_flag.py | 2,712 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Tom Moertel <tom@moertel.com>
# 2013-10-23
r"""Solution to "Dutch National Flag" problem, 6.1 from EPI.
Write a function that takes an array A and an index i and
rearranges the elements such that all elements less than A[i]
appear first, followed by all el... |
02c56e857cd58c6b65d0c6ff1680f3659d4df496 | loponly/python_class | /Design_Patterns/1_Creational/Abstract_factory_.py | 1,563 | 3.859375 | 4 | import abc
class Button(abc.ABC):
"""
Concret Button
"""
@abc.abstractmethod
def render(self):
pass
class WinButton(Button):
def render(self):
return 'This is button for windows.'
class MacButton(Button):
def render(self):
return 'This is button for mac.'
c... |
006b07d42aeba64df4c4b2ebbc654c281bf1be98 | bontu-fufa/competitive_programming-2019-20 | /Take2/Week 2/sort-an-array.py | 839 | 3.921875 | 4 | #https://leetcode.com/problems/sort-an-array
def sortArray(self, nums: List[int]) -> List[int]:
# return sorted(nums)
def merge_sort(values):
if len(values)>1:
m = len(values)//2
left = values[:m]
right = values[m:]
left = merge_sort(left)
... |
3df73920a57c840cc1df8e9abc6f20e3c59e3eb0 | fargofremling/learnypythonthehardway | /ex25.py | 1,856 | 4.46875 | 4 | def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word... |
7333481e42efe3c0b46327f97c4ab71b6492311a | parzipug/Random-Passcode-Generator | /Random password generator.py | 1,038 | 3.8125 | 4 | import time
import random
def whitespace(x):
for i in range(x):
print("\n")
def normalspace(x):
for i in range(x):
whitespace(1)
time.sleep(.8)
def passcode_generator():
print("<<< Random password generator. >>>")
normalspace(1)
... |
71b42cc185b048af5b065526decb65e6d519f4ac | alexReshetnyak/pure_python | /1_fundamentals/10_ tuples.py | 992 | 4.3125 | 4 | print('---------------------------TUPLES--------------------------------')
# like list but we can't modify it (immutable)
my_tuple = (1, 2, 3, 4, 5)
# ! TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 'z'
print("my_tuple[0]:", my_tuple[0]) # 1
print("2 in my_tuple:", 2 in my_tuple) # True... |
00740f46e831f28c48242d22637e1c304f9c2f96 | CNU-Computer-Physics/Example-and-Practice | /03_analysis/02A_function_differential.py | 736 | 4.09375 | 4 | """ 함수의 미분1
도함수를 출력하는 기초적인 방법
"""
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return 3 * x ** 2 + 2 * x + 6
def g(func, x):
y = []
h = 0.01
for _x in x:
y.append((func(_x + h) - func(_x)) / h)
return np.array(y)
if __name__ == "__main__":
x = np.linspace(0, 10)
... |
27990b303362311d16fdcce1ee0266bdb692f6d2 | jpark527/Fall2018 | /Python/HarvaidX/knnClassification.py | 4,436 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 2 23:38:02 2018
@author: j
"""
import numpy as np
import random
import scipy.stats as ss
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
def getDistance(p1, p2):
'''
Find the distance between p1 and p2.
''... |
56d983a2ebb06ff1bc4b65bf07fa189e830de598 | marcos8896/Python-Crash-Course-For-Beginners | /classes/classes.py | 1,335 | 4.03125 | 4 | #CLASSES AND OBJECTS
class Person:
__name = ''
__email = ''
def __init__(self, name, email):
self.__name = name
self.__email = email
def setName(self, name):
self.__name = name
def getName(self):
return self.__name
def setEmail(s... |
2d35e441b55121ba76ef7b05ef7a8b3a4bae2ef8 | edanilovets/python-jumpstart | /05_weather_app/05_weather_app.py | 1,334 | 3.59375 | 4 | import requests
import bs4
import collections
WeatherReport = collections.namedtuple('WeatherReport', 'loc, temp')
def main():
# print the header
print_header()
# get zip code from user
zip_code = input('What is your zip code (96001)? ')
# get html from web
html = get_html_from_web(zip_code)... |
088c2c0de2547adea8433d500df3f5c98bf75979 | pandiyan07/python_2.x_tutorial_for_beginners_and_intermediate | /samples/conceptual_samples/exceptional_handling/user_defined_exceptions.py | 377 | 4.15625 | 4 | # this is a sample python program which is used to create a user defined exception
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print 'My exception occurred, value:', e.value
# th... |
63a39387a4d1c31de732f113390d2f9305528838 | rlee1204/hackerrank | /strings/palindrome_index.py | 675 | 3.65625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
def get_palindrome_creation_index(s):
len_s = len(s)
for i in xrange(len_s//2):
comparison_char_index = len_s - 1 - i
if s[i] == s[comparison_char_index]:
continue
if s[i] == s[comparison_char_index - 1]:
... |
9b5b033bc4889cde686257355ee3f07a14ce5653 | jeremiahd/TTA_Student_Projects | /5_Python/Python Projects/TextGame/game.py | 2,991 | 4.03125 | 4 | # Python: 3.7.3
# Author: Jeremiah Davis
# Purpose: Python text based game
def start(nice=0, mean=0, name=""):
#get user's name
name = describe_game(name)
nice, mean, name = nice_mean(nice, mean, name)
def describe_game(name):
"""
check if this is a new game or not.
If it is new, get t... |
87ea315ed9bae5316a459750c1561de865b79d1a | duygucumbul/pyt4585 | /kararorn1.py | 1,539 | 3.796875 | 4 | #Örnek: Dışarıdan kullanıcı not girişi sağlayacak
# 0 - 30 => FF
# 31 - 50 => DD
# 51 - 70 => CC
# 71 - 84 => BB
# 85 -100 => AA harf notunu aldınız uyarısı veriniz.
try:
not_ = int(input("Lütfen notunuzu giriniz: "))
result = "Girilen {} notun karşılık harf notu: {}"
if not_ <= 30 and not_ >= 0 :
... |
43ded8660e6586618b8950086e4c838eb71b856a | andriitugai/python-morsels | /ordered_set.py | 2,361 | 3.921875 | 4 | class OrderedSet(object):
def __init__(self, some_iterable):
self.container = []
self.underset = set()
for item in some_iterable:
if item not in self.underset:
self.container.append(item)
self.underset.add(item)
def __repr__(self):
ret... |
579ae81be6c17e61c7608b2e20d18a8c280062b0 | Magnus-ITU/project1_code_1styear | /project_data.py | 1,107 | 3.515625 | 4 | import numpy as np
def data_load_to_array(file):
"""Reads in the data from csv file and stores it in an array."""
with open(file, "r") as data_str:
data_list = []
for i in data_str:
list_str = i.split("\n")
del list_str[-1]
data_list.append(list_str)... |
68a5b859eedeb3c618af6750be202ef51688eddf | JerinPaulS/Python-Programs | /MapSumPairs.py | 1,641 | 4.09375 | 4 | '''
Implement the MapSum class:
MapSum() Initializes the MapSum object.
void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
int sum(string prefix) Returns the sum of all the pairs' value whose key starts with... |
802875e2b188baa3741f7638bb1aaf493ddfabe4 | i-tanuj/Drawing-Application | /multitreading/multitreadingapp3.py | 430 | 3.59375 | 4 | import time
from threading import *
def printsquare(l1):
for i in l1:
print("square of ",i,"is",i*i)
time.sleep(1)
def printcube(l2):
for i in l2:
print("cube of ",i,"is",i*i*i)
time.sleep(1)
being=time.time()
l3=[n for n in range(1,11)]
t1=Thread(target=printsquare,args=(l3,))
t2=Thread(target=printcube,args... |
15641eb4c521a1d17460445158c36cad1f23c0d1 | ricardo1470/holbertonschool-interview | /0x1F-pascal_triangle/0-pascal_triangle.py | 628 | 4.03125 | 4 | #!/usr/bin/python3
"""
that returns a list of lists of integers
representing the Pascal’s triangle
"""
def pascal_triangle(n):
"""
Returns an empty list if n <= 0
"""
if n <= 0:
return []
"""
Returns a list of lists of integers representing
"""
triangle = [[1]]
"""
Lo... |
fa078791349b673866e956a0a645022d0338da88 | tarunpsquare/Python | /HangHimNotFreeHim.py | 10,655 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
@author: Tarun Purohit tarunpp2001@gmail.com
"""
#Python Project:HANG HIM NOT FREE HIM
#Implemented a game in python which is very similar to Hangman.
#Turtle library used to draw the stick figure of the man.
import random, time, turtle,sys
def movies():
movies=["DJANGO UNCHAINE... |
3280b7da5abda559f8699a795836e5cb595fae84 | starryKey/LearnPython | /04-TKinter基础/TkinterExample09.py | 958 | 3.59375 | 4 | # 画一个五角星
import tkinter
import math as m
baseFrame = tkinter.Tk()
w = tkinter.Canvas(baseFrame, width=300, height=300, background="gray" )
w.pack()
center_x = 150
center_y = 150
r = 150
# 依次存放五个点的位置
points = [
#左上点
# pi是一个常量数字,3.1415926
center_x - int(r * m.sin(2 * m.pi / 5)),
cent... |
21dda8a95578b433c2ae96aa6bbcede2799ae01a | luckyguy73/wb_homework | /2_week/valid_sudoku.py | 812 | 3.75 | 4 | import collections
from typing import List
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
def make_subs():
subs = [[] * 9 for _ in range(9)]
for i in range(0, len(board), 3):
for j in range(0, len(board), 3):
for x in ra... |
427bea7bc24d055ca56872ad1f655137812c24a4 | Connorsmith25/SSW567HW02Triangle | /Triangle.py | 919 | 3.8125 | 4 | # Connor Smith
# Professor Saremi
# SSW 567
# HW 02a
# "I pledge my honor that I have abided by the Stevens Honor System"
def classifyTriangle(a, b, c):
# check if input is valid
if not (isinstance(a, int) and isinstance(b, int) and isinstance(c, int)):
return 'InvalidInput'
if a <= 0 or b <= 0 or... |
af816a3d6e5b1cd5c6106a4bcc723e9b274bf6ca | cagriozcaglar/ProgrammingExamples | /DataStructures/TreesGraphs/SimilarStringGroups/SimilarStringGroups.py | 1,902 | 4.09375 | 4 | """
839. Similar String Groups
Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y.
Also two strings X and Y are similar if they are equal.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but
"star... |
ce5bec8be1b74ebc3f50b3f22e988ce20c5d5356 | ijassiem/training_one | /pokemon/pokemon.py | 3,645 | 4.09375 | 4 | """This module contains a two classes for creating pokemon."""
from random import randint
def repeat(m):
"""Decorator-function allows decorated function to repeat random number of times, ranging from 0 to m.
Parameters
----------
m : int
The value of the maximum random number allowed to be g... |
83e4fbc0a18862239c2ce8f6792f5c7f8256ba78 | L200180048/Praktikum-ASD | /modul2/5.py | 1,147 | 4 | 4 | class Mahasiswa(object):
"""Class Mahasiswa yang dibangun dari class Manusia"""
kuliah =[]
def __init__(self,nama,NIM,kota,us):
"""Metode inisialisasi ini menutupi metode inisiasi di class Manusia."""
self.nama = nama
self.NIM = NIM
self.kotaTinggal = kota
sel... |
bd89c6d757059c94af6517a23b88fb188814ad21 | GScabbage/SpartaPasswordProject | /Password_Project/app/userinfo.py | 6,167 | 4.125 | 4 | import sqlite3
from contextlib import closing
class userinfoclass:
def checkvalid(cls,t):
while True:
check = input("Is the above correct?(y/n) ")
if check.lower() == "y":
print ("Great! next")
return False
break
elif check... |
50a137a57c8b1d4b2d1974f0addbd573c6b4f2f8 | Aasthaengg/IBMdataset | /Python_codes/p03693/s576535932.py | 85 | 3.515625 | 4 | a = int(input().replace(' ', ''))
if a % 4 == 0:
print('YES')
else:
print('NO') |
4c6ffab64a4c31f1e36f51dc7cf70b0078a287d8 | RamonFidencio/exercicios_python | /EX016.py | 124 | 3.984375 | 4 | import math
n = float(input ("Digite o primeiro numero:"))
n = int(n)
print('A parte inteira do seu numero é {}'.format(n)) |
742c526824ddf5c50c8f970078ad7193044ba9a5 | duyvk/GTVRec | /utils/similarity.py | 1,941 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Mar 15, 2013
@author: rega
'''
import math
def similar_list_calculating(l1, l2):
"""
Tính similarity giữa 2 thành phần của 2 vector đặc trưng, công thức áp dụng
trong hàm này là tính hệ số Jaccard, nếu 2 thành phần càng giống nhau thì hệ số
... |
612baf1e03b9cf22a01ab1007921239ed447f157 | theGreenJedi/Path | /Python Books/Athena/training/demo/demo/threading/downloader.py | 3,288 | 3.6875 | 4 | """
downloader.py -- An example that uses threads to do work in the background
while waiting for user input.
"""
# I've tried to keep this fairly simple. There are *many* possible enhancements!
import os
import threading
import urllib2
# Importing readline adds some nice behavior to raw_input().
imp... |
7716f766825e178ed4f3b57299c25852f86a07b7 | carter144/Leetcode-Problems | /problems/11.py | 1,395 | 3.984375 | 4 | """
11. Container With Most Water
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contain... |
4a830aa37905446a7c99ed081cb32602e3e17482 | ryanh153/Morsels | /53_78/55_natural_sort/test_sortutils.py | 3,812 | 3.6875 | 4 | import unittest
from sortutils import natural_sort
class NaturalSortTests(unittest.TestCase):
"""Tests for natural_sort."""
def test_empty_iterable(self):
self.assertEqual(natural_sort([]), [])
self.assertEqual(natural_sort(()), [])
self.assertEqual(natural_sort(set()), [])
def... |
65e1a15eefd4ea3d243e0872373eb9692b81f3f0 | ayman-shah/Python-CA | /Python 1/20.3.py | 213 | 4.03125 | 4 | #Write your code here
food = int(input("how many servings of ruit and veg have ye had"))
if food >= 5:
print("Well done, you've had your 5+ today")
else:
print("You should eat 5+ a day, every day.")
|
0de36965b96d9b69e38d47a2d292bfeebd1ef250 | landenthemick/Codewars | /outlier.py | 393 | 4.125 | 4 | def find_outlier(integers):
odd = 0
odd_list = []
even = 0
even_list = []
if len(integers) == 0:
return None
else:
for item in integers:
if item%2==0:
even +=1
even_list.append(item)
else:
odd +=1
odd_list.append(item)
if even > odd:
return odd_list[... |
267cf38f3bbdaafe3505278ec8e8560516c72a34 | mangeld/aoc2020 | /src/day1.py | 724 | 3.90625 | 4 | from sys import argv
from typing import List, Tuple
from itertools import combinations
from functools import reduce
def find_2020_entries(entries: List[int], n_products=2) -> Tuple[int, ...]:
for combination in combinations(entries, n_products):
if sum(combination) == 2020:
return combination
... |
28f81d8e11cd8c7253ba87b44db02aeeb1af388b | diordnar/DesignPattern | /Python/Builder/Builder.py | 591 | 3.75 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
'''
Builder Pattern
Author: reimen
Data: Oct.9.2014
'''
from abc import *
class Builder(object):
__metaclass__ = ABCMeta
@abstractmethod
def build(self): pass
class Product(object):
def execute(self):
print "Hi"
class ConcreteBuilder(Builder):
de... |
cb2cc598984ab3f5bdec23659bd1c4405ef29287 | prayas2409/Machine_Learning_Python | /Week2/ArrayQ4.py | 1,293 | 3.921875 | 4 | from Utility.UtilityDataStructures import UtilityDataStructures
import array as array_object
flag: bool = True
while flag:
try:
print('Enter the number of elements to be added to the array')
util = UtilityDataStructures()
num = util.get_positive_integer()
counter = 0
array = ... |
5763d3c46d991023cb2977019e6477a5f03f2169 | starschen/learning | /algorithm_practice/2_1递归的概念.py | 2,082 | 3.828125 | 4 | #encoding:utf8
#2_1递归的概念.py
#例2-1 阶乘函数
def factorial(n):
if n==1:
return n
else:
return n*factorial(n-1)
#例2-2 Fibonacci数列
def Fibonacci(n):
if n==1 or n==2:
return n
else:
return Fibonacci(n-1)+Fibonacci(n-2)
#例2-3 Ackerman函数
def Ackerman(n,m):
if n==1 and m==0:
... |
0edfe460eb044805f188bdf8727eb4f74dd4e539 | Sarbjyotsingh/learning-python | /Control Flow/forLoop.py | 4,826 | 4.03125 | 4 | cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
print(city.title())
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
# Range Function
# With one variable argument become stop element
print(list(range(4)))
# With two variable arg... |
cf88f6fc1dcbe953ee26037aff766908c26fad7a | kalnin-a-i/Polyomino_Tiling | /creating_graph.py | 697 | 3.578125 | 4 | # Создание двудольного графа хранимого в виде двух словарей
def create_graph(placements, size):
M = size[0]
N = size[1]
graph = {}
graph_invert = {}
for i in range(M):
for j in range(N):
for position in placements.keys():
if placements[position][i][j] == 1:
... |
dc9801c5c0123046e1cf9e9b7258050401d85d93 | youridv1/ProgrammingYouriDeVorHU | /venv/Les7/7_5.py | 292 | 3.71875 | 4 | def gemiddelde(zin):
zin = zin.strip()
zin = zin.strip('.')
zin = zin.split(sep = ' ')
total = 0
count = 0
for word in zin:
total += len(word)
count += 1
res = total / count
return res
print(gemiddelde(input("Geef een willekeurige zin: ")))
|
830233ff5aff4ac86942cb7746f188001b923f37 | vivekanand-mathapati/python | /filter.py | 383 | 4.125 | 4 | '''As the name suggests,
filter creates a list of elements for which a function returns true.'''
def odds(value):
return True if value % 2 != 0 else False
lst = [1,2,3,4,5]
odd_num = [x for x in filter(odds, lst)]
print(odd_num)
#OR
odd_num = [x for x in filter(lambda x: x%2 != 0, lst)]
print(odd_num)
#OR
odd_n... |
fba425f6a647b3201d0fb249cc288e693c7be558 | maryaaldoukhi/Rock-Paper-Scissors | /_project2.py | 5,675 | 4.125 | 4 | #!/usr/bin/env python3
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
import random
import time
import sys
moves = ['rock', 'paper', 'scissors']
"""The Player class is the parent class for all of the Players
in this game"""
def... |
cb4e1bc0a2c7206b3b0172ed8dec05872f7abdc7 | Muertogon/2pythonPam | /exercise3.py | 188 | 3.609375 | 4 | c = []
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = int(input("input number: "))
for i in range(len(a)):
if a[i] < b:
c.append(a[i])
for i in range(len(c)):
print(c[i]) |
2e0396cdae982499d26ab3618392fec1c9af7d58 | zelzhan/Challenges-and-contests | /LeetCode/sqrt(x).py | 660 | 4.09375 | 4 | '''Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.'''
class Solution(object):
def mySqrt(self, x):
"""
... |
e12cf5bf91590104b254a7e298dd629017449dc0 | narnat/leetcode | /bt_is_cousins/cousins.py | 3,237 | 3.859375 | 4 | #!/usr/bin/env python3
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isCousins(self, root, x, y):
from queue import Queue
q = Queue(root)
q.put(root)
is_x = is... |
b5dcede26818fe771ac888c3783d730103550bec | NickAlleeProgrammingProjectsPortfolio/pythonWorkBookProjects | /makingExcelFile.py | 530 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 11 19:13:59 2020
create new folder and create an excel file in it.
add my the argument to the excel file
@author: nick
"""
import os, openpyxl
p = os.getcwd()
try:
os.mkdir("excelFileFolder")
except:
print("folder already exists")
os.chdir... |
ae76e03f27f31e4e125d8616c094a629e8ccdbb1 | Morena-D/Level-0-coding-challenge | /Task0_8.py | 376 | 3.796875 | 4 | def time_convert(t):
hours = t // 60
minutes = t % 60
if hours == 1 and minutes ==1:
return f"{hours} hour and {minutes} minute"
if hours == 1:
return f"{hours} hour and {minutes} minutes"
if minutes == 1:
return f"{hours} hours and {minutes} minute"
return f"{hours... |
ef1f0ca3270844afb5be8f8892196f47b10252ea | toniferraprofe/septiembre | /escribir.py | 326 | 3.890625 | 4 | '''
ESCRIBIR en Disco en Python
'''
nombre = input('Nombre: ')
# Escritura
with open('file.txt', 'a') as f:
for i in range(5):
f.write(f'{nombre}\n')
f.close()
# f = open ('file.txt','w')
# f.write(nombre)
# f.close()
# Lectura
with open('file.txt','r') as f:
for line in f:
print(... |
6889a07d22b0b90ce37a6f2c4df7f9bfe8c28d02 | devinyi/comp110-21f-workspace | /exercises/ex01/hype_machine.py | 394 | 3.6875 | 4 | # TODO: Write docstring here
"""Let's cheer someone up."""
# TODO: Initialize __author__ variable here
name: str = input("What is your name? ")
# TODO: Implement your program logic here
print("You entered: ")
print(name)
print("Go out there and do your best " + name + "!")
print(name + " is the GOAT!")
print("Keep movi... |
3ae2869e1e8e0dc0133b46231024224d369a2203 | deivid-01/manejo_archivos | /json/jsontools.py | 455 | 3.515625 | 4 | import json
def saveJSON(data,fileName):
try:
with open(fileName,'w') as json_file:
# Guardar la informacion
json.dump(data,json_file)
print("Archivo "+fileName+" guardado")
except :
print("Archivo no fue creado exitosamente")
def readJSON(fileName):
with... |
b194e9618df59bd9580504e7017cf1e8c16d8f20 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/MergeTwoSortedLists.py | 1,001 | 3.828125 | 4 | class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1... |
db7439661ef0a91532197e7eb5f433c7175d1adf | SonBui24/Python | /Lesson07/Bai03.py | 140 | 3.75 | 4 | list_ = ['Tôi', 'Yêu', 'Thích']
s = input("Nhập chuỗi")
s1 = []
for i in list_:
s1.append(i + s)
print(f"List mới là: {s1}")
|
b66e8843fbb48849145d927f27dd7ebd7b6cec54 | glibesyck/URest | /urest/additional_functions.py | 1,788 | 3.796875 | 4 | """
Additional functions for work (transformation of data).
! converting
! sorting_tuples
! random_choice
! first_elements
"""
import random
def converting (dictionary : dict) -> list :
'''
Return the keys : values as list of tuples (keys, values).
>>> converting ({'a' : 3, 'b' : ... |
331994596cb4c442bbcc0168a96d39ed5e45dc28 | Aasthaengg/IBMdataset | /Python_codes/p03042/s191121905.py | 190 | 3.59375 | 4 | s = input()
if 0 < int(s[:2]) <13 and 0< int(s[2:]) < 13:
print("AMBIGUOUS")
elif 0 < int(s[:2]) < 13:
print("MMYY")
elif 0 < int(s[2:]) < 13:
print("YYMM")
else:
print("NA") |
6dacdb8e6ccb4ad7bfec9e9180038c60be5703cd | CppChan/Leetcode | /medium/mediumCode/BinarySearchTree/LargestBSTSubtree.py | 732 | 3.546875 | 4 | class Solution(object):
def largestBSTSubtree(self, root):
if not root: return 0
return self.findBST(root)[0]
def findBST(self, root):
if not root:return None
elif not root.left and not root.right:
return (1, (root.val,root.val), True) # (root.val,root.val) is the min and max from this subtree
o... |
b8faf85858958db46d76cad4704067c8726982c7 | KatyaKalache/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 158 | 3.71875 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
squares = []
for row in matrix:
squares.append([i*i for i in row])
return squares
|
3d946fdafdbbfed302feaafd27ac132947b04f58 | orgail/SkillFactory | /Python/C1.10/C1.10.3/Clients.py | 715 | 3.671875 | 4 | # Класс Clients содержит методы наполнения и получения данных списка клиентов
class Clients:
def __init__(self, clients, name = "", balance = 0):
self.name = str(name)
self.balance = str(balance)
self.clients = clients
def set_clients(self):
if self.name:
self.clien... |
2339f7827eec58d7889a91bbe10b52b426fd79ea | BleShi/PythonLearning-CollegeCourse | /Week 6/6-九九乘法口诀表.py | 172 | 4.03125 | 4 | # 打印生成九九乘法口诀表
for i in range(1,10): # 行
for j in range(1,i+1): # 列
print(i,"*",j,"=",i*j,end=" ") # 横着生成
print() # 换行 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.