blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
068add47738d733f2302f81a6a4c6e49899ef25a | MaximSinyaev/CodeWars | /c6kyu/findTheUniqueNumber.py | 291 | 3.609375 | 4 | """
Description:
There is an array with some numbers. All numbers are equal except for one.
Try to find it!
url: https://www.codewars.com/kata/585d7d5adb20cf33cb000235
"""
from collections import Counter
def find_uniq(arr):
count = Counter(arr)
return count.most_common()[-1][0]
|
2740a84bc81f564dbe840cb12e63843a69597c16 | zeronnath/myPython | /cote/cote_final_1.py | 1,161 | 3.515625 | 4 | # 최종평가
# 과제1 팰린드롬
# 문자열을 뒤에서부터 읽어도 원래 문자열과 같은 단어를 팰린드롬이라 한다.
# 입력으로 주어진 문자열이 팰린드롬인지 판별한 뒤, 팰린드롬이면 빈 문자열을 출력한다.
# 입력된 문자열이 팰린드롬이 아닐 경우 문자열을 반으로 나누어 앞부분의 단어를 기준으로 팰린드롬 단어로 만드는 함수를 작성하시오.
#
# 예시 입력1:
# 입력: s = 'abcdcba'
# 출력: ''
#
# 예시 입력2:
# 입력: s = 'bannana'
# 출력: 'bannab'
#
# 예시 입력3:
# 입력: s = 'wabe'
# 출력: 'waaw'
def ... |
c7430c7896a2a514eff5b99705af9731ad7a097e | JasmineIslamNY/Thinkful | /snippets-app/snippets.py | 3,675 | 3.6875 | 4 | import logging
import csv
import argparse
import sys
# Set the log output file, and the log level
logging.basicConfig(filename="output.log", level=logging.DEBUG)
def put(name, snippet, filename):
""" Store a snippet with an associated name in the CSV file """
logging.info("Writing {!r}:{!r} to {!r}".format(name, sn... |
db1ff24371beeab1fb6888db4bdfe487e0680d07 | Werdna629/roulette | /game.py | 5,353 | 3.5625 | 4 | from enum import Enum
import random
class Color(Enum):
BLACK = 0
RED = 1
GREEN = 2
class Parity(Enum):
EVEN = 0
ODD = 1
class Zone(Enum):
FIRST12 = 0
SECOND12 = 1
THIRD12 = 2
FIRST18 = 3
SECOND18 = 4
FIRSTCOL = 5
SECONDCOL = 6
THIRDCOL = 7
class Space:
def __i... |
438e75cb1e5c05202a0cd679fdf0084fa0496c1d | marccarre/google-code-jam | /cj2021/r1c/roaring_years.py | 994 | 3.75 | 4 | '''
$ python cj2021/r1c/roaring_years.py < tests/cj2021/r1c/roaring_years.txt
Case #1: 2021
Case #2: 2122
Case #3: 78910
Case #4: 123
'''
from typing import List, Tuple
def main() -> None:
testcases = int(input())
for i in range(1, testcases + 1):
y = int(input())
next_y = next_year(y)
... |
e31d7b62239e8ecaa59faea3c763f84360b32ea3 | CoderSahara/Python_Study | /第1天/07-打印倒等边三角形.py | 396 | 3.734375 | 4 | # -*- coding:utf-8
i=int(input("请输入行数:"))
a=0
while a<i: #假设i=4,打印4行,a从0开始,当a=3最后一次循环
b=0
while b<a: #打印当前行前面的空格,第一行不打印空格,第二行打印一个空格...
print(" ",end="")
b+=1
c=i-a
while c>0: #打印* , 第一行打印4个*
print("*",end=" ")
c-=1
print("")
a+=1
|
3df839d65f872d02dd8d7e5fea37f3e001aa75bd | Gopi30k/DataStructures_and_Algorithms_in_Python | /02_RecursionProblems/06_Reverse_string.py | 559 | 4.125 | 4 | def reverseString(string: str): # METHOD - 2
# return string[::-1] # METHOD - 1
revString = ''
for i in string:
revString = i+revString
return revString
def reverseStringRecusrsively(string: str): # METHOD -3
if len(string) <= 1:
return string
return reverseStringRecusrsively(s... |
cf072e4a116bbfc1e001a4767f4ee69651f71d7c | shoemakerdr/cracking_the_coding_interview | /python/problems/ch02/p02.py | 373 | 3.828125 | 4 |
"""
Problem 2.2
Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.
"""
def kth_to_last(n, l):
p1 = l
p2 = l
while n > 1 and p2.next is not None:
p2 = p2.next
n -= 1
if n > 1:
return None
while p2.next is not None:
p1... |
b7e858f96062c5e850934097956ea11cf1e79638 | NoelineCRI/course-material | /exercices/108/solution.py | 311 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 22 16:38:03 2014
@author: nono
"""
#Write a function sets_diff(A, B) that takes to sets in parameters and return all the unique values containes in A and not B.
def sets_union(A,B):
return(A | B)
a = sets_union(set([1,2,3,4,5,6,7]),set([1,8,9,3]))
print(a) |
ab9149a7ec574058bed18cc4d659b52278430946 | hadanie7/connection_test | /clock.py | 541 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 20:37:38 2017
@author: J
"""
import time
class Clock:
def __init__(me):
me.first = time.clock()
me.last = me.first
def tick(me,wtime):
time.sleep(max(0,me.last+wtime-time.clock()))
while time.clock()<me.last+wti... |
5e79f0c52ee9183dd86b36a0b03494ca38d33bc3 | fjnn/pygame_tutorial | /Animation_Sprites/Monstro/flip_image.py | 600 | 3.78125 | 4 | #!/usr/bin/env python3
from PIL import Image
def flip_image(image_path, saved_location):
"""
Flip or mirror the image
@param image_path: The path to the image to edit
@param saved_location: Path to save the cropped image
"""
image_obj = Image.open(image_path)
rotated_image = image_obj.tr... |
1f2d740ea3556a979ffe4e4d5e513fa3d739a61f | OggyP/Conway-s-Game-of-Life | /main.py | 683 | 3.71875 | 4 | '''
Game of Life
Martin A. Aaberge
'''
from board import Board
import pygame
clock = pygame.time.Clock()
def main():
# assume the user types in a number
user_rows = int(input('how many rows? '))
user_columns = int(input('how many columns? '))
user_TPS = int(input('how many ticks per s... |
b1e45b244294a62f9bd1bda45118df03da18242b | adliaulia/Basic-Python-B4-C | /Pertemuan-2/conditions.py | 531 | 4.0625 | 4 | #condition ==, != , >, <, >=, <=, and, or, not
a = 4
b = 5
if a>b:
print("a lebih besar dari b")
elif a<b:
print("a kurang dari b")
else:
print("a tidak masuk semua kondisi")
c = 4
d = 5
if c == d:
print("c tidak sama dengan d")
elif c != d:
print("c tidak sama dengan d")
else :
print("tidak m... |
53f85881921c5c18b6b1a88bf3b5082fc5f3cb0b | bluedai180/PythonExercise | /algorithms/selection.py | 562 | 3.6875 | 4 | class Selection:
def sort(self, data):
for i in range(len(data)):
min_index = i
for j in range(i + 1, len(data)):
if self.less(data[min_index], data[j]):
min_index = j
self.exch(data, i, min_index)
def less(self, x, y):
ret... |
65f68388a47c9f4500ec2f10af9e5e50b6233acd | jiangjiu/DataStruc-python | /Stack.py | 621 | 3.9375 | 4 | # -*- coding: utf-8 -*-
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, elem):
self.items.append(elem)
def pop(self):
if not self.is_empty():
return self.items.pop()
return
... |
74411a1853d4449c96b0762b7058ce56b9687ee4 | fahimnis/CS303_Computer_Programming_Projects | /Deal.py | 1,358 | 3.65625 | 4 | # File: Deal.py
# Description: HW 10
# Student's Name: Fahim N Islam
# Student's UT EID:
# Course Name: CS 303E
# Unique Number: 50180
#
# Date Created:03/25/20
# Date Last Modified:03/25/20
import random
wins = [ ]
def roll(n):
return random.randint(1,n)
def runOneTrial():
pr... |
0bbcdb550507c1ef854d43e6776a2fc5560f92f0 | jakearmendariz/ride_the_bus | /card.py | 1,793 | 3.890625 | 4 |
class Card:
value = 0
name = ''
type = 0
color = ''
# Type: 0 == heart, 1 == diamond, 2 == spades, 3 == clubs
def __init__(self, value, type):
self.value = value
if self.value == 11:
self.name = 'Jack'
elif self.value == 12:
self.name = 'Queen'
... |
f0e115278cade0a8a1ed21523fd9ec4adf742895 | quanee/Note | /Python/Python/Python39.py | 874 | 3.9375 | 4 | '''
反射:
通过字符串的形式,导入模块;
通过字符串的形式,去模块寻找指定函数,并执行.
利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!
'''
"""
imp = input('输入模块名:')
dd = __import__(imp)
inp_func = input('输入函数名:')
f = getattr(dd, inp_func, None)
f()
"""
for item in [lambda x: i * x for i in range(4)]:
print(item(2)) # 6 6 6 6
for item in [lambda x... |
3fb8d1f5d0ea6666ddafb8f6cf65c3fc8b7200ed | Roninho514/Treinamento-Python | /ex033.py | 449 | 4.09375 | 4 | n1 = int(input('Digite o primeiro numero:'))
n2 = int(input('Digite o segundo numero:'))
n3 = int(input('Digite o terceiro numero:'))
menor = n1
maior = n1
#Verificar qual o menor
if n2 < n3 and n2 < n1:
menor = n2
if n3 < n2 and n3 < n1:
menor = n3
#Verificar qual o maior
if n2 > n1 and n2 > n3:
maior = n2... |
19135d37c1c83182e1fa4c504fbdd3f91573f816 | pulkitpn/python-codes | /string.py | 1,371 | 4.125 | 4 | while True:
print("1 => Length of string")
print("2 => convert to upper")
print("3 => check if a word is present or not")
print("4 => Reverse a string")
print("5 => Split the string")
print("6 => Iterate the string")
print("7 => Slicing of string")
print("8 => strings equal or not")
... |
b7d01dfdc8fc39ddfd53eb1685f0baaf9146b3cf | heitorgomes900/learn_python | /SecurityAlgorithms/congruencia.py | 1,544 | 3.734375 | 4 | import sys
letras = ('','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
"""def main():
head()
if(get_option() == 1):
criptograr()
else:
descriptografar()"""
"""def head():
print('Congruência')
print('\n')
print('Esco... |
42126fd13d53add2390f5a84cbc8d8886c217fa1 | blaza168/zkr | /scripts/utils/multiply.py | 238 | 3.890625 | 4 | # Calculate: pow(a, n) % mod
def square_multiply(a, n, mod):
return pow(a, n, mod)
if __name__ == '__main__':
import sys
a, n, mod = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])
print(square_multiply(a, n, mod))
|
bc36deab4a214ae3b6004efe224b56d197173d9f | JhonveraDev/python_test | /pruebas_estudio/game.py | 850 | 3.921875 | 4 | import random
def run():
numero_aleatorio=random.randint(1,10)
numero_Usuario=int(input("Escribe un numero"))
vidas=5
i=1
while numero_aleatorio != numero_Usuario:
i=i+1
if numero_Usuario < numero_aleatorio:
numero_Usuario=int(input("Busca un numero mas grande, escr... |
b67517379225f49d672308dc8f9d77fe92409016 | zision/Sort-Python | /quick_sort.py | 1,394 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : quick_sort.py
# Author: ZhouZijian
# Date : 2018/9/22
"""快速排序的基本思想:通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,
则可分别对这两部分记录继续进行排序,以达到整个序列有序。
快速排序使用分治法来把一个串(list)分为两个子串(sub-lists)。具体算法描述如下:
1、从数列中挑出一个元素,称为 “基准”(pivot);
2、重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值... |
9cbb7efe67b0c5fbc24c92e299cbde27d04db48b | ParkSeoJune/html_and_python | /python/py_camp/psj/sec06.py | 1,644 | 4.15625 | 4 | print(type(True))
if True:
print('Yes')
if False:
print('No')
if False:
print("You can't reach here")
else:
print('You are here')
# 관계연산자
# <, >, <=, >=, ==, !=
a= 10
b=0
print(a ==b)
print(a!=b)
print(a>b)
print(a>=b)
print(a<b)
print(a<=b)
# 참: "내용", [내용], (내용), {내용}
# 거짓: "",[],(),{}
city="GJ"
i... |
d0e4fa3aeb0d79f5acbb05a21b5ac76b826cb6b9 | August-us/exam | /leetcode/200/153-154 旋转排序数组中的最小值.py | 1,815 | 3.984375 | 4 | from typing import List
'''
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
请找出其中最小的元素。
你可以假设数组中不存在重复元素。
示例 1:
输入: [3,4,5,1,2]
输出: 1
示例 2:
输入: [4,5,6,7,0,1,2]
输出: 0
'''
class Solution:
def findMin(self, nums: List[int]) -> int:
start,end = 0,len(nums)-1
if end >= 0... |
8f0c45d3b72480046285a915e0ac4f420b9d4d13 | mmikiztli/stuff | /report2/part2/reports.py | 2,510 | 3.5625 | 4 | import math
# Report functions
def get_most_played(file_name):
'''What is the title of the most played game?'''
game = open(file_name, "r")
game_inv = game.readlines()
game.close()
maximum = max(float(line.split("\t")[1]) for line in game_inv)
for line in game_inv:
if float(line.split("... |
2d739d0e20d7a215a53425abfc34e9cf77ea8e1d | namlehai/seeds | /seeds/Cell.py | 4,832 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
A Cell object represents a place in the environment where an organism could
reside. If that Cell is occupied by an organism, the Cell object also defines
that organism.
"""
__author__ = "Brian Connelly <bdc@bconnelly.net>"
__credits__ = "Brian Connelly"
import random
from seeds.SEEDSErro... |
e19738009b8595640d5d8d537c07474169b86c6f | arduzj/NSA_COMP3321 | /Lesson_03/03_10.py | 324 | 3.890625 | 4 | #! /usr/bin/env python3
# -*- coding:utf-8 -*-
'''Lecture 03, Exercise 10
Challenge: Write a while loop that prints 100 copies of your favourite snack
on one single (wrapped) line. Hint: use +.
'''
snack = 'coffee'
snack_string = ''
i = 1
while (i < 101):
snack_string += snack + ' '
i += 1
print(snack_strin... |
e0407663f75aad74e3e994be99deefc983b7d02a | 404jv/python-exercises | /ex004.py | 457 | 4 | 4 | string = str(input('Digite algo: '))
print(f'O tipo primitivo é? {type(string)}')
print(f'Só tem espaço? {string.isspace()}')
print(f'É númerico? {string.isnumeric()}')
print(f'É alfabético? {string.isalpha()}')
print(f'É alfanúmerico? {string.isalnum()}')
print(f'Está em maiúsculas? ... |
dd8f52128241d7a1616fcd82ddbe61e09b400354 | raj-andy1/mypythoncode | /sampefunction25.py | 602 | 3.578125 | 4 | """
samplefunction 24 - class 5
Roll the dice
"""
import random
def rollDice():
thisFace = random.randrange(0,7)
return thisFace
while True:
nDoubles = 0
maxRounds = int(input("How many rounds do you want to play?"))
if maxRounds == '':
break
for roundNum in range(0,maxRounds):
... |
6d0ddcacef581e2555525b9bf20482804ef55b2c | shankar7791/MI-10-DevOps | /Personel/Ruthwik/Python/Practice/10mar/prog1.py | 2,332 | 4.3125 | 4 | # a menu driven Program to
# Perform following operations
# 1. Length of String
# 2. Reverse String
# 3. Check Palindrome or not
# 4. Check Symmetrical or not
# 5. Check Permutations and combination
# 6. Check two strings are anagram or not
# 6. Exit
def length(a):
l=len(a)
print(f"The length of {a} is {l}")... |
41a5b84f6af8f9eb4a106f16074091c10b953e2c | duncanmichel/Programming-Problem-Solutions | /Misc/randNumFromStream.py | 902 | 3.796875 | 4 | """
Reservoir Sampling Problem (select a random number from a stream of numbers with 1/n probability
"""
import random
# The resultant random number
res = 0;
# A function to randomly select a item from stream[0], stream[1], .. stream[i-1]
def selectRandom(x,count,res):
# increment count of numbers seen s... |
655d708b451b42858ee0ed82639bbb66625f48fb | noUsernamesLef7/gurps-door-assistant | /door-manager/die_rolls.py | 368 | 3.890625 | 4 | import random
# Takes an integer and rolls that many dice, returning the sum.
def roll_dice(dice):
sum = 0
critical = ""
for unused in range(0, dice):
sum = sum + random.randint(1,6)
return sum
# Takes a target number and rolls a quick contest against it.
def quick_contest(target):
roll, c... |
7665ce042184ac2729ec223fc71aeecc816713ce | Faranaz08/module2 | /fibnterms.py | 208 | 4.15625 | 4 | #print the fibonacci series 0,1,1,2,3,5,8,13....n
nterm = int(input("How many fibonacci terms? "))
n1 = 0
n2 = 1
i=0
while i<nterm:
print(n1)
next_t=n1+n2
n1=n2
n2=next_t
i=i+1
|
a57032ea059b018442df05e579946e8768a7e90f | timothy114/rosebotics2 | /src/capstone_1_runs_on_robot.py | 2,449 | 3.71875 | 4 | """
Mini-application: Buttons on a Tkinter GUI tell the robot to:
- Go forward at the speed given in an entry box.
Also: responds to Beacon button-presses by beeping, speaking.
This module runs on the ROBOT.
It uses MQTT to RECEIVE information from a program running on the LAPTOP.
Authors: David Mutchler, his co... |
a5d5c16203d1e1d6ce04e5a1f537152bad43a776 | nikkiwong/Comp20230_project1 | /Project1/linked_list.py | 2,426 | 4.09375 | 4 | class Node(object):
""" A Node in a Linked List
"""
__next = None
__element = None
def __init__(self, element=None):
self.__next = None
self.__element = element
def get_next(self):
return self.__next
def get_element(self):
return self.__element... |
2e299286ca1af6e93a70d9eedfbd244858fd108a | snebotcifpfbmoll/Damas | /coordenadas.py | 1,081 | 3.828125 | 4 | #!/usr/bin/env python3
from tablero import letras
def separarCoordenada(coord):
# Separar las coordenadas <origen>:<destino>
# .split(":") para separar origen de destino
# [n] para sacar la primera o segunda coordenada
# .upper() para convertirlas en mayusculas
return (coord.split(":")[0].upper(), ... |
e2e5fd71827b7dc1316b7f25feb637834eb4f326 | techytux/Project-Euler | /problem1.py | 374 | 4.3125 | 4 | def problem1(number):
''' If we list all the natural numbers below 10 that are multiples
of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.'''
return sum(x for x in range(number) if x%3==0 or x%5==0)
if __name__ == "__main__"... |
677c51acf037459ea1af283114e8bb4d35ebe5e8 | sourcery-ai-bot/Python-Curso-em-Video | /python_exercicios/desafio034.py | 496 | 3.84375 | 4 | # Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento.
# Para salários superiores a R$1250,00, calcule um aumento de 10%.
# Para os inferiores ou iguais, o aumento é de 15%.
sal = float(input('Informe o valor de seu salário: '))
if sal<=1250:
print('Você terá um reajuste d... |
23ac74fd7a202381c39d63650d3f65ba10d86634 | Muttakee31/solved-interview-problems | /leetcode/35.search-insert-position.py | 716 | 3.6875 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
https://leetcode.com/problems/search-insert-position/
binary search problem. needed help as i was using wrong mid value in conditions.
"""
if target <= nums[0]:
return 0
if target > nums[-1]... |
ddb6fcfba5bdf13678580aba578cc4a709872703 | fenglihanxiao/Python | /Module01_CZ/day4_oop/04-代码/day4/75_1_成员方法调用成员变量.py | 483 | 4.125 | 4 | """
演示成员方法调用成员
"""
class Cat:
def __init__(self):
self.type = "波斯猫"
self.name = None
# def introduce(self):
# print("我是一只%s,我叫%s" % (self.type, self.name))
def introduce(self):
print("我是一只%s,我叫%s,我穿的衣服是%s" % (self.type, self.name, self.color))
cat1 = Cat()
cat1.name = "大帅"... |
4d323ce633a16bc9c93cd029be463a29b1703b44 | Turta-io/Sensor-uHAT | /Samples/Python/env.py | 1,139 | 4.03125 | 4 | #!/usr/bin/python
#This sample demonstrates reading temperature, relative humidity, and air pressure data.
#Install Sensor uHAT library with "pip3 install turta-sensoruhat"
import time
from turta_sensoruhat import Turta_Env_280
#Variables
#Sea level pressure in bar
slp = 1000.0 #Update this from weather forecast to ... |
1a3ca5fd40b24d323c5ba614ebc2c787862d24c3 | ffraganeto/pythonfundamentals | /Aula02/Ex02.py | 1,606 | 4.03125 | 4 | # Coleções
dicionario = {
'Morango': 3.50,
'Banana': 2.20,
'Melancia': 5.00,
}
dicionario['palavra'] # significado
exit()
# Definição da Variáveis
cesta = []
valores = [3.50, 2.20, 5.00]
soma = 0
# Processamento
while True:
print('Escolha o seu produto:')
produto = input('1- Morang... |
e1a69afbcd4fd9ba123c7a4ab4c19311ee6d3daf | koustavmandal95/Competative_Coding | /String algorithm/No_palindromic_substring.py | 660 | 3.796875 | 4 | def isPalindrome(S,N_sub):
mid=len(S)//2
start=0
end=len(S)-1
pal=False
if len(S)==0:
return 0
if len(S)==1:
return 1
while start<end and S[start]==S[end]:
start=start+1
end=end-1
if start==mid:
pal=True
if pal==True:
... |
af790e2fd727fc748cd33cf9f50e759d8b460ce5 | cccccccccccccc/Myleetcode | /295/Find Median from Data Stream.py | 1,976 | 3.71875 | 4 | from typing import List
import heapq
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.smaller = []
self.larger = []
heapq.heapify(self.smaller)
heapq.heapify(self.larger)
def addNum(self, num: int) -> None:
... |
2c2f8c944c850f6cfcfb7e58829ffaad7e3e27ec | LuisaE/cs257 | /hello/hello.py | 116 | 3.984375 | 4 | #Etienne Richart and Luisa Escosteguy
print("Hello World!")
print("Hi Alice, this is bob.")
for i in range(10):
print("Hi grader!") |
332879749bd34792038e9cdd3cdd67856f94b8b8 | monique-tukaj/curso-em-video-py | /Exercises/ex056.py | 1,045 | 4.0625 | 4 | '''Desenvolva um programa que leia o nome, idade e seco de 4 pessoas.
No final do programa, mostre:
- A media de idade do grupo.
- Qual e o nome do homem mais velho.
- Quantas mulheres tem menos de 20 anos.'''
sum_age = 0
average_age = 0
highest_age_m = 0
name_oldest_m = ''
woman_20 = 0
for person in range(1, 5):
... |
d15acf24c1de6ea0393e33366e6fc143f2fd5635 | darthvedder17/data-structures | /Linked List/traverse.py | 681 | 4.09375 | 4 | class node:
def __init__(self,data):
self.data=data
self.next= None
class linkedlist:
def __init__( self ):
self.head= None
def printlist(self):
temp=self.head
while(temp):
print (temp.data)
temp = temp.next
def push(self,... |
04947253157874ee687878b58b94deea824959b1 | ICB-DCM/pyABC | /pyabc/population/population.py | 14,999 | 3.5 | 4 | import logging
from typing import Callable, Dict, List, Tuple
import numpy as np
import pandas as pd
from ..parameters import Parameter
logger = logging.getLogger("ABC.Population")
class Particle:
"""
An (accepted or rejected) particle, containing the information that will
also be stored in the databas... |
2f6d06f1ce760918ae36a03998814e65a44d49ed | Shiirima/Learning | /formation-udacity/web-development-course/lesson 2/Validation test/Day.py | 152 | 3.734375 | 4 |
def valid_day(day):
if day and day.isdigit():
day = int(day)
if day > 0 and day <=31:
return day
print valid_day('35')
|
19a6a1ae76b171cf943b700547b297755b1b693f | slz250/interview_qs | /ctci/kth_to_last.py | 1,035 | 3.703125 | 4 | def kth_to_last_iter(node, k):
"""
hit end to find length
traverse from beginning length-k nodes
:param node:
:return:
"""
curr = node
length = 0
while curr is not None:
length += 1
curr = curr.next
curr = node
for i in range(1, length - k):
curr = cu... |
cfd67790c716980aa66e7fa4dc92ba0ecf0416af | summum/ProjectEuler | /77_old.py | 2,019 | 3.625 | 4 | #!/usr/bin/python
import sys
def isPrime (n) :
if n < 4 :
return True
if n%2 == 0 :
return False
for i in range ( 3, int (n/2) + 1, 2 ) :
if n%i == 0 :
return False
return True
def primesLessThanN (n) :
primes = []
for i in range ( 2, n ) :
if isPrime (i) :
primes.append (i)
return primes
... |
c133628c84894ba053af65937fc4e0e559f673f2 | AlinGeorgescu/Problem-Solving | /Python/704_binary_search.py | 475 | 3.890625 | 4 | #!/usr/bin/env python3
import ast
def main() -> None:
nums = ast.literal_eval(input("Enter nums: "))
target = int(input("Enter target: "))
start = 0
end = len(nums) - 1
while start <= end:
mid = (start + end) // 2
if target == nums[mid]:
print(mid)
return... |
01ccd34b05f9b5d1a885453d0cc6f4d3eefaef97 | gabialeixo/python-exercises | /exe102.py | 611 | 4.15625 | 4 | #Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e
#o outro chamado show, que será um valor lógico(opcional) indicando se será mostrado ou não na tela o processo de cálculo fatorial.
def fatorial(num, show=False):
f = 1
for c in range(num,... |
3a11039b2b0d2c9c5d2ca9687539e352ddb71ded | Lennoard/ifpi-ads-algoritmos2020 | /Fabio01_Parte02/f1_p2_q10_soma_inverso.py | 314 | 4 | 4 | # Leia um número inteiro (3 dígitos), calcule e escreva a soma do número com seu inverso.
n = int(input('Insira um número inteiro de 3 dígitos: '))
c = n // 100
d = (n % 100) // 10
u = n % 10
n_inverso = (u * 100) + (d * 10) + c
print(f'A soma entre {n} e seu reverso ({n_inverso}) é {n + n_inverso}') |
38ca7c692e926dd1657c1231faa394e2a7e009cc | botOctavio/test-MachEight | /src/functions1.py | 1,316 | 4.03125 | 4 | from . import formatter, message
def On2(data : list, totalHeight: int, fromDict=True):
"""This algorithm represents the O (n ^ 2) optimization and it does not
need to do what it should do, it only represents the upper limit of the
test on python
Args:
data (list): List of data that will be c... |
711ab1e03badb3de75de7294037467012d65f90b | SanderUbink/CVE-2020-12712 | /jobscheduler-decrypt.py | 947 | 3.640625 | 4 | """
Author: Sander Ubink
Date: 20-04-2020
Description: Decryptor for passwords stored in a Jobscheduler (S)FTP profile configuration file. The password is encrypted using the name of the profile as the key. E.g. if the profile starts with '[profile example]', the key is 'example'.
"""
import pyDes
import base64
import... |
9e35a351160b5ea61b04f05be1eb44f57ecebcfe | mgarciareimers/pythonCourse | /randomGame/main.py | 1,048 | 3.828125 | 4 | from random import randint
# Method that asks for the number
def ask_for_number():
random_number = randint(0, 10)
valid = False
while not valid:
number = input('\n¿En qué número del 1 al 10 estoy pensando? ')
try:
if 10 < int(number) < 0:
raise ValueError
... |
3ae1ca5c67c9018182103c35fa47831fd9836e52 | theamistudy/Python_exercises | /venv/TypesOfVariable/IfStatement.py | 626 | 3.84375 | 4 |
import numpy as np
from numpy.random import randn
print(randn())
print("hello")
#----- If statement ------- -2 -1 0 1 2 ----------
x = randn()
answer = None
if x >1:
answer = "Greater than 1"
else:
if x >= -1:
answer = "Between -1 and 1"
else:
answer = "Less than -1"
... |
f0b31e25057f1ebe7dba4780469c08c76a0b7d55 | dawagja/Calculadora | /calculadora.py | 1,203 | 3.90625 | 4 | # -*- coding: UTF-8 -*-
'''
@author: Jose Antonio Aguilar Granados
'''
import os
from Pcalculadora.funciones import *
def menu():
"""Función que limpia la pantalla y muestra nuevamente el menu"""
os.system('cls') # NOTA para windows tienes que cambiar clear por cls
print ("Selecciona una opción")
pri... |
c323aa23f1b52b28c385892dde0c30f978da5aa6 | bharathkumarreddy19/basicpythonprograms | /swapping_two_numbers.py | 404 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 19:39:28 2020
@author: bhara_5sejtsc
"""
a = float(input("Enter the first number: "))
b = float(inout("Enter the second number: "))
#before swapping
print("Before swapping")
print("Value of a: ", a , "and y : ", b)
#code for swapping
a , b = b , a
... |
0dd564c9ec118b6ab6323eccabc8304d63041320 | agnaka/CEV-Python-Exercicios | /Pacote-download/Exercicios/ex045.py | 1,486 | 3.8125 | 4 | from random import randint
print('-=' * 20)
print('\033[1;34mVAMOS A JOGAR JANKENPÔ!!!\033[m')
print('-=' * 20)
print('''SUAS OPÇÕES:
[1] Pedra
[2] Papel
[3] Tesoura''')
choice = int(input('Qual a sua escolha? '))
print('JAN')
print('KEN')
print('PO!!!')
itens = ('Pedra', 'Papel', 'Tesoura')
compu = randint(1, 3)
# pri... |
9d28f79610770a6d8e7455d3213753b821fe60dc | jaortiz21/Bill_Pay | /Bill.py | 524 | 3.640625 | 4 | # Class to represent Bill object
# Meant to contain valuable information for any bill
# Most important of these are the due dates and total price
from datetime import date
class Bill:
def __init__(self,name,due_date,price,paid):
self.name = name
self.due_date = due_date
self.price = p... |
fc41decbc4d2b1d57f14a3c756a4bc27042692d2 | UWPCE-PythonCert-ClassRepos/Wi2018-Online | /students/John_Sekora/lesson03/Slicing_Lab.py | 3,001 | 4.15625 | 4 | # Write some functions that take a sequence as an argument, and return a copy of that sequence:
#
# with the first and last items exchanged.
# with every other item removed.
# with the first and last 4 items removed, and every other item in between.
# with the elements reversed (just with slicing).
# ... |
cc30d97bfa4e07afc50624c6006d2b6187a095dd | Davidhfw/algorithms | /python/linkedlist/25_reverseKGroups.py | 2,103 | 3.8125 | 4 | # 题目描述
# 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
#
# k 是一个正整数,它的值小于或等于链表的长度。
#
# 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
#
#
#
# 示例:
#
# 给你这个链表:1->2->3->4->5
#
# 当 k = 2 时,应当返回: 2->1->4->3->5
#
# 当 k = 3 时,应当返回: 3->2->1->4->5
#
#
#
# 说明:
#
# 你的算法只能使用常数的额外空间。
# 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
# 解题思路1:
# 1 定义一个哨兵节点, 2 定义一个start节... |
7b26ffd3a4977814b696d79325e2a16c45f82b45 | Rudy-Neyra/Rudy-Stuff | /curso/08Herencia/isinstancie.py | 2,002 | 3.859375 | 4 | class Producto:
def __init__(self, codigo, nombre, precio, descripcion):
self.codigo = codigo
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
def __str__(self):
return f"CODIGO\t\t{self.codigo}\n" \
f"NOMBRE\t\t{self.nombre}\n" \
... |
fc154d1bdbb6af331283f308361ef00e4067a21f | isajidh/Tic-Tac-Toe | /tictac.py | 3,622 | 3.8125 | 4 | import random
def display_board(board):
print('\n'*100)
print(board[7]+'|'+board[8]+'|'+board[9])
print('-+-+-')
print(board[4]+'|'+board[5]+'|'+board[6])
print('-+-+-')
print(board[1]+'|'+board[2]+'|'+board[3])
def player_input():
marker = ''
while marker.upper() != 'X' and marker.upp... |
8017830cd4e6d258dce7968d9f44ee3918352268 | ThaisMB/Curso-em-Video-Python-Exercicios | /ex015.py | 176 | 3.65625 | 4 | dias= float(input('Quantos dias alugado?'))
km=float(input('Quantos kms rodados?'))
total= (dias*60)+ (km*0.15)
print('O total a pagar pelo aluguel é R${:.2f}'.format(total)) |
b138c15176000a40540091c5ef26a41167a399dc | Zitr0/Cursos_Platzi | /Python/Clases/Clase_4_DifenciasVersiones.py | 183 | 3.875 | 4 | '''
Diferencias en python 2 y 3
Print ""
Print("")
unicode en los strings, caracteres especiales
División de enteros con decimales
'''
mi_input = input("ingresar un numero: ")
|
56acc7b2130d75b4a03c39bed4730aeb5d46051e | mzargham/credcastle | /credcastle.py | 2,896 | 3.5 | 4 | import random # psuedo randomness generator
import numpy as np # import numerical python
import matplotlib.pyplot as plt # import matplot library
# Params
the_end = 100 # days to simulate in credland
village_folk = [[np.random.randint(0,10), 0] for i in range(100)] # initialize village folk and their stuff and cred_ca... |
d9c9d2c5c863bfc2cbe45ace6531f622d22ad1f1 | jitendraselvam/LeetCode | /Trees/ConstructStringFromBinaryTree.py | 1,158 | 3.734375 | 4 | # 606. Construct String from Binary Tree
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t:
ret... |
1ce96df8456ef5fbad5c46800b2401b091286ca3 | probaku1234/LeetCodeAlgorithmSolution | /Google/License Key Formatting.py | 662 | 3.71875 | 4 | """
URL : https://leetcode.com/explore/interview/card/google/67/sql-2/472/
"""
class Solution(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
temp_string = S.replace('-','').upper()
print(temp_string)
inde... |
32b5304c29497610aa344147f5ad899fab3cca9e | mercykylax/Example5 | /shape.py | 1,254 | 4.03125 | 4 | class Circle:
def__init__(self,area,radius,circumfrence):
self.radius=radius
self.area=area
self.circumfrence=circumfrence
def area(self,area):
self.area = 3.142*r^2
print(area)
def circumfrence(self,circumfrence):
self.circumfrence=3.14*r+r
print(circumfrence)
class Sq... |
9e96c229587812c7fda57a86835a8f1ef2c3dae7 | isabelriches/my-final-project | /hearts master.py | 4,635 | 3.8125 | 4 | import random
#all possibilities for what a card could be
previously_played = []
hearts_broken = False
cards = []
points = 0
class card:
suit = {
0: "spades",
1: "hearts",
2: "diamonds",
3: "clubs",
}
value = {
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9... |
d253f530c4f4a7e69234c2d3849a88f4bcfc3c22 | aaroncymor/coding-bat-python-exercises | /String-1/extra_end.py | 335 | 4.1875 | 4 | """
Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The
string length will be at least 2.
"""
def extra_end(str):
if len(str) == 2:
return str * 3
elif len(str) > 2:
return str[len(str) - 2:len(str)] * 3
"""
def extra_end(str):
end = str[-2:]
return end ... |
d7827785530d0e8c7d69a1a2e412a8adeebaf51a | jineetd/CNN_from_scratch | /test_cnn_layers.py | 705 | 3.5625 | 4 | import unittest
from cnn import Input2D
class TestLayers(unittest.TestCase):
def test_input_layer(self):
# Test for valid input shape dimensions.
with self.assertRaises(Exception) as context:
inp = Input2D((2,))
print(context.exception)
# Verify a valid dimension for input layer.
inp = Input2D((2,3))
... |
2670c92b6a49cbf60a61fcf63302626ec32d97d3 | mvanisimov/PythonProject | /lesson 5/task4.py | 1,466 | 3.828125 | 4 | # 4. Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо
# написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные
# должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл... |
d709f02f8db6b1cbb2afabc1cf0e046d0c72a65a | jessicae5/CodeForChina | /CS Lesson 4 (Wed 07.17.19) /ifElsePractice.py | 179 | 4.03125 | 4 |
age = int(input("Enter age: "))
driveAge = 18
if age < driveAge:
print("You cannot drive")
elif age == driveAge:
print ("Take Lessons")
else:
print("You can drive")
|
a96a828a4eb29252c4a3536999ca1adc3fd22352 | n-Holmes/AdventOfCode2020 | /Day1-ReportRepair.py | 1,732 | 3.78125 | 4 | def get_summing_pair(target : int, elements : list[int]) -> int:
check = set(elements)
for x in elements:
if target - x in elements:
return x
def get_2020_2(elements : list[int]) -> int:
x = get_summing_pair(2020, elements)
return x * (2020 - x)
def get_2020_3(elements : list[int])... |
f6e4d51b8038fa468d38f772c4671871a4137b64 | geosmirnoff/learn-python | /3_old.py | 256 | 3.53125 | 4 | #print("Купи слона")
response = input("Купи слона! ")
while response != "Ок":
response = input("Все говорят '" + response + "', а ты купи! ")
print("Урааа!")
input("Жмякни Enter и купи слона!")
|
b894683c03ff19f8c5851deef13ea32984eab0dc | lobo0616/bysj | /examples/1827402038.py | 941 | 3.75 | 4 | # 学号:1827402038
# 姓名:赵旭佳
# IP:192.168.157.164
# 上传时间:2018/11/12 15:24:48
import math
def func1(a,b):
if int(a)==a and int(b)==b:
result=a
while a<b:
result*=(a+1)
a+=1
result=result*b
ge=0
while result%10==0:
result=res... |
479ccb7a4f13f82ca30152c4ab9891643423807e | Kshumishyn/Python | /Homework #FINAL/finalProject3/PartTime.py | 983 | 3.53125 | 4 | # Homework No. FINAL Exercise No.3
# File Name: PartTime.py
# Programmer: Kostyantyn Shumishyn
# Date: December 14, 2017
#
# Problem Statement: Employee Child Class
from Employee import Employee
class PartTime(Employee):
def __init__(self, firstName, lastName, employeeID, numberClasses):
... |
396816ef452d06e2004e75aae0360d89938c4b58 | YeasirArafatRatul/problem_solving | /uVA/299.py | 517 | 3.609375 | 4 | def train_swapper(carriages):
count = 0
for i in range(len(carriages)):
for j in range(i+1,len(carriages)):
if carriages[i] > carriages[j]:
carriages[i],carriages[j] = carriages[j],carriages[i],
count += 1
print(f"Optimal train swapping takes ... |
41d9e688da5bd3c508551974f9a36d5a8317e2c1 | jwon/adventofcode | /2019/day4/day4.py | 724 | 3.703125 | 4 | PUZZLE_INPUT = '284639-748759'
def is_valid_password(password):
digits = [int(x) for x in str(password)]
adjacent_found = False
for i in range(len(digits)-1):
if digits[i] == digits[i+1]:
adjacent_found = True
if digits[i+1] < digits[i]:
return False
return ad... |
1060cd96ea73e0aceb5b8789614be080d6a8cbb8 | keepmyfavor/yzu_python | /day01/九九乘法表-for-3X3陣列.py | 188 | 3.796875 | 4 |
for k in range(0, 3):
for i in range(1, 10):
for j in range(3 * k + 1, 3 * k + 4):
print("%2d * %2d = %2d " % (j, i, i*j), end = (" "))
print()
print() |
434abc279046b5226cda1a42a6015c13ef329daa | Aasthaengg/IBMdataset | /Python_codes/p02255/s808383206.py | 275 | 3.515625 | 4 | n = int(input())
data = input().split()
array = []
for i in data:
array.append(int(i))
for i in range(1, n):
print(*array)
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
array[j+1] = array[j]
j -= 1
array[j+1] = key
print(*array)
|
2f252ed2da08e3f306d0b97a50ed2b4d04f522a0 | ashburnere/data-science-with-python | /python-for-data-science/2-4-Dictionaries.py | 1,770 | 4.15625 | 4 | '''Table of Contents
Dictionaries
What are Dictionaries?
Keys
'''
'''What are Dictionaries?
A dictionary consists of keys and values. It is helpful to compare a dictionary to a list.
Instead of the numerical indexes such as a list, dictionaries have keys.
These keys are the keys that are used to access valu... |
a422901bd3b7f1dcbdf2529c4768f00943bb4c70 | thalals/Algorithm_Study | /Geonil/problem_solving/week3/BOJ2751.py | 958 | 3.796875 | 4 | import sys
In = sys.stdin.readline
def merge(lst, left, mid, right):
result = []
i = left
j = mid+1
while i <= mid and j <= right:
if lst[i] <= lst[j]:
result.append(lst[i])
i += 1
else:
result.append(lst[j])
j += 1
# 나머지
if mid... |
afdc40122ef03b56c853a3b0576d4c2533a2a43b | hakank/hakank | /z3/p_median.py | 2,316 | 3.625 | 4 | #!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# P-median problem in Z3
#
# Model and data from the OPL Manual, which describes the problem:
# '''
# The P-Median problem is a well known problem in Operations Research.
# The problem can be stated very simply, like this: given a set of customers
# with known amounts o... |
39467dbb11929025d6501f7d914d4b3c4ac5558f | Snepsts/notes | /python/day1.py | 979 | 3.96875 | 4 | #!/bin/python3
import sys
def main():
# Start code given by HackerRank
i = 4
d = 4.0
s = 'HackerRank '
# End code given by HackerRank
# Declare second integer, double, and String variables.
second_i = 0
second_d = 0.0 # Lol its python so this isnt really useful
second_s = ""
#... |
fe0cf0511f1ab88d8af228780a98380b0e7fb7a6 | 0xInfty/GrupoFWP | /Funciones/waveform.py | 2,147 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 19:49:50 2018
@author: 0xInfty
"""
import numpy as np
from scipy.signal import sawtooth, square
def waveform(key, n, m=1):
"""Makes a period of a wave of form 'key' on an array of lenght 'n'.
This function defines a period of a wave. Its waveform is chosen w... |
ab6aa599bd808cd93cc28df119f1e87b935e657d | dapoth/rm_fused_lasso | /src/data_management/functions_for_data_generation.py | 4,273 | 3.53125 | 4 | import math
import random as rd
import numpy as np
from numba import jit
@jit(nopython=True)
def generate_beta(num_features, number_blocks, length_blocks, block_height,
levels=False, spikes=0, spike_height=7):
"""Generate beta with non-overlapping blocks.
Divide the generated_blocks into 1/... |
88de3d563c9550ddea6427c2981a93d236555bea | AmanChaudhary1998/python_training | /Module_3/str_sum_average.py | 192 | 3.796875 | 4 | s = input("enter the name of the subjects along with their marks\n").split(' ')
p= [int(s[i])for i in range(2,len(s),3)]
print("sum is ", sum(p), "percentage is ",round(sum(p)/len(p),2))
|
43371a6fda371551a82bfd33e02c4fda13f7785c | amarelopiupiu/python-resumos | /listas.py | 6,012 | 4.3125 | 4 | """
Podemos adicionar qualquer valor nas listas, as listas aceitam valores repetidos e são mutáveis:
lista1 = [1, 2, 3, 4, 5] -> Lista de números
lista2 = ['F', 'e', 'r', 'n', 'a', 'n', 'd', 'a'] -> Lista de strings
lista3 = [] -> Lista vazia
lista4 = list(range(11)) -> Adiciona valores de 0 a 10 na lista
Podemos... |
1b6d8d6341640abb27738ffe35b518fc1d608e36 | rayhanzfr/latihan_github | /lat6-DictandTuple/lat6-6.py | 346 | 3.78125 | 4 | awal= list(item.lower() for item in input("Masukkan Kalimat : ").split())
kamus={}
values=1
for i in awal:
if i in kamus:
kamus[i] += values
else:
kamus[i] = values
print(kamus)
print("Jumlah kata terbanyak adalah sebanyak"%max(kamus.values()))
for i in kamus:
print("Jumlah Kata %s ada sebanyak %s"%... |
04c00a8fc7f89786276dfea6f74763db7d09ed31 | BoiseState/CS111-resources | /projects/jeopardy/project3_jeopardy_stub.py | 2,344 | 3.96875 | 4 | # Summary:
# author:
# date:
import random
# Constants for the parts of a question
CATEGORY = 0
VALUE = 1
QUESTION = 2
ANSWER = 3
# Constant representing a used question
NO_QUESTION = "____"
# Copy your getInfo function from the minitask
def getInfo(quesInfo, whichInfo):
return "Not implemented"
# Read in... |
acb9205ec1eaa62a9b5897eb0970a8543fa52e6c | Spektralzerleger/PyOpenGL-Billard | /textures.py | 1,809 | 4.1875 | 4 | """
Last modified: 28.06.2020
Texture help function, to load and work with textures efficiently.
"""
from PIL import Image
from graphics import *
def check_file_existance(filename):
"""Help function to check whether a file exists.
Args:
filename (string): Path to the file, e.g. "Textures/1.bmp"
... |
95a7aa1494eb5c531846b7310595a72d708f72a7 | EvgenijGod/interview_tasks | /Largest_BST_in_a_Binary_Tree.py | 1,363 | 4.125 | 4 | """
You are given the root of a binary tree.
Find and return the largest subtree of that tree, which is a valid binary search tree.
"""
class TreeNode:
def __init__(self, key):
self.left = None
self.right = None
self.key = key
def __str__(self):
# preorder traversal
an... |
4ae5aafff25bed20f4aca81ba7c9aaa728ca0884 | ajielinarko/PYTN049ONL005 | /sesi8.py | 2,472 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 19:29:54 2020
@author: user
"""
##Training Python Sesi 8: Advanced Visualization
import numpy as np
import pandas as pd
from PIL import Image
df_can = pd.read_excel(r'C:\tes\python\data-contoh\Canada-data-contoh-sesi7.xlsx',
shee... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.