blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
12968b96b203a6ef03f9bbb3862045177f2f1c64 | Carlos-ZRM/tallerPython | /Proyecto/ordenamiento/insertionSort.py | 550 | 3.96875 | 4 | import random
def insertionSort(list_a,element):
flag = False
if len(list_a) == 0:
list_a.insert(0 , element)
return
i = 0
while(i < len(list_a) ):
if element <= list_a[i]:
list_a.insert(i, element)
flag = True
break
i = i + 1
if not flag :
list_a.insert(len(list_a)... |
8544751266827527e24d63ba0130923b8a090d69 | andrezzadede/Curso-de-Python-POO | /ClassMixin.py | 778 | 4.03125 | 4 | '''
Quando utilizar?
Se você desejar reutilizar uma determinada feature(caracteristica) em várias classes diferentes.
Para melhorar a modularidade
Mixins é uma forma controlada de adicionar funcionalidades as classes
Propriedades:
Nao deve ser extendida
Não deve ser instanciada
Em Python, o conceito de mixins é ... |
8b9dad1d0e76314bbc07118194630d3bc4f7b7fb | andrezzadede/Curso-de-Python-POO | /interfaceclassabstrata.py | 404 | 3.640625 | 4 | # Classe abstrata ou interface
#Uma classe abstrata nãoo pode ser diretamente instanciada, ela serve apenas para que outras classes possam ter ela como base
from abc import ABCMeta, abstractmethod
class MinhaClasseAbstrata(metaclass=ABCMeta):
@abstractmethod
def fazer_algo(self):
pass
@abstr... |
8b177e102a97980bebb269b7cb719b72617bd155 | andrezzadede/Curso-de-Python-POO | /testes/debug.py | 831 | 3.546875 | 4 | # Identifica erros
import logging
#INFO, DEBUG, WARNING, ERROR, CRITICAL - Niveis de mensagens
'''
logging.basicConfig(level=logging.INFO)
print("INFO")
logging.info("Mensagem informativa")
logging.debug("Mensagem de debug")
logging.error("Um erro aconteceu")
'''
# Debug só funciona quando no level é DEBUG
print(f'-... |
7c1c8e21773cf05be04e25f2cc42f9b947929f39 | andrezzadede/Curso-de-Python-POO | /decorators.py | 743 | 4.28125 | 4 | '''
Decorator = Função que recebe outra função como parametro, gera uma nova função que adiciona algumas funcionalidades à função original e a retorna essa nova funçao
'''
'''
def modificar(funcao):
def subtrair(a, b):
return a - b
return subtrair
@modificar
def soma(a, b):
return a + b
print(som... |
958f46e484633323679744cce0303d15e049b431 | xzenggit/mydates | /mydates/Dates.py | 837 | 3.921875 | 4 | import pandas as pd
class Important_Dates():
def __init__(self, birth_day, wedding_day):
"""Initialize class
Args:
birth_day: birth day in the format of 'YYYY-MM-DD'
wedding_day: similar as birth_day
"""
self.birth_day = pd.to_datetime(birth_day)
self.we... |
a5f6438f27e7ba05fbbef25e41df57fc90634b68 | LuisaRestrepo/MisionTIC2022-Ciclo1 | /Semana2/Semana2-2.Ciclos.py | 13,595 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 1. Introducción
# Suponga que le piden mostrar 100 veces el mensaje “Bienvenido a Python”.
# ¿Cómo lo solucionamos con lo que hemos visto hasta el momento?
# In[ ]:
print("Bienvenido a Python")
print("Bienvenido a Python")
print("Bienvenido a Python")
print("Bienvenido a Py... |
056ceeda51ccb6ddf7b7335ed5edb3f6de6641bc | LuisaRestrepo/MisionTIC2022-Ciclo1 | /Semana5/Semana5-1.Listas Ligadas.py | 12,636 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 1. Introducción
# - Una lista ligada es una colección de elementos que están enlazados entre sí, en donde cada elementos contiene un valor hacia los otros elementos.
# - Se dice que es eficiente porque permiten un menor desperdicio de memoria y además los algoritmos para se ma... |
12f37df63cc112944e7b032c0591e147dfb9d389 | veronicabasso/rna_seq | /scripts/select_columns.py | 2,878 | 3.65625 | 4 | # This file reads a text file, and produces another text file which contains the selected columns
# from the original text file.
#
# Format the LIBRARIES.txt file:
# :%s/^M/\r/g
# To get a ^M, you need to do Ctrl-V followed by Ctrl-M
import csv
import re
name = input("Please provide the differentially expressed genes... |
4b6a748460babbac39784b96215df4ac4407cdb6 | PirieD704/drag_game2 | /main.py | 1,072 | 3.96875 | 4 | # for class we want health attack-power and defense
# attackP subtracts from health
# Denfense subtracts from attack power
import sys # Allows the player to have the option exit the game
from hero import Hero #brings in our Hero class
from dragon import Dragon # brings in our Dragon class
import choose
import random # ... |
c987360a8fbbf86ba5a00c7c56ec0b8d603948ad | AlexProutski/Casimir-Programming-2 | /circlefinder.py | 2,377 | 3.5 | 4 | import cv2
import matplotlib
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from PIL import ImageFilter, Image
def find_circle_coords(imagefile, radmin=80, radmax=110, houghaccumulator=0.6, searchrad=190):
''' Pass a raw image, and it will return a list of the identified circl... |
0e3d8ef0d018a59105f5f5a1b39cce08b0bc9937 | gillc0045/CTI110 | /Module4/TurtleDrawing/turtle_square_gillc0045.py | 246 | 3.6875 | 4 | # Turtle drawing a square
# CTI 110
# 22 Jun 2017
# Calvin Gill
import turtle
wn = turtle.Turtle()
turtle.bgcolor("black")
turtle.color("violet")
mellow = turtle.Turtle()
for t in range (4):
turtle.forward(100)
turtle.left(90)
|
f25d333feb9ac0541d756e65e035f31760711745 | gillc0045/CTI110 | /Module6/m6_file_read_examples (1)/m6/m6_2file_multi_read.py | 307 | 3.578125 | 4 | # m6 - file i/o
# norrisa
# 7/5
# open a file, read the contents one line at a time, close it
def main():
# read the contents of "data1.txt" from the same directory
myFile = open("data1.txt","r")
for line in myFile:
print(line)
myFile.close()
main()
|
b201d29f539242f9295b7826df8cd4834b173a02 | gillc0045/CTI110 | /Module3/CTI110_M3HW2_bodyMassIndex_gillc0045.py | 502 | 4.4375 | 4 | # Write a program to calculate a person's body mass index (BMI).
# 12 Jun 2017
# CTI 110 - M3HW2 -- Body Mass Index
# Calvin Gill
weight = float(input("Enter the person's weight (pounds): "))
height = float(input("Enter the person's height (inches): "))
bmi = weight*(703/height**2)
print("The person's BMI va... |
a759f1d5f374469571e3691250f6c4b57a51ba89 | python-practice-b02-927/davit.zohrabyan | /lab2/task_8.py | 327 | 3.953125 | 4 | import turtle as t
from math import sin, pi
def polygon(r,n):
a=r*2*sin(pi/n)
for i in range(n):
t.forward(a)
t.left(360/n)
t.shape('turtle')
r=0
n=3
for i in range(10):
r+=30
t.penup()
t.forward(30)
t.pendown()
t.left(180-(n-2)*90/n)
polygon(r,n)
t.right(180-(n-2)*90/n)
n+=1
input... |
49f9a5e68ade3a0b46ee8d48c4574c7a8baebf11 | HussainWaseem/Learning-Python-for-Data-Analysis | /ListMethods.py | 4,473 | 4.09375 | 4 | ''' Some popular Lists Methods '''
# 1. list.sort() = Modifies the uniform typed-list. Return type = None.
a = [80,45,96,74,100]
print(id(a))
a.sort()
print(a)
print(id(a)) # both ids are same. Therefore it only modifies the old list. Doesnot creates a new object.
print(a.sort()) # Returns None. Since s.sort() ret... |
f74f8032c81b88479718b6bd9e861f1bb04c77c1 | HussainWaseem/Learning-Python-for-Data-Analysis | /NewtonRaphson.py | 1,625 | 4.1875 | 4 | ''' Newton Raphson '''
# Exhaustive Enum = In this we were using guesses but we were going all the way from beginning to end.
# And we were only looking for correct or wrong answers. No approximation.
# Approximation = It was an improvement over Exhaustive Enum in a way that now we can make more correct guesses
# a... |
0f29a27910231b916770d34273c7416154940d03 | HussainWaseem/Learning-Python-for-Data-Analysis | /BasicForLoop.py | 3,462 | 5.0625 | 5 | # Python's for statement iterates over the items of any sequence or iterable (list,tuple,string,dictionary(mapping))
# in the order that they appear in the sequence.
''' For using Range'''
# In a nutshell, range() generates successive Values .
# which is generally used TO ITERATE over with for loops.
# There's man... |
026139b2e0beed35054a503d4c308c5450e6684b | HussainWaseem/Learning-Python-for-Data-Analysis | /FractionsToBinary.py | 1,695 | 4.3125 | 4 | ''' Fractions to Binary '''
# Method ->> Fractions -> decimals using 2**x multiplication -> Then converting decimal to binary.
# -> Then dividing the resultant binary by 2**x (Or right shift x times) to get the outcome.
num = float(input("Give your fraction : ")) # we have to take a float.
x = ... |
346c05201be6379aea4801d2ad28d3b495258b4a | HussainWaseem/Learning-Python-for-Data-Analysis | /Tuples.py | 2,673 | 4.40625 | 4 | ''' Tuples '''
# Immutables.
# defining tuples = With braces or without braces
t = (1,2,'l',True)
print(t)
g = 1,2,'l',False
print(g)
# Tuples are Squences (just like Strings and lists) = So they have 6 properties = len(),indexing,slicing, concatenation,
# iterable and membership test (in and not in)
# Range objec... |
956102fc45403039803dba06475f4cef40b5f7a7 | HussainWaseem/Learning-Python-for-Data-Analysis | /FindString.py | 1,026 | 4.03125 | 4 | ''' In this challenge, the user enters a string and a substring.
You have to print the number of times that the substring occurs in the given string.
String traversal will take place from left to right, not from right to left.
Sample Input:
ABCDCDC
CDC
Sample Output:
2 '''
my_str, sub = input(), input()
count = 0
... |
a989c2cf0708fa25ede98e77ae528815cc5a2f77 | HussainWaseem/Learning-Python-for-Data-Analysis | /DivisorsTupples.py | 1,044 | 4.09375 | 4 | ''' Finding Common divisors and saving them in a tuple '''
def findDiv(a,b): # We wish to go to upto the smallest number to find the 'Common' divisor.
divisor = ()
for i in range(1,(min(a,b)+1)):
if a%i == 0 and b%i == 0:
divisor = divisor + (i,) # Saving that into tupple.
return divis... |
da0cfb0351b06dfd006419197ba19d70c1011632 | branquinhoaa/algorithms-practice | /union_find_algorithm.py | 745 | 3.875 | 4 | # create a class with 2 methods: union and find
# this class will implement the connected component that
# will say if two components are conected or not between them
# to solve it, the array is instantiated with unique numbers and each
# union operation we will change the value of the connected points for the same va... |
6ac8f18784e41a62c441ecb976c76b3749e8d569 | thouseef46/MOHAMMED-THOUSEEF-S-ENLIST-BOOTCAMP | /days 4.py | 321 | 3.984375 | 4 | a=b=c=100
print("divide a by 10",a/10)
print("multiply b by 50",b*50)
print("add c value by 60",c+60)
#------
string_var="abcdef"
print(string_var)
replacedstring=string_var.replace('d','G')
print(replacedstring)
#------
a=10
b=10.5
print("convert a to float=",float(a))
print("convert b to int=",int(b))
... |
0f6e834493b8a87bacce63a61fb68a42bd72278e | thouseef46/MOHAMMED-THOUSEEF-S-ENLIST-BOOTCAMP | /Days11.py | 193 | 3.609375 | 4 |
# Online Python - IDE, Editor, Compiler, Interpreter
import pandas as pd
cars = {"Names": ["AUDI","BENZ","BMW"],"Price": [12000,36000,45000]}
var = pd.DataFrame(cars)
print(var)
print("*"*25)
|
85bdb20c063b623b3ba8b576096318804c70b212 | sakar123/Python-Assignments | /Question24.py | 261 | 4.3125 | 4 | """24. Write a Python program to clone or copy a list."""
def clone_list(given_list):
new_list = []
for i in given_list:
new_list.append(i)
return new_list
print(clone_list([1, 2, 3, 4, 5]))
print(clone_list([(1, 2), ('hello', 'ji')]))
|
8662bff5cc4408a61abdd7763bfc29d5e08cfdc7 | sakar123/Python-Assignments | /Question1.py | 198 | 3.6875 | 4 | s = input("Enter a string")
diction = {}
for i in range(len(s)):
if s[i] in diction:
diction[s[i]] = diction[s[i]] + 1
continue
else:
diction[s[i]] = 1
print(diction) |
c6f8438dd6c2d7c7a441c0b6b493c18190ac0fe1 | sakar123/Python-Assignments | /Question33.py | 425 | 4.09375 | 4 | """33. Write a Python script to print a dictionary where the keys are numbers
between 1 and 15 (both included) and the values are square of keys
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144,
13: 169, 14: 196, 15: 225}"""
def square_upto(n):
dictionary =... |
cc02f947a004d1c929d2a1ca6a79808909ed7d02 | sakar123/Python-Assignments | /Question37.py | 410 | 4.1875 | 4 | """37. Write a Python program to multiply all the items in a dictionary."""
def prod_dicts(dict1):
list_of_values = dict1.values()
product_of_values = 1
for i in list_of_values:
product_of_values = i * product_of_values
return product_of_values
print(prod_dicts({1: 1, 2: 4, 3: 9, 4: 16, 5: 2... |
49f5acd49717204b4f4c7ad7fed70a9eff1191f1 | sakar123/Python-Assignments | /Question16.py | 360 | 4 | 4 | """16. Write a Python program to sum all the items in a list."""
given_list = input('Enter numbers in the list')
given_list_string= given_list.split()
given_list_sum=[]
for i in given_list_string:
given_list_sum.append(int(given_list_string[given_list_string.index(i)]))
sum_of_list = sum(given_list_sum)
print("The... |
2ebbe24152816bcd10252000bc45c49e11b7ea77 | SK556531/CS_1-1 | /1_1/a121_catch_a_turtle_SK.py | 2,899 | 3.546875 | 4 | # a121_catch_a_turtle.py
#-----import statements-----
import turtle as trtl4
import turtle as trtl
import random as rand
import turtle as trtl2
import turtle as trtl3
#-----game configuration----
spot = trtl.Turtle()
score_writer = trtl2.Turtle()
counter = trtl3.Turtle()
start_button = trtl4.Turtle()
spot... |
73092f5ec137b664da1cb0ee18093fcdc1850e90 | ngongongongo/Python-for-beginners | /Chapter 1 - Python Basics/1.7-Practice.py | 3,790 | 4.4375 | 4 | #1.7 Practice
#----------------------------------------
#Question 1
#Add three random grades 0~100 for math, physics, and chemistry
#Find an average grade
#Convert average grade from 100 scale to A-F scale
#Prompt the computer to print out final grade using if statemnt
#Question 2
#Write a machine that giving change... |
69c3484772644518a3245f6a925858232fa066ab | ngongongongo/Python-for-beginners | /Chapter 1 - Python Basics/1.8-Practice.py | 2,669 | 4.4375 | 4 | #1.8 Practice
#----------------------------------------
#Question 1
#Prompt the computer to print from 1 to 10 using loop
#Ask user if he/she wants to do it again using loop
#Question 2
#Write a rock-paper-scissor game
#The winning condition is either the player or the computer win 3 times first
#Hint: import random... |
4ad0f1b638a69a083c6acc6d7a6459c00aa52ccf | FDUJiaG/PyWay | /Base/PySort.py | 3,885 | 4 | 4 | def select_sort(arr): # 选择排序
l = len(arr)
for j in range(0, l - 1):
count = j # 记录最小元素下标
# 每次找出最小元素
for i in range(j, l - 1):
if arr[count] > arr[i + 1]:
count = i + 1
arr[j], arr[count] = arr[count], arr[j] # 实现跟上述代码一样
print('Sorted List:', ... |
da2d3aaac735c2b24e11da78d4d52051fc72a1d9 | alex0parhomenko/MethodOfBarrierFunctionsWithTheQuickestDescentRule | /fast_descent_method.py | 1,368 | 3.515625 | 4 | from scipy.optimize import minimize_scalar
import numpy as np
from helpers import FuncWithGradient
from scipy.optimize import Bounds
def mininize(fn : FuncWithGradient, x, restriction_functions) -> float:
'''
We supose what we optimize our function on convex closed set
:param fn: function for optimize, lam... |
12992730f68a32faddef7190db4536761ec172fc | TEAMLAB-Lecture/basic-math-seoyoonbaek | /basic_math.py | 660 | 3.84375 | 4 | #######################
# Basic Math #
#######################
def get_greatest(number_list):
number_list.sort()
greatest_number = number_list[-1]
return greatest_number
def get_smallest(number_list):
number_list.sort()
smallest_number = number_list[0]
return smallest_number
def... |
7af51e74401e1509fff83666bb7b28d7f7f378cd | pbuzzo/backend-dotm-search-assessment | /dotm_search.py | 3,285 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given a directory path, search all files in the path for a given text string
within the 'word/document.xml' section of a MSWord .dotm file.
Assistance: Enrique Galindo, Jake Hershey, Derek Barnes
"""
__author__ = "Patrick Buzzo"
import os
import sys
import zipfile
im... |
10678f2e6458ff95a51223ef93232d32d78bd77b | fastlater/Python_Fundamental_DataScience | /0 Python Fundamental/29.write_file.py | 329 | 3.734375 | 4 |
# 'a' append : add element to the end of the file
# 'w' write : overwrite the entire file or create a new file
file = open('28.karyawan.txt', 'a')
file.write('\nEuis - Staf Marcomm')
file.close()
# file = open('26.karyawan.txt', 'w')
file = open('27.index.html', 'w')
file.write('<h1>Tes Create HTML from Python!</h1>... |
38d496f7974f76593368000adf79ae5e5fc2cfc9 | gmagannaDevelop/ARN.py | /arnstruct/core/dynamicprog.py | 2,006 | 3.65625 | 4 | import numpy as np
from .sequence import Sequence
# TODO : integrate these methods to Sequence
class RNAStruct(Sequence):
""" Calculate secondary structure by dynamic programming """
def __init__(self, sequence: str):
super().__init__(sequence)
self._n = n = len(self.sequence)
self._m... |
bf0c0893e3f9d26630d51233854ae34695154715 | angrylearners/guessing-game | /guess.py | 699 | 3.78125 | 4 | import random
def guessing(n):
m = int(input())
if (m == n):
print("Congratulation!You got it!")
print("Let's play again!")
main()
# question()
if (m > n):
print("Sorry it is too high.")
ask(n)
else:
print("Sorry it is too low.")
ask(n)
... |
8a96736eb8d882bd742bd59ffec8589cbba5943b | PlumpMath/designpatterns-428 | /Singleton/book.py | 816 | 3.90625 | 4 | #!/usr/bin/env python
from threading import RLock
class Book(object):
"""Reusable Book class using singleton design pattern
Attributes:
__instance: static singleton instance
__lock : lock for the thread safety
name: book name
author: book author
"""
__instance = None
__lock = RLock()
def __new__(c... |
09c2796b52e0bc68c4cc2069c5ab9d261779e321 | Bua0823/python_clases | /clase_2/suma.py | 321 | 3.890625 | 4 | a = float(input('hola, ingrese el primer numero: '))
b = float(input('ingrese el segundo numero: '))
# suma = a + b
# print(f'la suma es: {suma} ')
# def suma(a, b):
# suma = a + b
# print(f'la suma es: {suma} ')
# suma(a, b)
def suma(a, b):
suma = a + b
return suma
resultado = suma(a, b)
print(resultado)... |
c3838b3e9654ed52b5c1353deb01d101520ce6a2 | Bua0823/python_clases | /clase_3/imprimir_numeros.py | 186 | 3.53125 | 4 | def run():
for i in range(1001):
print(i)
run()
# rango = list(range(100))
# print(rango)
# contador = 1
# while contador <= 1000:
# print(contador)
# contador += 1
|
d4caf8442473e71d624651bb9a8ccc67384ef05d | Bua0823/python_clases | /clase_2/imprimir_opcion.py | 1,470 | 4.1875 | 4 | # mensaje ="""
# hola
# como estas?
# elige una de estas opciones por favor
# 1
# 2
# 3
# 4"""
#print(mensaje)
opcion = int(input('ingrese una opcion: '))
#if opcion == 1:
#print(f'la opcion que elegiste es {opcion}')
#print('adios!')
#elif opcion == 2:
#print(f'la opcion que elegiste es {opcion}')
#pri... |
0c5c216e024271752c5cf2cebddfa5d2e70d846c | jingyi-stats/-python- | /python_syntax.py | 865 | 4.1875 | 4 | # Python syntax 语法
# print absolute value of an integer
a = 100
if a >= 0:
print(a)
else:
print(-a)
# print if the input age is adult or not
year = input("Please enter your birth year: ")
print(2020 - int(year))
a = int(2020 - int(year))
if a >= 18:
print("Adult")
else:
print("underage")
# print wh... |
e107d586567c69b47bd4056298bc16563f5ac549 | khjsla/algorithm_study | /khj_personal/repeat.py | 1,723 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# 위 코드: 한글 python 에서 돌리는 법
# 반복문
# range() 의 세번쨰 인자
# for - else 문
# 기억하기
for i in range(11):
print(i)
print("----------------------------------")
for i in range(1, 11):
print(i)
print("----------------------------------")
for i in range(5, 11):
print(i)
print("-------------------... |
06ab340ad6b88e3fbfffba048be4311285a76601 | matveyevichevg/Laboratorky | /Lab2/CheckInput.py | 5,757 | 4.09375 | 4 | #Модуль для ввода и проверки введенного значения
# функция проверки значения, принимает переменную неопределенного типа,
# возвращает True если это число и оно больше нуля, False во всех остальных случаях
def isPositiveNumber(num):
try:
if float(num) > 0:
return True
else:
... |
9c29bf90d7e47e795697a267daa2bebb628c4506 | ameserole/Tamusploits | /Python-Parfait/ciphers.py | 4,189 | 3.640625 | 4 | #Viginere, substitution, and Caesar ciphers.
#All below take case into consideration; a simpler code would just convert
#everything to lowercase.
import sys
global alflist
alflist = ['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']
alf ... |
d0e6ce1849f952f3ac2cdfe6994cd3647d48b4e3 | TENCAT/Senior-Design | /Raspberry_pi_Code/python/example/simpleclient.py | 457 | 3.71875 | 4 | #Name: Rachel Brundage
import socket
client=socket.socket() #Create a socket object
host = ''
port = 20003
print("Host and port set")
client.connect((host,port))
print("Client connected")
message = input("What message would you like to send?\n")
client.send(message.encode('ascii'))
data = client... |
2fd565946438b5c365dc4128fc1ba4021d95379a | ChengBinJin/TensorFlow-Tutorials-Weihai | /src/example04.py | 799 | 3.671875 | 4 | import matplotlib.pyplot as plt
import tensorflow as tf
X = [1, 2, 3]
Y = [1, 2, 3]
W = tf.compat.v1.placeholder(tf.float32)
# Our hypothesis for linear model X * W
hypothesis = X * W
# cost/loss function
cost = tf.math.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session.
sess = tf.... |
41091972af4bcb803c8139008c7417dbfa9f6d55 | sansabelphyuhnin/BootCamp2 | /Tuple.py | 479 | 4.09375 | 4 | Tuple.py
Tuple - ()
t = 12345, 54321, 'hello!'
t[0]
x = list(t)
x[0] = 1000
t = tuple(x)
t
(1000, 54321, 'hello!')
#tuples may be nested:
u = t, (1, 2, 3, 4, 5)
u
#tuples are immutable:
t[0] = 88888
#but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v
fruits = ("apple", "banana", "cherry", "ora... |
df7703598f23a89d25cfd63f30ac92b37bfb015a | kurbatovdv/fogstream_courses | /Practice_1/task_4.py | 716 | 3.984375 | 4 | """
Процентная ставка по вкладу составляет P процентов годовых, которые прибавляются к сумме вклада.
Вклад составляет X рублей Y копеек.
Определите размер вклада через год.
Программа получает на вход целые числа P, X, Y
и должна вывести два числа: величину вклада через год в рублях и копейках.
Дробная часть копеек отбр... |
4a8c0493dead1b83a3046f3138228a7cf9df53ba | vashistaarav1611/AVAppsPY | /DrawingApp/index.py | 979 | 3.765625 | 4 | import turtle
import tkinter as tk
turtle.title("Drawing")
t = turtle.Pen()
t.shape("turtle")
w1 = tk.Tk()
w1.title("Drawing App by Aarav Vashist")
def up():
t.fd(10)
def left():
t.left(10)
def right():
t.right(10)
def back():
t.bk(10)
def pu():
t.penup()
t.shape("square")
def pd():
t.pendown()
t.shape(... |
28a48a3582a11cf364e783a5b3a6f403ad63a366 | PrintTeamX/eBoys | /1D-20A.py | 568 | 3.84375 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
a = int(input('Введіть кількість буханок вчорашього хліба: '))
b = 8.50
c = 60
d = b * a * (c / 100)
print('Кількість буханок вчорашнього хліба: ' + str(a))
print('Зви... |
960dbc444e621b66d9bbcac8945c5800694ea880 | PrintTeamX/eBoys | /1D-21A.py | 114 | 3.53125 | 4 | import math
print("Ціле число: ")
a = float(input())
s = (a*(a + 1))/2
print ("Сума: ",s)
|
71136e25b12fba1ff28031b960bd5792ff6bd6f1 | PrintTeamX/eBoys | /3D-2A.py | 787 | 3.828125 | 4 | import datetime
import random
x = 0
nums = []
def num():
global nums
global x
num1 = '+38(0'
num1 += str(random.randint(0, 9))
num1 += str(random.randint(0, 9))
num1 += ')'
num1 += str(random.randint(0, 9))
num1 += str(random.randint(0, 9))
num1 += str(random.randi... |
15b58c50522001275c6359099186e6d88d569e89 | alayton-sys/CS162Final | /CS 162 Final/Account_Main_File.py | 20,592 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 6 13:15:38 2021
@author: Arianna
@CS 162 Final Project
"""
from Checking_File import Checking
from Savings_File import Savings
import csv
import random
def createSavingsAccount():
print('\nCREATE ACCOUNT\n')
new_account = Savings()
new_a... |
b0866402b38328d8070e078a7acef16b8e9fb7eb | Dhiraj-tech/Python-Lab-Exercise | /greater,smallest and odd number among them in list (user input in a list).py | 400 | 4.21875 | 4 | #WAP to take a user input of a list consist of ten numbers and find (1)greater no among the list (2)smaller no among the list (3) list of a odd number
list=[]
odd=0
for i in range(10):
num=int(input("enter a number"))
list.append(num)
print("minimum no among them:",min(list))
print("maximum no among them:",max(... |
cb15ea5b60a679f0e0a62799762ec008f89393e8 | Dhiraj-tech/Python-Lab-Exercise | /two error in single except in exception handling.py | 242 | 3.78125 | 4 | try:
x=int(input("enter a first num: "))
y=int(input("enter a second num: "))
print("The result is: ",x/y)
except(ZeroDivisionError,ValueError) as ms:
print("Exception name: ",ms)
print("plz provide valid input only ",ms)
|
729a041175683bbb4662dae0baa24d08cd5f0168 | Dhiraj-tech/Python-Lab-Exercise | /turtle of hexagon.py | 169 | 3.765625 | 4 | import turtle
wn=turtle.Screen()
pen=turtle.Turtle()
sides=6
length=70
angle=360//sides
for i in range(sides):
pen.forward(length)
pen.right(angle)
turtle.done() |
ecdcec255b578eb50ac4abf351ada61747f5c7a9 | Dhiraj-tech/Python-Lab-Exercise | /(3) to identify even or odd number.py | 101 | 4.1875 | 4 | print("enter a number")
n=int(input())
if n%2==0:
print("n is even")
else:
print("n is odd")
|
b96f2252a44943ccef0b5cd6950479cf67241857 | Dhiraj-tech/Python-Lab-Exercise | /(4) define a function and show the multiples of 3 and 5.py | 231 | 4.34375 | 4 | #write a function that returns a sum of multiples of 3 and 5 between 0 and limit(parameter)
def function():
for i in range(21):
sum=0
if i%3==0 or i%5==0:
sum=sum+i
print (sum)
function() |
e9eee3acec1e30befcc951b356fb81f2302a4e56 | Dhiraj-tech/Python-Lab-Exercise | /calculator by using def.py | 709 | 4.125 | 4 | print("enter a choice")
print("1 for addition")
print("2 for substraction")
print("3 for multiplication")
print("4 for division")
choice=int(input())
def add():
x=int(input("first number"))
y=int(input("second number"))
z=x+y
print(z)
def substraction():
a=int(input("first number"))
b=int(input(... |
f2b3b70c2d6ec472770e36124143542a57c7e690 | deathlysamurai/python_challenges | /Fibonacci.py | 392 | 4.03125 | 4 | #time complexity = 0(2^N)
fibonacci = []
total_numbers = int(input("Total numbers: "))
while total_numbers <= 0:
total_numbers = int(input("Please enter a positive number.\n"))
for n in range(total_numbers):
if n <= 1:
fibonacci.append(1)
else:
fibonacci.append(fibonacci[n-1] ... |
362222070a59f9e40d88bfda8cc1c4641da12bf1 | smunson/spotify-terminal-client | /spotify-terminal-client.py | 3,838 | 3.53125 | 4 | import urllib.request, urllib.parse, urllib.error
import json
## this example follows the client authorization
class spotiClient():
# I'm going to create a client class to handle requests to spotify
# including managing authorization.
# This is different from Flickr where we just wrote one function
... |
51e2b2dae4278bcaf2432af8bb718978356da3c5 | vaderkvarn/aoc18 | /5/b.py | 1,073 | 3.6875 | 4 | import re
import sys
from string import ascii_lowercase
input = open('input').readline()
#input = 'dabAcCaCBAcCcaDA'
def next(i, removed):
i += 1
if i >= len(removed):
return i
while removed[i] >= 0:
i += 1
if i >= len(removed):
return i
return i
def prev(i, remov... |
a443b4acf86964757b39b1b912c93259629ca1b4 | ButtonWalker/Crash_Course | /4_Exercise2.py | 455 | 4.125 | 4 | for value in range(1, 21):
print(value)
numbers = []
for value in range(1,1001):
numbers = value
print(numbers)
digits = range(1, 1000001)
print(min(digits))
print(max(digits))
print(sum(digits))
# odd numbers
for value in range(1,21,2):
print(value)
for value in range(3, 30, 3):
print(value)
c... |
25858a424c87d830efd357659f36d71100b53f8d | jakekausler/Greek-Language-Learner | /lib/generators/main.py | 15,294 | 3.859375 | 4 | '''
Created on Nov 18, 2014
@author: Jake Kausler
Main class of the program. Start a GUI that allows the user to
generate and translate sentences
'''
from Tkinter import *
import ttk
import tkFileDialog, tkMessageBox
import SemanticGenerator, SentenceGenerator
import os
class Window(Frame):
'''
Main Progra... |
253d5c2591d9df127e45faaa98716f9b17b05ea2 | kstonny/Python-coding-Practice-file | /list counetr.py | 245 | 3.734375 | 4 | def count():
name_list = ["karna", "baban", "annu", "shivareddy", "radhakrishnan", "sambhah", "harikishan", "candy"]
for i in range(0,len(name_list)):
if len(name_list[i])>5:
print(name_list[i])
count() |
00260faa6daba2575bc7aba459ff2f9b88cd92be | goatmxj67/home-python | /pythonworkspace/quiz/quiz04.py | 538 | 3.640625 | 4 | # from random import *
# lst = [1,2,3,4,5]
# print(lst)
# shuffle(lst)
# print(lst)
# print(sample(lst, 1))
from random import *
users = range(1, 21) # 1부터 20까지 숫자를 생성
# print(type(users))
users = list(users)
# print(type(users))
print(users)
shuffle(users)
print(users)
winners = sample(users, 4) # 4명 중에서 1명은 치킨, 3명... |
66b0aa8f683e54075e4efa5f379a110caa39bbf0 | DomomLLL/newpy | /jiaoben/6.py | 216 | 3.6875 | 4 | #/usr/bin/python
x = int(input('请输入1~100之间的一个整型数:'))
a = int(0)
b = int(101)
if(a < x < b):
print('你好棒阿!继续努力')
else:
print('乖乖, 你咋这么不听话呢')
|
7ae82057ebbdc159b1c9719aa7d3b41183219bda | DomomLLL/newpy | /jiaoben/FishAndTurtle/m.py | 1,379 | 3.859375 | 4 | import random
class Turtle():
def __init__(self):
self._x = random.randint(0,9)
self._y = random.randint(0,9)
self._hp = 100
def move(self):
if 1 < self._x <9 :
nowx = self._x +random.choice([1,2,-1,-2,0])
elif self._x <= 1:
nowx = self._x + r... |
dc6d90ccae7cea3e3c18bdc5f7bc3b8b8acf91f6 | jrminter/tips | /ImageJ/py/set_max_val_for_all_channels.py | 729 | 3.65625 | 4 | from ij import IJ
def calc_max_val(n_bits):
"""
calc_max_val(n_bits)
calculate the maximum value for an integer with n_bits
Parameters
----------
n_bits integer
The number of bits in an integer image. Typically
8, 12, or 16 in ImageJ
Returns
-------
max_val double
The maximum value
"""
max_val = ... |
2c3aed05f2a16b983fac45069c284c67af5f27ca | bkoester/SSU | /make_data.py | 8,065 | 3.65625 | 4 | '''Create university synthetic data for testing'''
# write python code to create synthetic college
# transcript table with about 30 courses per student,
# and about 4 courses a term, with a single student
# course per row, and unique student ID for each student,
# and a second table that contains graduating majors and
... |
1b61c84e441edeeb84857dbe50ae988bd9c1ea41 | RA251995/RevolvingField | /ThreePhaseCurrent.py | 1,072 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure(facecolor="white")
ax = plt.axes(aspect=1, xlim=(0, 2*np.pi), ylim=(-1.5, 1.5), frameon=False, xticks=[], yticks=[])
x = np.arange(0, 2*np.pi, 0.01)
r_line, = ax.plot(x, np.sin(x), color="red")
y_line... |
37fb1f6ad85ebc7a62955ff9e53a7f3902ee6b79 | kaustubh2708/INFYTQ-fundamnetals-assignment | /experiment48.py | 726 | 3.859375 | 4 | def find_correct(word_dict):
correct_list=[0]*3
for key,value in word_dict.items():
if len(key) == len(value):
difference=0
for i in range(len(key)):
if key[i]==value[i]:
continue
else:
difference+=1... |
2c797c6c5c3c5f5f534d0d566a2c0937dd99891f | VayneDuan/CQU-NLP-course | /wordSplit.py | 2,848 | 3.609375 | 4 | """
姓名:
段贤维
学号:
20182294
班级:
计科卓越班
"""
# 加载词库, 数据预处理
def loadLib(path):
maxLen = 0 # 记录最长词语的长度
with open (file = path,mode = "r") as f:
data = f.readlines()
#去除 开头的数字 和 末尾的'\n'
for i in range(len(data)):
if(len(data[i])==2):
try:
if(0<int(data[i]... |
9cd6a5567ea14189dd7a63aa14a51af31512f6db | MayankLadha/Trigram_frequency | /trigram_frequency.py | 1,537 | 3.625 | 4 | ########################################
# Written by: Mayank Ladha #
# email: mayankladha27@gmail.com #
########################################
import itertools
from itertools import permutations
import xlsxwriter
workbook = xlsxwriter.Workbook('Trigram_Frequency.xlsx')
worksheet = workb... |
ffcb621fe70ca640e287c8f0574f15585d6df8b1 | montejt/Cyberpunk-Fight-Manager | /FightManager/Test/InitiativeQueueTests.py | 2,139 | 3.609375 | 4 | import unittest
from FightManager.InitiativeQueue import InitiativeQueue
"""
Unit tests for the FightManager.InitiativeQueue Python class
"""
class MyTestCase(unittest.TestCase):
def test_add(self):
# Add 1
queue = InitiativeQueue()
queue.add("eight", 8)
self.assertEqual(queue.q... |
03eb80d11a6d0124dec239990503dff8bbd742b9 | mjneiditch/CSC256_ddg_integration_test | /test_ddg_api.py | 2,880 | 4.03125 | 4 | """
Program: test_ddg_api.py
Name: Matthew Neiditch
Date: 10/19/2020
Course: CSC256.0001
Program Description:
Write a PyTest module that queries the DuckDuckGo api for “presidents of the united states,” and tests that each president is listed in the response. (If you need a list or our presidents, see Presidents (ope... |
25dcd91312e598e8eb9848d996ebd503c9db6e10 | Jiangsir0113/Leetcode | /找出列表中的最大值.py | 112 | 3.671875 | 4 | nums = [3, 5, 6, 9, 8, 4, 0, 1, 2, 7]
n = 0
for i in nums:
if n < i:
n = i
print(n, nums.index(n))
|
a89076fdb0878258c122bff4df875ad3becabc86 | nobe0716/problem_solving | /leetcode/contests/wildcard-matching.py | 1,248 | 3.84375 | 4 | import functools
class Solution:
def isMatch(self, s: str, p: str) -> bool:
@functools.lru_cache(None)
def is_match(s, p):
if len(s) == 0 and len(p) == 0:
return True
if len(p) == 0:
return False
if len(s) == 0:
r... |
de257a65c89c62f6da5af3a4b2545829a503bc2a | nobe0716/problem_solving | /leetcode/sum-of-left-leaves.py | 526 | 3.796875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
def solve(node, from_left):
if node is None:
return 0
... |
f73e82e0b0a1eaf63030e953307aa7aa2b7c198f | nobe0716/problem_solving | /leetcode/insert-delete-getrandom-o1.py | 699 | 3.515625 | 4 | import random
class RandomizedSet:
def __init__(self):
self.pos = dict()
self.keys = []
def insert(self, val: int) -> bool:
if val in self.pos:
return False
self.keys.append(val)
self.pos[val] = len(self.keys) - 1
return True
def remove(self, ... |
27fa92272e5fa59d3adf84dd6dea844fd0f756a4 | nobe0716/problem_solving | /leetcode/implement-queue-using-stacks.py | 678 | 3.921875 | 4 | class MyQueue(object):
def __init__(self):
self.s = []
def push(self, x):
self.s.append(x)
def pop(self):
buf = []
while len(self.s) > 0:
buf.append(self.s.pop())
v = buf.pop()
while len(buf) > 0:
self.s.append(buf.pop())
ret... |
06aa1b28457b6a4c8478e17596956ef24f0107b6 | nobe0716/problem_solving | /codejam/2018/kickstart/h/A. Big Buttons.py | 966 | 3.609375 | 4 | from collections import defaultdict
class Trie:
def __init__(self):
self.halt = False
self.next = defaultdict(Trie)
def get_sum(current_prefix, current_sum, node):
r = 0
# if node.halt:
# r += current_sum
if node.halt:
# print('halt at ' + current_prefix)
retu... |
cf229118a0caab4d1152696cf4d901ac55669b4a | nobe0716/problem_solving | /leetcode/implement-stack-using-queues.py | 563 | 3.59375 | 4 | class MyStack(object):
def __init__(self):
self.q = []
def push(self, x):
self.q.append(x)
def pop(self):
v = None
buf = []
while len(self.q) > 0:
v = self.q.pop(0)
if len(self.q) > 0:
buf.append(v)
self.q = buf
... |
c609b2c9725740741feb5e1ddef7c0eadff69b74 | nobe0716/problem_solving | /hacker_rank/domains/algorithms/strings/morgan-and-a-string_sunghyo.jung.py | 533 | 3.53125 | 4 | __author__ = 'sunghyo.jung'
def is_a_smaller(a, b):
n = len(a)
m = len(b)
if n == m:
return a < b
elif n < m:
return a < b[:n]
else:
return a[:m] <= b
for t in xrange(int(raw_input())):
a, b = raw_input(), raw_input()
c = ''
while len(a) > 0 and len(b) > 0:
... |
5187b11011f5b9c79cff2599dac50ef9eac8d4e4 | nobe0716/problem_solving | /leetcode/linked-list-random-node.py | 593 | 3.671875 | 4 | # Definition for singly-linked list.
from random import Random
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self, head: ListNode):
self.length = 0
self.head = head
self.rand = Random()
node... |
5673ec816c8240ceb8d436f2610d6a49ff7fb041 | nobe0716/problem_solving | /leetcode/validate-binary-search-tree.py | 560 | 3.546875 | 4 | class Solution:
def isValidBST(self, root):
def search(root):
if root is None:
return [True, None, None]
lr = search(root.left)
rr = search(root.right)
if not lr[0] or not rr[0]:
return [False, None, None]
if lr[2] is not None and lr[2] >= root.val:
return [False, None, None]
if rr[1] i... |
ecd368fb9e424c7653e88ab8c3051f407e591d5c | nobe0716/problem_solving | /codeforces/contests/1433/E. Two Round Dances.py | 206 | 3.78125 | 4 | import math
n = int(input())
number_of_groups = math.factorial(n) // math.factorial(n // 2) ** 2 // 2
counts_per_group = math.factorial(n // 2) // (n // 2)
print(number_of_groups * counts_per_group ** 2)
|
6be0fe92977f0ab0cec858697a66d5abe3784c1a | nobe0716/problem_solving | /hacker_rank/domains/algorithms/strings/pangrams_sunghyo.jung.py | 288 | 3.984375 | 4 | __author__ = "sunghyo.jung@gmail.com"
def is_pangrams(str):
s = set()
for ch in str.upper():
s.add(ch)
for ch in map(chr, range(ord('A'), ord('Z') + 1)):
if not ch in s:
return False
return True
print "pangram" if is_pangrams(raw_input()) else "not pangram" |
0f657a0616340ea10cfbbf56ffdd1911edc02fd4 | marmy28/board_game | /strategy/generalfunctions.py | 9,477 | 3.609375 | 4 | #####################
#### Decorators #####
#####################
def makeSureArray(func):
"""Decorator that makes sure the function gets an array of dictionaries.
"""
def checker(make_array, args):
if isinstance(make_array, dict):
new_array = [make_array.copy()]
else:
... |
940329185c6a8f36d3cef3479baf2b8c5364d912 | lw9726/KFIR | /preprocessor/legacy_functions/missingval_return_replaced.py | 1,058 | 3.734375 | 4 | def missingval_return_replaced(missing_value_query, replacement_value, target_column_header, dataset):
"""
Returns the inputted column with a version of itself that has its missing values replaced with the given value.
NaN values will be replaced no matter which missing_value_query is entered, so in such ca... |
00e20fdc6b0216e58460c483350554c531429b3b | lw9726/KFIR | /preprocessor/legacy_functions/print_column_vertically.py | 953 | 4.0625 | 4 | def print_column_vertically(target_column_name, dataset):
"""
Prints each variable of a column to a new line in console.
:param target_column_name: (str) Header of the column to be printed
:param dataset: dataset to column is in
:returns: Strings printed to console
:example:
>>> long_da... |
fef7e4f91aea58a47c0fa09d2fc44189f50174fb | wanyukang/leetcode | /linkedlist/203RemoveLinkedListElements.py | 606 | 3.515625 | 4 | #coding: utf-8
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeElements(self, head, val):
"""def removeElements(self, head: ListNode, val: int) -> ListNode:
"""
new_head = ListNode(0)
... |
35d09f4b6f8f4dd2a3919fab8a0513dfe85a3165 | SinvalVJunior/AI_Deep-Learning-A-Z-Udemy-Course | /Bank_Churn_AI/evaluate_ann.py | 1,268 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 00:39:22 2020
@author: sinval
"""
import preprocessing_data as data
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense
d... |
46d1390a097d1eac5942f974463e2321d4203cb0 | stacygo/2021-05_UCD-SCinDAE-PRJ | /cleaner/cleaner.py | 5,802 | 3.671875 | 4 | from functions import write_df_to_csv, print_pretty_table, show_extended_info
import pandas as pd
import numpy as np
if __name__ == '__main__':
# Read the 'dirty' dataset from a .csv file
df = pd.read_csv('../parser/output/parser_marks_df.csv',
parse_dates=['date'],
dt... |
f72caa0da79b4d4d656d6654596685d6487cbb3a | DeniseArias/EmTechPython | /practica08Comparadores.py | 356 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@author: DELL
"""
operacion=3==5
operacion2=3!=5
operacion3=3>=5
operacion3=3<=5
operacion4="Python"=='Pythoon'
operacion5='Casa'!='Lunes'
Lista1=[1,2,5,7]
Lista2=[1,4,6,8]
print(Lista1==Lista2)
productos=['Cereal','Queso','leche','Pan']
print(productos[2]=='Jug... |
7ed82f0fa0bfd851aa867007feed6c52a2556dbb | DeniseArias/EmTechPython | /practica10OPERADORESASIGNACION.py | 260 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
@author: DELL
"""
numero=0
numero+=10
numero+=5
print(numero)
numero-=9
print(numero)
numero*=2
print(numero)
numero/=2
print(numero)
valor_a=9
valor_a%=2
print(valor_a)
a = 15
a %= 2
print (a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.