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
2e32e2d423badc03ca6181154a7357e9335475e6
nguyenthanhthao1908/classpython_basic_online
/homework/bai_tap_buoi06/bai05.py
484
3.859375
4
"""Bài 05: Viết chương trình tạo ra dict với lớn hơn 3 phần tử, value của mỗi phần tử là một list có lớn hơn 5 phần tử. Truy cập và in ra phần tử thứ 5 trong phần value của mỗi phần tử trong dict""" D1 = { 'dict1': [10, 'th', 78, [58, 4], 45, 'Nguyen'], 'dict2': [20, 'a', 't', 200, 65, 'Thanh'], 'd...
60624f99d6a85fbe779c437437b6908708effc7e
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_resource_w/dictionary/bai7.py
348
4
4
""" 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} """ D = {} for i in range(1, 16...
6aa48df1dad575ed4ca911f0948a2ca6ce05d451
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_resource_w/dictionary/bai14.py
138
4.15625
4
"""Write a Python program to sort a dictionary by key.""" D = {3: 30, 2: 20, 19: 8} for i in sorted(D): print("%i : %i" %(i, D[i]))
6e6cfa2370f65a28fc529d924efc6cb17ee3189b
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_inexample_g/ascii.py
567
3.6875
4
class ascii: #khoi tao class 1 parameres def __init__(self): #thuoc tinh self.symbol = input("enter a symbol: ") def myfunc(self): #phuong thuc if type(self.symbol) is str: #neu symbol la str print("The ASII value of ", self.symbol, "is", ord(self.symbol))...
774c324b7abe762f19956ebae6ea3db472ad2129
nguyenthanhthao1908/classpython_basic_online
/rewrite_code_inexample_g/swap_two_variables.py
504
3.703125
4
class swap: #khoi tao class def __init__(self, num1, num2): #hai thuoc tinh self.a = float(num1) self.b = float(num2) def myfunc(self): #phuong thuc print("so a la: ", self.a) print("so b la: ", self.b) temp = self.a #gan tam thoi s...
2b74fbd753904839b8c799be2c66f345b6f308f8
nguyenthanhthao1908/classpython_basic_online
/homework/bai_tap_buoi02/baiso2.py
658
3.84375
4
"""Bài 2. Lập chương trình tính các tổng sau: S_1 = 1 + x + x^2 + x^3 + ... + x^n S_2 = 1 - x + x^2 - x^3 + ... + (-1)^n.x^n S_3 = 1 + \dfrac{x}{1!} + \dfrac{x}{2!} + ... + \dfrac{x^n}{n!} Trong đó, n là số nguyên dương và x là một số thực bất kì. Cả 2 đều được nhập từ bàn phím """ import math n = int(...
d564eb175f44d9d16ba9cf020d5e8e667904786f
darksacred/Python_L2
/L_2_5.py
313
3.765625
4
my_list = [7, 5, 3, 3, 2] n = int(input('Введите новый результат: ')) for i, sl in enumerate(my_list, 1): if sl <= n: my_list.insert(i - 1, n) break elif n < min(my_list): my_list.append(n) break print(f'Результат: {my_list}')
04a1d4849a4c9d5445eeb89552d7f29483ec3d01
Ahaan-R/Informed-and-Uninformed-Search-Algorithm
/find_route.py
5,417
3.59375
4
# Ahaan Rajesh # 1001768638 # AI 1: CSE-5360 import sys from queue import PriorityQueue def TakeInput(inputfile): graph = dict() try: input = open(inputfile, 'r') for line in input: line = line.rstrip('\n') line = line.rstrip('\r') if line ...
b7cf3dc7a5d8304e19e397853b3eb5a0052d3fc0
GeeklifeWang/gitworkspace
/my python note/try_except异常处理机制.py
943
3.9375
4
# -*- coding:utf-8 -*- def fudian(x): return float(x) ''' try: x = raw_input('enter:') print fudian(x) except IOError,e: print e except ValueError,e: print e try: x = raw_input('enter:') print fudian(x) except (ValueError,IOError): print 'Error' try: x = raw_input('enter:') p...
4093f1e83609f1951c8ac823602721d98cdc78c1
GeeklifeWang/gitworkspace
/practice/practice2.py
1,714
3.75
4
# -*- coding:utf8 -*- import threading class Thread_Count(object): def __init__(self, n): self.n = n self.result = 0 self.number = [] self.threadlist = [] self.mutex = threading.Lock() def counter(self, arg): r = sum(arg) self.mutex.acquire() sel...
bfc3959b77a36fe05467217f30677849319e822b
GeeklifeWang/gitworkspace
/my python note/除法.py
1,225
3.84375
4
# -* coding:UTF-8 *- class A(): distance = raw_input("distance:") totalTime = raw_input("totalTime:") def velocity(self): self.distance = A.distance self.totalTime = A.totalTime rate = int(self.distance) / int(self.totalTime) print float(rate) a=A() a.velocity() a=raw_inp...
6aecb8ba2acffbad37d09642f4de5d3f4fb6eb93
fervorArd/Hackerrank-Solutions-in-Python-
/45_itertools-combinations-with-replacement.py
257
3.640625
4
from itertools import combinations_with_replacement string = input().split() string[0] = sorted(list(string[0])) returnedList = list(combinations_with_replacement(string[0],int(string[1]))) for j in sorted(returnedList): print(''.join(list(j)))
934787dcb791ae5f6ddd94caba9685938df0b599
ChaitanyaDave/Stock-Market-Analysis
/KBC_Trading.py
10,798
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 11 16:31:04 2019 @author: chait """ import getpass as gp import os from datetime import datetime as dt from datetime import timedelta as td import pandas as pd import KBC_trading_functions as pk #functions def analyse_company(company_df): search_...
1273e08b63216bf884f8eaa56c26be64b73a9def
Whiteshadow-hacker/white_shadow
/series_rhombus.py
383
3.796875
4
def series(n): a=list() for i in range(1,n+1): a.append(i) for i in range(n-1,0,-1): a.append(i) for i in a: print(i,end=" ") n=int(input("enter the number:")) x=(n+(n-2)) for i in range(1,n+1): print(" "*x,end="") series(i) print() x-=2 y=2 for i in range(n-1,0,-...
8297d8eb5ed397008ac8e31689bcb9b3e633746f
4eshanb/Movie-Review-Classifier
/movie_reviews.py
5,181
3.640625
4
""" Created on Apr 15, 2014 @author: Reid Swanson Modified on: April 14, 2015 Modified by: Kendall Lewis Modified on: Oct 24, 2019 Modified by: Wen Cui """ import nltk, random from nltk.corpus import movie_reviews # This will be used for feature selection later on # Initialize it to None so that we u...
2a5e405a969ee25669ec43f173ccfec0446058bd
alicja-michniewicz/online-cache
/cache/cache.py
722
3.65625
4
from abc import ABC, abstractmethod class Cache(ABC): def __init__(self, size: int) -> None: super().__init__() self.size = size self.costs = [] self.cache = [] def request(self, k: int): self.on_request(k) # print("Requested {} on cache {}".format(k, self.ca...
c49d433e80a6251491f7c345aa7180c0e34e3720
LictiEmoret/my_code
/py_snake.py
14,628
3.59375
4
""" Игра змейка в консоли. Управление: стрелочками на клавиатуре. """ import time import os import random from pynput import keyboard import sys class Field(): def __init__(self, score, size): # объект класса Score self.score = score # разрешение нюанса с очищением ко...
7ec739aa48d07a2a8eb84c7e28b2b8227b17e079
Bigg-Iron/152_001
/L_labs/L4/L4_testing.py
9,607
3.890625
4
""" 4.12 L4 - Lab Plan For today's lab we are going to discuss functions, and practice scope and working with multiple return values. Course Logistics Reminder ZyBooks is the primary learning tool for this class. All course material originates here; readings, labs, and assignments. To complete labs and programs in ...
0988bc077b20d8922a6e80004e92a06c6c92b0b8
Bigg-Iron/152_001
/L_labs/L8/L8.py
1,874
3.6875
4
def writeToFile(string, filename): f = open('/Users/lorenzor.bartolo/Desktop/FALL_20/CS_151_001/activities/labs/L8/' + filename,"w") #opening file in write mode allows you to write something in the file f.write(string) pass def printFile(filename): f = open('/Users/lorenzor.bartolo/Desktop/FALL_20...
6c952a8e00c4a823828985e353e4ff04c5c747c8
Bigg-Iron/152_001
/C_activities/C10.py
2,963
4.1875
4
""" 10.1.2: Modify a list. Modify short_names by deleting the first element and changing the last element to Joe. Sample output with input: 'Gertrude Sam Ann Joseph' ['Sam', 'Ann', 'Joe'] """ # user_input = input() # short_names = user_input.split() # ''' Your solution goes here ''' # del short_names[0] # del shor...
69ebbdc906d0a88510bb195df04beaa05b340990
huangtao00/aha-algorithm
/link_array.py
1,390
3.921875
4
#simulation data=[3,6,15,19,27,38] # 0,1,2,3,4,5 pos=[1,2,3,4,5,-1] print ("before insert:") print (data) print (pos) index=0 while index!=-1: print (data[index],end=" ") index=pos[index] print("\n") print ("insert 18") cell=18 data=[3,6,15,19,27,38] # 0,1,2,3,4,5 pos=[1,2,3,4,5,-1] print ("before insert:...
f683cbbba69ce43dbcf7aa072a7b5890b123aadb
kennylugo/Tweet_Generator_Data_Structures_-_Probability
/1.3_anagram_generator.py
1,343
4.15625
4
import sys, random # THIS ANAGRAM GENERATOR IS NOT WORKING YET # method signature def generate_anagram(): # the list method will break a word apart and add each letter to a list data structure list_of_letters_from_word_input = list(sys.argv[1]) # we store the count of the elements in the list above ...
ba1f1d2157c0874500423ad566181235b8954e3a
tittuvmathew/REINFORCE-PSE
/src/initial_controls.py
3,459
3.6875
4
"""Here we generate a random bounded function in a closed interval.""" # NOTE: Chebyshev polinomials of the first kind are useful because they are # defined in the closed interval [-1,1] and bounded between [-1, 1]. # Cheaper to evaluate and define than Fourier series. import random import itertools as it...
cc67c1aeedb7ee74a55908dc86837e71f7f8b56c
caricks32/tictactoe
/tictactoe.py
7,153
3.984375
4
####### FUNCTIONS -> ######## # Print the game board outline along w user pieces (X's and O's) def print_live_gameboard(pieces): print("\t|\t|") print(" " + str(pieces[0]) + " \t| " + str(pieces[1]) + "\t| " + str(pieces[2])) print("\t|\t|") print("--------------") print("\t|\t|") print(" " + ...
0af53ed79a3d2df089f628732cd0f0989ef4e26c
abdullahclarusway/Python_Assignments
/Assignment_9.py
214
4.28125
4
name = input("Please enter your name:").title() my_name = "Abdullah" if name == my_name: print("Hello, {}! The password is: W@12".format(my_name)) else: print("Hello, {}! See you later.".format(name))
146c15c96e35d304f7b67806a38f51f629dbee01
firchatn/python-101-introduction
/week1/for-demos.py
251
4.25
4
""" For use cases """ print("For 1:") for i in range(2, 5, 2): print(i) print("For 2:") for i in range(5, 2, -1): print(i) print("For 3:") l = [1, 5, 9] for i in l: print(i) print("For 4:") s = "hello" for i in s: print(i, end='')
4cdca329acc88488af56ba14e77f32eae73629ad
Kirill-Kuznetsov-git/search
/distance.py
665
4.03125
4
import math def lonlat_distance(a, b): degree_to_kilometers_factor = 111 a_lon, a_lat = float(a[0]), float(a[1]) b_lon, b_lat = float(b[0]), float(b[1]) # Берем среднюю по широте точку и считаем коэффициент для нее. radians_lattitude = math.radians((a_lon + b_lon) / 2) lat_lon_factor = math.c...
40558e746dc111022fe8d3251a9465a73d5783e5
ChristosGrigor/Movies-for-tonight-
/Movie for tonight1.py
5,081
3.5625
4
#part 1 import random print(("-"*34)+("Movie for tonight!!!")+("-"*34)) #part 1.2: lists and dictionary Anime = ["Hauru no ugoku shiro","Tsumiki no ie", "The End of Evangelion", "Kaze no tani no Naushika","One Piece Film Z",] Comedi = ["The Big Lebowski","Monty Python and the Holy Grail", ...
61930222fb451361444667710455d8233a9853bc
lareniar/Curso2018-2019DAW
/1er Trimestre/EjerciciosAlgoritmo2/Ejercicio5.py
670
4.0625
4
"""Algoritmo que nos permita introducir por teclado un número y posteriormente nos diga si el número introducido es primo o no. Un número es primo cuando solamente es divisible por dicho número y la unidad, por ejemplo: 5 es primo solo es divisible entre 5 y entre 1, 6 no es primo, ya que es divisible entre 1, 2, 3 y ...
5474cc84193f02c47d2a4c23e53ebe6f412e303d
lareniar/Curso2018-2019DAW
/2do Trimestre/Diciembre/factorialFunciones.py
679
4.34375
4
# En esta funcion generamos un calculo factorial de un número def factorial(n1): fact = 1 i = 1 while(i <= n1): fact = fact * i i = i + 1 return fact # En esta funcion calculamos la multiplicación del resultado de diferentes factoriales def triple_factorial(n1,n2,n3): resultado...
b8b34d84ae4da1fc72dfcab7c83bba4413194fde
lareniar/Curso2018-2019DAW
/1er Trimestre/EjercicioAlgoritmo2_Hoja3(real)/ejercicio1.py
902
3.703125
4
#Se desea codificar en Java un programa que nos permita introducir # por teclado una cadena de caracteres, seguidamente una letra, # el programa deberá indicarnos el número de palabras de la cadena # que comienzan con dicha letra. Por ejemplo: # Cadena introducida: La casa de Carlota tiene chimenea. # Letra ……………....
35eb35e48c43390f4af7217876f5298fe59220ab
lareniar/Curso2018-2019DAW
/2do Trimestre/Diciembre/arboldenavidad.py
986
4.0625
4
def arbol_navidad(x): estrellas = 1 espacio_tronco = x - 1 while x > 0: espacio(x) estrella(estrellas) espacio(x) print("") estrellas = estrellas + 2 x = x - 1 tronco(espacio_tronco) def espacio(x): for i in range(x-1): print(' ', end = "") ...
47071b6246172fa8907302eef3886ed14a070ee4
lareniar/Curso2018-2019DAW
/1er Trimestre/listas.py
208
3.609375
4
lista = [] suma = 0 for x in range(0,101): lista = x if (x%2) == 0: """suma = suma + x""" print (lista) suma = 0 for i in range(lista): suma = suma + lista[i] print("\n", suma)
d6355aa98540d5e5fd107ad6afd0f35bccab4ebc
lareniar/Curso2018-2019DAW
/1er Trimestre/EjerciciosAlgoritmo/Ejercicio7.py
254
3.9375
4
"""Algoritmo que lea dos números y seguidamente nos muestre siempre la división del mayor entre el menor""" x = float(input("Inserta el primer número: ")) y = float(input("Inserta el segundo número: ")) if x >= y: print(x/y) else: print(y/x)
fffc801fd9b6594e75449233044a172779ecb434
lareniar/Curso2018-2019DAW
/1er Trimestre/EjerciciosAlgoritmo2/Ejercicio7.py
752
4.03125
4
"""Algoritmo que nos permita introducir por teclado dos números, y posteriormente proceda a obtener el cociente y resto de la división entera mediante restas y sumas. El resultado se mostrará por pantalla. 6/2 = 3 (Cociente)""" x = int(input("Inserta un número: ")) y = (int(input("Inserta otro número: "))) resultado ...
82cc70df9dc223cf576015638c15e5e934bfb6b5
muhmunt/python
/latihan ket/lat3.py
1,254
3.671875
4
def batas(): print("==========================================") batas(); print("APLIKASI LAUNDRY KILOAN") print("\nKODE LAUNDRY\t JENIS LAUNDRY\tTARIF/KILO") print("\t\t\t1\t\tPAKAIAN\t\t\t10.000") print("\t\t\t2\t\tSELIMUT\t\t\t20.000") print("\t\t\t3\t\tKARPET\t\t\t30.000") batas(); pl = int(input("Masukkan Kod...
b3caa3404aaab2b1812688e8e3e65b35b7412c4d
BurdenKing/Python
/Chap5_If_statements/5_2_More_Conditional_Tests.py
396
3.921875
4
# string equality my_cat = "Brock" friends_cat = "Peanut" print(my_cat == friends_cat) # lower() my_cat_cap = "BROCK" print(my_cat == my_cat_cap.lower()) # Numerical stuff, + and/or num = 15 fav_num = 24 print(num <= fav_num and fav_num >= 19) print(fav_num < num or fav_num % 2 == 0) # Check if an item exist in a l...
94b787c71882850f856e7a28dce52121c58171e9
BurdenKing/Python
/Chap5_If_statements/5_4_Alien_Colors_2.py
990
3.734375
4
alien_color = 'green' if alien_color == 'green': print(f"Player just earned 5 points") else: print(f"Player just earned 10 points") alien_color = 'Grey' if alien_color == 'green': print(f"Player just earned 5 points") else: print(f"Player just earned 10 points") # 5.5 alien_color = 'green' if alien_c...
04ea05304e34922a587f91b0e78ae641ef321142
BurdenKing/Python
/Chap4_Working_with_Lists/4_13_buffet.py
247
4
4
foods = ("Noodle", "Rice", "Burger", "Drum Stick", "Pepper") # foods[0] = "Noob" # TypeError: 'tuple' object does not support item assignment foods = ("Beef", "Chicken", "Burger", "Drum Stick", "Pepper") for food in foods: print(f"{food}")
0af84b3837df1c18f5538adf1b1d713f42f5e55d
refschool/exercice-python
/OOP/property_decorator.py
584
3.90625
4
#https://www.freecodecamp.org/news/python-property-decorator/ class House: def __init__(self, price): self._price = price @property def price(self): return self._price #protected because one underscore @price.setter def price(self, new_price): if new_price > 0 and isinstan...
216871f87048cc8ee8c6da6c88098ce1d33f04e6
refschool/exercice-python
/exo/exo7.py
668
3.828125
4
nombre_mystère = 90 entree,comptage = -1,0 while (True): entree = input('Entrez un nombre entre 0 et 100 (Entrée pour sortir) : ') comptage += 1 if entree == "": break elif not entree.isdigit(): print ("Réentrez un nombre") elif int(entree) < nombre_mystère: print ("trop pe...
9f4446c0fe8cf2beed77f79c299d7e23473e6eae
refschool/exercice-python
/exo/exo15.py
194
3.65625
4
try: liste = [1,2,5,3] x= int(input('entrez un chiffre:')) print(liste[x]) except IndexError: print('index hors liste') except ValueError as e: print('Entrez un chiffre !',e)
fbce00417b2b05757d093b7fce044b5deb68dccc
refschool/exercice-python
/exo/exo9.py
185
3.71875
4
for nombre in [1,2,3,4,5,6,7,8,9,10]: print(nombre) if(nombre == 4): break for nombre in [1,2,3,4,5,6,7,8,9,10]: print(nombre) if(nombre == 4): continue
b6387f5d4d9abde61ff60fa9954e4395d36d7096
refschool/exercice-python
/pandawork/realtime.py
356
3.59375
4
import matplotlib.pyplot as plt import numpy as np import pandas as pd x = np.arange(100) y = np.random.rand(100) df = pd.DataFrame({"x":x, "y":y}) df2 = df[0:0] plt.ion() fig, ax = plt.subplots() i=0 while i < len(df): df2 = df2.append(df[i:i+1]) ax.clear() df2.plot(x="x", y="y", ax=ax) plt.draw() ...
30b6f7adf37dd1f6949d31a1be265a43916dcf4c
refschool/exercice-python
/test.py
135
3.546875
4
import pandas as pd df = pd.DataFrame({'num_legs': [2, 4], 'num_wings': [2, 0]},index=['falcon', 'dog']) print(df) print(df.iloc[1,1])
f6d620e115571464987c30732ea1a88fe47ab19a
ciaranmooney/procMaze
/maze.py
795
3.859375
4
#! /usr/bin/env python import random def next_row(start_row): next_row = [0]*len(start_row) for each in enumerate(start_row): index, value = each try: if (start_row[index] == 0) and (start_row[index+1] == 0): next_row[index] = random.randint(0,1) except Inde...
ca8e6927eb562cdb4f2a5a686dea3e8dd3ed5739
arthurshmidt/BlogApp
/post_to_sql.py
3,686
3.734375
4
# Python program to read in a blog post and instert it into the sql database import mariadb import sql_com_class import os # general syntax for connecting to MariaDB server # mysql -u root -p # USE to connect # SHOW to display # SELECT FROM to read # DROP to delete def clear_screen(): _ = os.system("clear") def...
5f1df607c99984af8b32cabeb6d38bb9b85d91e3
srinisha2628/new_practice
/cuberoot.py
358
4.125
4
x= int(input("enter a number\n")) ans=0 while ans**3 < abs(x): ans+=1 if(ans**3!= abs(x)): print("it is not a perfect cube") else: if(x<0): ans = -ans print("cube root of "+ str(x)+" is "+ str(ans)) cube=int(input("enter a number")) for guess in range(cube+1): if(guess**2==cube): p...
7d64cd46b5f75a391ebb74164b9ed7b41ec4a334
chorizon/libraries
/scripts/utils/addtofile.py
842
3.6875
4
#!/usr/bin/python3 import argparse import json parser = argparse.ArgumentParser(description='Utility for add a new line on a text file.') parser.add_argument('--file', help='The file to open', required=True) parser.add_argument('--line', help='The new line added to the file', required=True) args = parser.parse_args...
4569e3bdb3288a61cd6a52501cff15e6fa99ea1f
25-vidushi/python
/SavingsAccount.py
996
4.0625
4
class SavingsAccount: def __init__(self,balance,rate): self.saving_balance=balance self.annual_inter_rate=rate def MonthlyInterest(self): interest = self.saving_balance * self.annual_inter_rate / 12 self.saving_balance+= interest def modifyInterestRate(self,new_inter...
830603a9edcfb5edf9f3f2ba1d0d4a5e2a2427d5
Kings42/HelloWorld
/Maquina Dispensadora.py
6,853
3.84375
4
# -*- coding: utf-8 -*- print "Maquina dispensadora" var = int(raw_input("Ingrese el dinero: ")) if var<200: print "Ingrese una cantidad entre 200 y 2500" print var, "pesos han sido devueltos" print "Intentelo de nuevo" import sys sys.exit("Intentelo de nuevo") if var>2500: print "Ing...
eff2d394bb9c6b2c1a4e525df89fe285d7af0b97
yasin-yasco/16_Convert_Milliseconds_into_Hours_Minutes_and_Seconds
/app.py
627
3.640625
4
def convert(milliseconds): seconds=(milliseconds/1000)%60 seconds = int(seconds) minutes=(milliseconds/(1000*60))%60 minutes = int(minutes) hours=(milliseconds/(1000*60*60))%24 result = '' if milliseconds < 1000: result = ("Just %d millisecond/s" % (milliseconds)) elif m...
adf1c2ab782203df011c2d374b136febf7d1747c
mraizer1102/-
/צצצצ.py
1,955
3.765625
4
def hazpana(n,chofen1,list,list1,k): for x in range(0,int(n)): if chofen1[x].isspace() == True: list1.append(' ') else: number1= list.index(chofen1[x]) if number1+k> 25: nu= number1+k nu1 = nu-26 list1.append(list[in...
15f34008cb101d81ac46f97cb27ce843b3366ec0
nickkaranatsios/ruby-utils
/ml/nn_pred.py
1,131
3.59375
4
# This code is a copy from the deep computer vision 2 pdf book. import keras from keras.datasets import mnist from keras.layers import Dense from keras.models import Sequential # Stochastic Gradient Descent from keras.optimizers import SGD import matplotlib.pyplot as plt from keras.preprocessing import image # step 2 ...
aea149c9e24ecc57ce34b8b84452cb16f2b4318e
CharlesGe129/DailyScripts
/CS673/Homework3/p5.py
406
3.765625
4
sortedArray = [0, 1, 1, 2, 3, 3] duplicateArray = {1: [1, 1], 3: [3, 3]} N = len(sortedArray) i = 0 while i < N: print(i) if sortedArray[i] == sortedArray[i+1]: element = sortedArray[i] originalOrder = duplicateArray[element] for j in range(len(originalOrder)): sortedArray[...
8c7232b94e2d3383785893f67938186a5ee70796
CharlesGe129/DailyScripts
/CS686/week_7_math_possible.py
865
3.828125
4
def math_possible(numbers, target): # print(f"try, {target}, {numbers}") if not numbers and target == 0: return True elif not numbers: return False numbers = numbers.copy() pop_num = numbers[0] numbers.pop(0) if math_possible(numbers, target + pop_num): print(f"{tar...
2df999274d69c56852f245e96b18e67ddf5b309a
CharlesGe129/DailyScripts
/CS686/week4_closable.py
1,257
3.890625
4
class Stack: def __init__(self): self.data = list() self.char_map = {'(': ')', '[': ']', '{': '}'} self.index = 0 def push(self, char): if char in self.char_map: if self.index < len(self.data): self.data[self.index] = char else: ...
0dd61418ef648e74636f4f97e5f763982e1da884
CharlesGe129/DailyScripts
/arrayFlattening.py
332
3.75
4
def array_flatten(content, rs): [traverse(each, rs) for each in content] def traverse(content, rs): if isinstance(content, str): rs.append(content) elif isinstance(content, list): array_flatten(content, rs) test = ["aa", "bb", ["cc", "dd", ["ee", "ff"]]] rs = list() array_flatten(test, r...
8fe0a08128c24688bf10749a8b6710b8a9362fc0
east825/python-inference-playground
/control_flow/generators.py
192
3.71875
4
g1 = (x for x in range(1)) print(g1) g2 = (x for x in ['foo', 'bar', 'baz']) print(g2) g3 = (x for x in {1, None}) print(g3) def gen1(): for x in range(1): yield x print(gen1)
0c8a297f9805927ddf2de2fa551e172238324985
ashfaqu3/NLP
/exp1/exp12.py
434
3.59375
4
import nltk from nltk.tokenize import sent_tokenize,word_tokenize from nltk.corpus import stopwords data="Greetings of the day.Hi Ashfaque how are you" print("Sentence:\n") word_tokens=word_tokenize(data) print(word_tokens) print("\n Filtered Sentence:\n") stop_words=set(stopwords.words('english')) filtered_sentence=[w...
fdf54ba8ebc79f4cca818758d09db77a02fd71bf
jiahui-qin/python_learn
/primes.py
489
3.890625
4
from collections import Iterator def _odd_iter(): n=1 while True: n=n+2 yield n def _not_divisible(n): return lambda x: x%n>0 def primes(): yield 2 it=_odd_iter() while True: n=next(it) yield n #print(isinstance(it, Iterator)) it=filter(_not_div...
19379ac00334fa917fc02d21ea2c57bdda2e7145
jiahui-qin/python_learn
/enum_test.py
190
3.65625
4
from enum import Enum, unique #Enum类:枚举类 @unique class Weekdays(Enum): Sun=0 Mon=1 Tue=2 Wed=3 Thu=4 Fri=5 Sat=6 print(Weekdays.Fri) print(Weekdays(1))
0718cd98f0c363e8de80dea6464d04122d523ec7
liuyanfang-git/test_1
/python jiaoben/zhuangshiqi.py
556
3.921875
4
#python 装饰器 #作用:将函数作为参数进行返回给别的函数使用 # def foo(f): # print("执行foo函数开始") # f()#koo() # print("执行foo函数结束") # def koo(): # print("执行了koo函数") # foo(koo) #函数执行规则:函数名 + () def out(func): print("开始执行out函数") def innre(): func() print("执行out函数结束") return innre #@ python的语法糖 @out 使用out这个装饰...
e061d6a05c835edf461323a6b0631cd8375acca7
lalitkapoor112000/Fun-Assignment-on-Python
/Old Macdonald.py
151
4
4
def old_macdonald(st): st=st.title() st=st.replace(st[3],st[3].upper()) return st m=input("Enter a word:") print(old_macdonald(m))
076f59fedeb631a4284093eab8358526ea1390a5
mewilczynski/python-classwork
/program41.py
865
4.375
4
#Marta Wilczynski #February 2nd, 2016 © #Chapter 4 assignment program41.py #Start program #Import math since we will be using PI #Set up a range of numbers, using the for loop. #Calculate area of a circle with "radius", where the equation # will be area = (PI * (radius ** 2)) #Calculate circumfrence with "rad...
b496deacdbb5b1098a24631825f11221a2cbfcb6
mewilczynski/python-classwork
/order32.py
1,681
4.21875
4
#Marta Wilczynski #February 2nd, 2016 © #order32.py #Start program. #Get the number of t-shirts being purchased from the user, #assign to variable "amountOfShirts". #Calculate amountOfShirts * 12.99, assign to variable "priceOfShirts". #Assign number 8.99 to variable "shipping". #Determine discounts by lookin...
2308a0ab570f0695b446490383c3a281403cacc1
htrueman/db2_limited_test
/task2.py
406
3.859375
4
test_string = "Hello! 111---000. I'm test string. Digits: 754." def handle_string(string): letters_count = 0 digits_count = 0 for sign in string: if sign.isalpha(): letters_count += 1 elif sign.isdigit(): digits_count += 1 return "Result:\nLetters - {}\nDigits -...
61a787ee69c3e67a8fbaab6c6d057aeab66245e6
Manish-bitpirate/Hacktoberfest
/python files/story_maker_by_cyoa.py
2,019
4.125
4
name=input("What's your name?") print("Treasure Hunter, a custom story by " + name ) print("You are a brave explorer that was recognized by the world and found an ancient Mayan temple!") opt1=input("Do you walk in? y/n?") opt2="" opt3="" opt4="" if opt1=="y": print("You walk in, your footsteps echoing in the dark. ...
9d3e26a284604321c3ff34275144209b3de313ea
sunnysong1204/61a-sp14-website
/slides/17.py
1,998
3.53125
4
class Range: def __init__(self, low, high): self._low = low self._high = high def __iter__(self): return RangeIter(self) class RangeIter: def __init__(self, limits): self._bound = limits._high self._next = limits._low def __next__(self): if self....
597fa793c9f510235f2c786f7abdd24d2a27b663
sunnysong1204/61a-sp14-website
/slides/lect11.py
1,519
3.890625
4
from ucb import main, interact def indent_lines(s, n): """'s' with all lines prefixed by 'n' blanks.""" return "\n".join(map(lambda line: " " * n + line, s.split('\n'))) import re def indent_lines2(s, n): """'s' with all lines prefixed by 'n' blanks.""" return re.sub(r'(?m)^', ' ' * n, s) # Notes: # ...
b5a4e4e2a514e5273bf50aa5d4326555d8764b9f
sunnysong1204/61a-sp14-website
/slides/23.py
6,720
4.25
4
class Tree: """A Tree consists of a label and a sequence of 0 or more Trees, called its children.""" def __init__(self, label, *children): """A Tree with given label and children.""" self._label = label self._children = list(children) @property def is_leaf(self): r...
6786774819903db96e9008597ea4d8060fc6f217
sunnysong1204/61a-sp14-website
/slides/lect21.py
2,276
4.125
4
class Tree: """A Tree consists of a label and a sequence of 0 or more Trees, called its children.""" def __init__(self, label, *children): """A Tree with given label and children. For convenience, if children[k] is not a Tree, it is converted into a leaf whose operator is children[...
6352b44f555f05ef2456bf692eb49a4410e1e2b1
anjan111/saad_ajay
/006_operator/008_special/002_identity.py
810
3.953125
4
#Special Operator ''' ====>> Identity Operator ========================= ===>> To check the memory loc / id's are same or not 1. is True ===> both id's are same False ==> different 2. is not True ==>> different Fals...
b1e8f5c94e55c41ff916d9d343f052bde06bb947
anjan111/saad_ajay
/003_str/004_str_dicing.py
541
4.03125
4
# string dicing ----> str_var[start_index : stop_index : step_index] ''' ---> To access the step wise character as a sub string from main string ---> we can access in between start to stop index with step values start ----> 0 stop ----> len step ----> 1 ''' var = "python program" print "data with in var :...
81be65f6bf57a305b483a3d7d64b4f74dbd58f4e
anjan111/saad_ajay
/007_control/001_cond/003_salary.py
608
3.75
4
#wap find the salary based on exp exp = input("enter no of years of exp : ") if( exp >=0): if( exp >=0 and exp <=2): print "salary 2.4 lac PA " elif( exp > 2 and exp <= 4): print "salary 4.8 lac PA " elif(exp > 4 and exp <= 6): print "salary 8.0 lac PA " elif(exp > ...
29a17e068122c452c2b4ffa9ac32d84d86aad46a
KeshkOS/SNP-parental-test
/SNPS_OS v1.3.py
8,169
4.1875
4
#importing the packages we will use import os import sys import re import itertools #set a variable for using in while loop print("""---Hello there.This application detect the Single nucleotide polymorphism. It accepts VCF files as an input of the Father,Mother,son. After our marvellous and magical calculations...
bf74914843bb8ad4e81ba45d203d4f45aeaf80da
kate711/day1
/code/元组.py
555
4.25
4
# 创建元组 my_tuple = ('x', 'y', 'z') print('{}'.format(my_tuple)) print('{}'.format(len(my_tuple))) print('{}'.format(my_tuple[1])) longer_tuple = my_tuple + my_tuple print('{}'.format(longer_tuple)) # 元组解包 one, two, three = my_tuple print('{0} {1} {2}'.format(one, two, three)) var1 = 'red' var2 = 'robin' print('{} {}'.f...
e3a047cf2b179f67502eac8e3fd5029af046b110
kate711/day1
/code/杨辉三角2.py
445
3.765625
4
from collections import defaultdict def yanghui(n): triangle = defaultdict(int) for row in range(n): # 每行第一个元素为1 triangle[row, 0] = 1 print(triangle[row, 0], end='\t') # 生成该行后续元素 for col in range(1, row+1): triangle[row, col] = triangle[row-1, col-1] + triang...
3308b86bfae493a53eb1e2c0fef7eae4a7d0abd1
kate711/day1
/data structure/链表/链表建立二叉树.py
1,035
3.890625
4
class tree: def __init__(self): self.data = 0 self.left = None self.right = None def create_tree(root, val): newnode = tree() newnode.data = val newnode.left = None newnode.right = None if root == None: root = newnode return root else: curre...
793a23b8cd6c966228957e704ba90241a3f81d4e
kate711/day1
/data structure/链表/在单向链表中插入新节点.py
2,762
3.75
4
import sys class employee: def __init__(self): self.num = 0 self.salary = 0 self.name = '' self.next = None def findnode(head, num): ptr = head while ptr != None: if ptr.num == num: return ptr ptr = ptr.next return ptr def insertnode(hea...
f79a1f8ad581bde7d0c521f8d9b3bf88f7655b6d
kate711/day1
/data structure/数组结构/矩阵相乘.py
346
3.71875
4
# out(i,j)=a(i,k)b(k,j) import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) b = np.array([[1, 2], [3, 4], [5, 6]]) print(np.dot(a, b)) print(np.matmul(a, b)) print(a.dot(b)) print('---------------------') # # out(i,j)=a(i,j)b(i,j) print(np.multiply(a, a)) print('---------------------') # 普通矩阵相乘 print(np.mat(a)...
527527ec6b1cc93a28d6105a50a0d5344401240e
kate711/day1
/code/快速排序1.py
695
3.671875
4
from random import randint def quickSort(lst, reverse=False): if len(lst) <= 1: return lst # 默认使用最后一个元素作为枢点 pivot = lst.pop() first, second = [], [] # 默认升序排列,True降序排列 if reverse == False: exp = 'x <= pivot' if reverse == True: exp = 'x >= pivot' for x in lst...
7082b31b87ea64e7e57afca78a1edecbd10625f8
LittleSheepH/Practice
/excel数据转换.py
467
3.640625
4
# -*-coding:utf-8-*- # @Time :2019/1/8 22:20 # @Autor :DA BAI CAI # @Email :icewong401@163.com # @File :excel数据转换.py # @Software :PyCharm test="wangdanhui:111111\nkakakakkaka:66666666" a= test.split("\n")#split只能分割字符串,分割之后变为列表 # for item in a: # print('********************',item) # ss=it...
f60869163e8c3fc04453a0fdb6a2a6dd87de1e55
Rodolfombc/invincible-tictactoe
/tictactoe.py
9,203
4.125
4
# -*- coding: utf-8 -*- import random class TicTacToe: def __init__(self): self.board = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] def drawBoard(self, board): """Draws the passed board. Board is a list of 10 strings. Each string represents a position of the board (ignore in...
0b10431aaa89e20c4538dfd50f53554fe16daf31
ValeryMukhin1711/Python_Algos
/3_task_1_v2.py
1,525
4.0625
4
""" Задание 1. Докажите, что словари обрабатываются быстрее, чем списки. Реализуйте две функции, в первой нужно заполнить элементами список, во второй-словарь Сделайте замеры времени выполнения каждой из функций Подсказка: для замеров воспользуйтесь модулем time (см. примеры урока 1) Примечание: eсли вы у...
469c4f915638f416d5c03eacc0b2743a235b1555
amirmc/TheHardWay
/ex05-v2.py
859
3.71875
4
name = 'Amir Chaudhry' age = 31.0 # not a lie height_cm = 175.0 # cm weight_kg = 76.0 # kgs eyes = 'brown' teeth = 'white' hair = 'black' height_in = height_cm*0.3937008 weight_lb = weight_kg*2.20462 print "Let's talk about %s." % name print "He's %d cm tall." % height_cm print "That's", height_in, "in imperial units...
692cb57f985585479db0f866bf1698759b2f87d4
finos/datahub
/datahub_core/datasets/sic_code.py
488
3.765625
4
class SicCode: """ SicCode data class. Represents a specific industry within an Industry Sector.. For example, Commercial Bank within the Finance Sector # Attributes: { code: int name: str } """ code: int name: str def __init__(self, code, n...
b9cba9c7263a823f594def65fb5cbbf7556363e9
suujaan/Python
/weight converter.py
265
4.09375
4
weight = int(input("Enter Your weight: ")) unit = input("Enter (L)bs or (k)g: ") converted = weight * 0.45 if unit.upper() == "L": print(f"You are {int(converted) * float(0.45)} kilos") else: print( f"You are {int(converted) / float(0.45)} pounds")
a10ac23465198fe79d500213d50b8fe8923a534e
crisbern-g/Password-Manager-v2.0
/LoginScreen.py
8,420
3.5
4
import tkinter.messagebox from tkinter import * import dbConnection import sqlite3 class Login_Signup(Tk): def __init__(self, db_connection): Tk.__init__(self) self.login_credentials = {} self.visible_password = False self.db_connection = db_connection #Frame ...
e615bb8deabcf831e20e7da31ae8fd897023ee10
ProfessorJas/Python_100_days
/day_014/higher_order.py
374
3.53125
4
from math import factorial def high_fun(f, arr): return [f(x) for x in arr] def square(n): return n**2 # use the Python plug-in function print(high_fun(factorial, list(range(10)))) # print out [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] # use the self-defined function print(high_fun(square, list(range(1...
494d3a930d2ad1d06541c879812dc26595366fc0
ProfessorJas/Python_100_days
/day_031/public_private_method_ex.py
497
3.78125
4
class Methods(object): # Define a class # Define a public method def publicMethod(self): return 'Public method' # Define a private method def __privateMethod(self): return 'Prviate method' m = Methods() print('Use the object to call:', m.publicMethod()) print('Use the object to ca...
111b3cb6d2a16e162794847257edd366dbb1afa3
ProfessorJas/Python_100_days
/day_031/class_attributes_ex.py
1,269
4.4375
4
class Person(object): # Define class attribute and assign the value nation = 'China' city = 'Shanghai' def __init__(self, name, age): # define object attribute self.name = name self.age = age p1 = Person('Joe Wang', 34) p2 = Person('Javier Amgio', 25) print('Visit the class at...
eb1ba69b3312c5aa005bfc78105fc18daf86aa83
ProfessorJas/Python_100_days
/day_011/dictionary_setdefault.py
189
3.875
4
dict = {'Name': 'Mary', 'Age': 17} print("The value for Age is: ", dict.setdefault('Age', None)) print("The value for sex is: ", dict.setdefault('Sex', None)) print("New dict is: ", dict)
2027aa5e1dc4f9de83c2d23b0a4a47eb44783f96
ProfessorJas/Python_100_days
/day_027/str_method.py
2,311
4.34375
4
str = 'abcabcabc' print(str.count('ab')) # count 'ab' in the str print(str.count('ab', 2)) # count 'ab' in the str from index 2 print(str.endswith('bc')) # endwith check with the string end with some string # true print(str.endswith('b')) # false print(str.startswith('ab')) ...
9e7c846198b684c569f43e0305bedee64c624eff
ProfessorJas/Python_100_days
/day_027/list_meethod.py
2,661
4.21875
4
print([]) # create an empty list object # [] print(list()) # create an empty list object # [] print([1, 2, 4]) # list with the same type print([1, 2, 3, ('a', 'bc', 'defg'), [12, 34, 'amigo']]) # list with different type print(list('abcd')) # listify an iterative object ...
87b86f49c37494ca7fe6907d52101f2ebb096ab8
SamanehGhafouri/Algorithms
/tree_traversal.py
1,794
3.9375
4
import unittest class TreeNode: def __init__(self, value, left_child, right_child): self.value = value self.left_child = left_child self.right_child = right_child three = TreeNode(3, None, None) four = TreeNode(4, None, None) two = TreeNode(2, three, four) seven = TreeNode(7, None, None)...
088b30ae7857cb3825645af6ddf82c208897a940
liwencong666/store
/pingjunshu.py
167
3.890625
4
count=0 sum=0 while count<10: num1=input("请输入数字:") num1=int(num1) count=count+1 sum=num1+sum print("平均数为:",sum/count,)
b06db0e8ca45ac636331c862027b55565b6ada40
liwencong666/store
/工商银行.py
7,055
3.546875
4
import random #随机取数 users = {} bank_name = "中国工商银行昌平支行" #银行名称 def welcome(): print("************************************") print("* 中国工商银行 *") print("* 账户管理系统 *") print("* V1.0 *") print("* 1.开户 ...
61ecd3d8773408ed8808f4353e09aedf687145ec
liwencong666/store
/100qiuhe.py
281
3.640625
4
count=0 sum=0 while count<101: num1=input("请输入数字:") num1=int(num1) count=count+1 sum=num1+sum if num1>0 and num1<101: print ("和为:",sum,) else: print("请输入1-100以内的数字")
bb1853463edfe1ca67b0539d620de616c580a61b
ChunKaiC/Snake
/Button.py
780
3.546875
4
import pygame class Button: def __init__(self, x, y, w, h, color, font, text): self.x = x self.y = y self.w = w self.h = h self.color = color self.text = font.render(text, 1, (0, 0, 0)) def hover(self, pos): if self.x <= pos[0] <= self.x + ...